repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Esri/arcgis-runtime-samples-android | kotlin/route-around-barriers/src/main/java/com/esri/arcgisruntime/sample/routearoundbarriers/MainActivity.kt | 1 | 19077 | /*
* Copyright 2020 Esri
*
* 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.esri.arcgisruntime.sample.routearoundbarriers
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.routearoundbarriers.databinding.ActivityMainBinding
import com.esri.arcgisruntime.symbology.CompositeSymbol
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol
import com.esri.arcgisruntime.symbology.SimpleFillSymbol
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleRenderer
import com.esri.arcgisruntime.symbology.TextSymbol
import com.esri.arcgisruntime.tasks.networkanalysis.DirectionManeuver
import com.esri.arcgisruntime.tasks.networkanalysis.PolygonBarrier
import com.esri.arcgisruntime.tasks.networkanalysis.Route
import com.esri.arcgisruntime.tasks.networkanalysis.RouteParameters
import com.esri.arcgisruntime.tasks.networkanalysis.RouteResult
import com.esri.arcgisruntime.tasks.networkanalysis.RouteTask
import com.esri.arcgisruntime.tasks.networkanalysis.Stop
import com.google.android.material.bottomsheet.BottomSheetBehavior
import kotlin.math.roundToInt
class MainActivity : AppCompatActivity() {
private val TAG: String = MainActivity::class.java.simpleName
private var bottomSheetBehavior: BottomSheetBehavior<View>? = null
private var routeTask: RouteTask? = null
private var routeParameters: RouteParameters? = null
private var pinSymbol: PictureMarkerSymbol? = null
private val routeGraphicsOverlay by lazy { GraphicsOverlay() }
private val stopsGraphicsOverlay by lazy { GraphicsOverlay() }
private val barriersGraphicsOverlay by lazy { GraphicsOverlay() }
private val stopList by lazy { mutableListOf<Stop>() }
private val barrierList by lazy { mutableListOf<PolygonBarrier>() }
private val directionsList by lazy { mutableListOf<DirectionManeuver>() }
private val routeLineSymbol by lazy {
SimpleLineSymbol(
SimpleLineSymbol.Style.SOLID,
Color.BLUE,
5.0f
)
}
private val barrierSymbol by lazy {
SimpleFillSymbol(
SimpleFillSymbol.Style.DIAGONAL_CROSS,
Color.RED,
null
)
}
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val mapViewContainer: ConstraintLayout by lazy {
activityMainBinding.mapViewContainer
}
private val resetButton: Button by lazy {
activityMainBinding.resetButton
}
private val bottomSheet: LinearLayout by lazy {
activityMainBinding.bottomSheet.bottomSheetLayout
}
private val header: ConstraintLayout by lazy {
activityMainBinding.bottomSheet.header
}
private val imageView: ImageView by lazy {
activityMainBinding.bottomSheet.imageView
}
private val addStopButton: ToggleButton by lazy {
activityMainBinding.bottomSheet.addStopButton
}
private val addBarrierButton: ToggleButton by lazy {
activityMainBinding.bottomSheet.addBarrierButton
}
private val reorderCheckBox: CheckBox by lazy {
activityMainBinding.bottomSheet.reorderCheckBox
}
private val preserveFirstStopCheckBox: CheckBox by lazy {
activityMainBinding.bottomSheet.preserveFirstStopCheckBox
}
private val preserveLastStopCheckBox: CheckBox by lazy {
activityMainBinding.bottomSheet.preserveLastStopCheckBox
}
private val directionsTextView: TextView by lazy {
activityMainBinding.bottomSheet.directionsTextView
}
private val directionsListView: ListView by lazy {
activityMainBinding.bottomSheet.directionsListView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// create simple renderer for routes, and set it to use the line symbol
routeGraphicsOverlay.renderer = SimpleRenderer().apply {
symbol = routeLineSymbol
}
mapView.apply {
// add a map with the streets basemap to the map view, centered on San Diego
map = ArcGISMap(BasemapStyle.ARCGIS_STREETS)
// center on San Diego
setViewpoint(Viewpoint(32.7270, -117.1750, 40000.0))
// add the graphics overlays to the map view
graphicsOverlays.addAll(
listOf(stopsGraphicsOverlay, barriersGraphicsOverlay, routeGraphicsOverlay)
)
onTouchListener = object : DefaultMapViewOnTouchListener(this@MainActivity, mapView) {
override fun onSingleTapConfirmed(motionEvent: MotionEvent): Boolean {
val screenPoint =
android.graphics.Point(
motionEvent.x.roundToInt(),
motionEvent.y.roundToInt()
)
addStopOrBarrier(screenPoint)
return true
}
}
}
// create a new picture marker from a pin drawable
pinSymbol = PictureMarkerSymbol.createAsync(
ContextCompat.getDrawable(
this,
R.drawable.pin_symbol
) as BitmapDrawable
).get().apply {
width = 30f
height = 30f
offsetY = 20f
}
// create route task from San Diego service
routeTask = RouteTask(
this,
"https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route"
).apply {
addDoneLoadingListener {
if (loadStatus == LoadStatus.LOADED) {
// get default route parameters
val routeParametersFuture = createDefaultParametersAsync()
routeParametersFuture.addDoneListener {
try {
routeParameters = routeParametersFuture.get().apply {
// set flags to return stops and directions
isReturnStops = true
isReturnDirections = true
}
} catch (e: Exception) {
Log.e(TAG, "Cannot create RouteTask parameters " + e.message)
}
}
} else {
Log.e(TAG, "Unable to load RouteTask $loadStatus")
}
}
}
routeTask?.loadAsync()
// shrink the map view so it is not hidden under the bottom sheet header
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet)
(mapViewContainer.layoutParams as CoordinatorLayout.LayoutParams).bottomMargin =
(bottomSheetBehavior as BottomSheetBehavior<View>).peekHeight
bottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
bottomSheet.apply {
// expand or collapse the bottom sheet when the header is clicked
header.setOnClickListener {
bottomSheetBehavior?.state = when (bottomSheetBehavior?.state) {
BottomSheetBehavior.STATE_COLLAPSED -> BottomSheetBehavior.STATE_HALF_EXPANDED
else -> BottomSheetBehavior.STATE_COLLAPSED
}
}
// rotate the arrow so it starts off in the correct rotation
imageView.rotation = 180f
}
// change button toggle state on click
addStopButton.setOnClickListener { addBarrierButton.isChecked = false }
addBarrierButton.setOnClickListener { addStopButton.isChecked = false }
// solve route on checkbox change state
reorderCheckBox.setOnCheckedChangeListener { _, _ -> createAndDisplayRoute() }
preserveFirstStopCheckBox.setOnCheckedChangeListener { _, _ -> createAndDisplayRoute() }
preserveLastStopCheckBox.setOnCheckedChangeListener { _, _ -> createAndDisplayRoute() }
// start sample with add stop button true
addStopButton.isChecked = true
}
/**
* Add a stop or a point to the correct graphics overlay depending on which button is currently
* checked.
*
* @param screenPoint at which to create a stop or point
*/
private fun addStopOrBarrier(screenPoint: android.graphics.Point) {
// convert screen point to map point
val mapPoint = mapView.screenToLocation(screenPoint)
// normalize geometry - important for geometries that will be sent to a server for processing
val normalizedPoint = GeometryEngine.normalizeCentralMeridian(mapPoint) as Point
// clear the displayed route, if it exists, since it might not be up to date any more
routeGraphicsOverlay.graphics.clear()
if (addStopButton.isChecked) {
// use the clicked map point to construct a stop
val stopPoint =
Stop(Point(normalizedPoint.x, normalizedPoint.y, mapPoint.spatialReference))
// add the new stop to the list of stops
stopList.add(stopPoint)
// create a marker symbol and graphics, and add the graphics to the graphics overlay
stopsGraphicsOverlay.graphics.add(
Graphic(
mapPoint,
createCompositeStopSymbol(stopList.size)
)
)
} else if (addBarrierButton.isChecked) {
// create a buffered polygon around the clicked point
val bufferedBarrierPolygon = GeometryEngine.buffer(mapPoint, 200.0)
// create a polygon barrier for the routing task, and add it to the list of barriers
barrierList.add(PolygonBarrier(bufferedBarrierPolygon))
// build graphics for the barrier and add it to the graphics overlay
barriersGraphicsOverlay.graphics.add(Graphic(bufferedBarrierPolygon, barrierSymbol))
}
createAndDisplayRoute()
}
/**
* Create route parameters and a route task from them. Display the route result geometry as a
* graphic and call showDirectionsInBottomSheet which shows directions in a list view.
*/
private fun createAndDisplayRoute() {
if (stopList.size < 2) {
// clear the directions list since no route is displayed
directionsList.clear()
return
}
// clear the previous route from the graphics overlay, if it exists
routeGraphicsOverlay.graphics.clear()
// clear the directions list from the directions list view, if they exist
directionsList.clear()
routeParameters?.apply {
// add the existing stops and barriers to the route parameters
setStops(stopList)
setPolygonBarriers(barrierList)
// apply the requested route finding parameters
isFindBestSequence = reorderCheckBox.isChecked
isPreserveFirstStop = preserveFirstStopCheckBox.isChecked
isPreserveLastStop = preserveLastStopCheckBox.isChecked
}
// solve the route task
val routeResultFuture = routeTask?.solveRouteAsync(routeParameters)
routeResultFuture?.addDoneListener {
try {
val routeResult: RouteResult = routeResultFuture.get()
if (routeResult.routes.isNotEmpty()) {
// get the first route result
val firstRoute: Route = routeResult.routes[0]
// create a graphic for the route and add it to the graphics overlay
val routeGraphic = Graphic(firstRoute.routeGeometry)
routeGraphicsOverlay.graphics.add(routeGraphic)
// get the direction text for each maneuver and add them to the list to display
directionsList.addAll(firstRoute.directionManeuvers)
showDirectionsInBottomSheet()
} else {
Toast.makeText(this, "No routes found.", Toast.LENGTH_LONG).show()
}
} catch (e: Exception) {
val error = "Solve route task failed: " + e.message
Log.e(TAG, error)
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
}
// show the reset button
resetButton.visibility = VISIBLE
}
}
/**
* Clear all stops and polygon barriers from the route parameters, stop and barrier
* lists and all graphics overlays. Also hide the directions list view and show the control
* layout.
*
* @param reset button which calls this method
*/
fun clearRouteAndGraphics(reset: View) {
// clear stops from route parameters and stops list
routeParameters?.clearStops()
stopList.clear()
// clear barriers from route parameters and barriers list
routeParameters?.clearPolygonBarriers()
barrierList.clear()
// clear the directions list
directionsList.clear()
// clear all graphics overlays
mapView.graphicsOverlays.forEach { it.graphics.clear() }
// hide the reset button and directions list
resetButton.visibility = GONE
// hide the directions
directionsTextView.visibility = GONE
directionsListView.visibility = GONE
}
/**
* Create a composite symbol consisting of a pin graphic overlaid with a particular stop number.
*
* @param stopNumber to overlay the pin symbol
* @return a composite symbol consisting of the pin graphic overlaid with an the stop number
*/
private fun createCompositeStopSymbol(stopNumber: Int): CompositeSymbol {
// determine the stop number and create a new label
val stopTextSymbol = TextSymbol(
16f,
stopNumber.toString(),
-0x1,
TextSymbol.HorizontalAlignment.CENTER,
TextSymbol.VerticalAlignment.BOTTOM
)
stopTextSymbol.offsetY = pinSymbol?.height as Float / 2
// construct a composite symbol out of the pin and text symbols, and return it
return CompositeSymbol(listOf(pinSymbol, stopTextSymbol))
}
/**
* Creates a bottom sheet to display a list of direction maneuvers.
*/
private fun showDirectionsInBottomSheet() {
// show the directions list view
directionsTextView.visibility = VISIBLE
directionsListView.visibility = VISIBLE
// create a bottom sheet behavior from the bottom sheet view in the main layout
bottomSheetBehavior?.apply {
// animate the arrow when the bottom sheet slides
addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
override fun onSlide(bottomSheet: View, slideOffset: Float) {
imageView.rotation = slideOffset * 180f
}
override fun onStateChanged(bottomSheet: View, newState: Int) {
imageView.rotation = when (newState) {
BottomSheetBehavior.STATE_EXPANDED -> 180f
else -> imageView.rotation
}
}
})
}
directionsListView.apply {
// Set the adapter for the list view
adapter = ArrayAdapter(
this@MainActivity,
android.R.layout.simple_list_item_1,
directionsList.map { it.directionText })
// when the user taps a maneuver, set the viewpoint to that portion of the route
onItemClickListener =
AdapterView.OnItemClickListener { _, _, position, _ ->
// remove any graphics that are not the original (blue) route graphic
if (routeGraphicsOverlay.graphics.size > 1) {
routeGraphicsOverlay.graphics.removeAt(routeGraphicsOverlay.graphics.size - 1)
}
// set the viewpoint to the selected maneuver
val geometry = directionsList[position].geometry
mapView.setViewpointAsync(Viewpoint(geometry.extent, 20.0), 1f)
// create a graphic with a symbol for the maneuver and add it to the graphics overlay
val selectedRouteSymbol = SimpleLineSymbol(
SimpleLineSymbol.Style.SOLID,
Color.GREEN, 5f
)
routeGraphicsOverlay.graphics.add(Graphic(geometry, selectedRouteSymbol))
// collapse the bottom sheet
bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
// allow the list view to scroll within bottom sheet
isNestedScrollingEnabled = true
}
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | 5cf4feddf73b6fd72c789ae791a4ee5d | 40.114224 | 113 | 0.649893 | 5.548866 | false | false | false | false |
KotlinPorts/pooled-client | db-async-common/src/main/kotlin/com/github/mauricio/async/db/util/ByteBufferUtils.kt | 2 | 3407 | /*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares 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.github.mauricio.async.db.util
import java.nio.charset.Charset
import java.nio.ByteOrder
import io.netty.buffer.Unpooled
import io.netty.buffer.ByteBuf
object ByteBufferUtils {
fun writeLength(buffer: ByteBuf) {
val length = buffer.writerIndex() - 1
buffer.markWriterIndex()
buffer.writerIndex(1)
buffer.writeInt(length)
buffer.resetWriterIndex()
}
fun writeCString(content: String, b: ByteBuf, charset: Charset) {
b.writeBytes(content.toByteArray(charset))
b.writeByte(0)
}
fun writeSizedString(content: String, b: ByteBuf, charset: Charset) {
val bytes = content.toByteArray(charset)
b.writeByte(bytes.size)
b.writeBytes(bytes)
}
fun readCString(b: ByteBuf, charset: Charset): String {
b.markReaderIndex()
var byte: Byte = 0
var count = 0
do {
byte = b.readByte()
count += 1
} while (byte != 0.toByte())
b.resetReaderIndex()
val result = b.toString(b.readerIndex(), count - 1, charset)
b.readerIndex(b.readerIndex() + count)
return result
}
fun readUntilEOF(b: ByteBuf, charset: Charset): String {
if (b.readableBytes() == 0) {
return ""
}
b.markReaderIndex()
var byte: Byte = -1
var count = 0
var offset = 1
while (byte != 0.toByte()) {
if (b.readableBytes() > 0) {
byte = b.readByte()
count += 1
} else {
byte = 0
offset = 0
}
}
b.resetReaderIndex()
val result = b.toString(b.readerIndex(), count - offset, charset)
b.readerIndex(b.readerIndex() + count)
return result
}
fun read3BytesInt(b: ByteBuf): Int =
(b.readByte().toInt() and 0xff) or
((b.readByte().toInt() and 0xff) shl 8) or
((b.readByte().toInt() and 0xff) shl 16)
fun write3BytesInt(b: ByteBuf, value: Int) {
b.writeByte(value and 0xff)
b.writeByte(value shl 8)
b.writeByte(value shl 16)
}
fun writePacketLength(buffer: ByteBuf, sequence: Int = 1) {
val length = buffer.writerIndex() - 4
buffer.markWriterIndex()
buffer.writerIndex(0)
write3BytesInt(buffer, length)
buffer.writeByte(sequence)
buffer.resetWriterIndex()
}
fun packetBuffer(estimate: Int = 1024): ByteBuf {
val buffer = mysqlBuffer(estimate)
buffer.writeInt(0)
return buffer
}
fun mysqlBuffer(estimate: Int = 1024): ByteBuf =
Unpooled.buffer(estimate).order(ByteOrder.LITTLE_ENDIAN)
}
| apache-2.0 | ef7d781eb40d07c7084e9a88f2d3b35d | 25.601563 | 78 | 0.600587 | 4.188192 | false | false | false | false |
gradle/gradle | build-logic/binary-compatibility/src/test/kotlin/gradlebuild/binarycompatibility/KotlinInternalFilteringTest.kt | 3 | 6131 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 gradlebuild.binarycompatibility
import org.junit.Test
/**
* Asserts Kotlin `internal` members are filtered from the comparison.
*/
class KotlinInternalFilteringTest : AbstractBinaryCompatibilityTest() {
private
val internalMembers = """
internal fun foo() {}
internal val bar = "bar"
internal var bazar = "bazar"
internal fun String.fooExt() {}
internal fun Int.fooExt() {}
internal val String.barExt: String
get() = "bar"
internal var Int.bazarExt: String
get() = "bar"
set(value) = Unit
"""
private
val publicMembers = """
fun foo() {}
val bar = "bar"
var bazar = "bazar"
fun String.fooExt() {}
fun Int.fooExt() {}
val String.barExt: String
get() = "bar"
var Int.bazarExt: String
get() = "bar"
set(value) = Unit
"""
private
val existingSource = """
class ExistingClass {
class ExistingNestedClass
}
val valTurnedIntoVar: String
get() = ""
typealias ExistingTypeAlias = String
"""
private
val internalSource = """
$internalMembers
class ExistingClass() {
internal constructor(bar: String) : this()
$internalMembers
class ExistingNestedClass {
$internalMembers
}
}
typealias ExistingTypeAlias = String
var valTurnedIntoVar: String
get() = ""
internal set(value) = Unit
internal const val cathedral = "cathedral"
internal class AddedClass() {
constructor(bar: ExistingTypeAlias) : this()
$publicMembers
}
internal object AddedObject {
$publicMembers
const val cathedral = "cathedral"
}
internal enum class AddedEnum {
FOO;
$publicMembers
}
"""
private
val publicSource = """
$publicMembers
class ExistingClass() {
constructor(bar: String) : this()
$publicMembers
class ExistingNestedClass {
$publicMembers
}
}
typealias ExistingTypeAlias = String
var valTurnedIntoVar: String
get() = ""
set(value) = Unit
const val cathedral = "cathedral"
class AddedClass() {
constructor(bar: ExistingTypeAlias) : this()
$publicMembers
}
object AddedObject {
$publicMembers
const val cathedral = "cathedral"
}
enum class AddedEnum {
FOO;
$publicMembers
}
"""
@Test
fun `added internal members are filtered from the comparison`() {
checkBinaryCompatibleKotlin(
v1 = existingSource,
v2 = internalSource
).assertEmptyReport()
}
@Test
fun `existing internal members made public appear as added`() {
checkNotBinaryCompatibleKotlin(
v1 = internalSource,
v2 = publicSource
).apply {
assertHasErrors(
*reportedMembers.map {
added(it.first, it.second)
}.toTypedArray()
)
assertHasNoWarning()
assertHasNoInformation()
}
}
@Test
fun `existing public members made internal appear as removed`() {
checkNotBinaryCompatibleKotlin(
v1 = publicSource,
v2 = internalSource
).apply {
assertHasErrors(
*reportedMembers.map {
removed(it.first, it.second)
}.toTypedArray()
)
assertHasNoWarning()
assertHasNoInformation()
}
}
private
val reportedMembers = listOf(
"Class" to "AddedClass"
) + reportedMembersFor("AddedClass") + listOf(
"Constructor" to "AddedClass(java.lang.String)",
"Constructor" to "AddedClass()",
"Class" to "AddedEnum",
"Field" to "FOO"
) + reportedMembersFor("AddedEnum") + listOf(
"Method" to "AddedEnum.valueOf(java.lang.String)",
"Method" to "AddedEnum.values()",
"Class" to "AddedObject",
"Field" to "INSTANCE",
"Field" to "cathedral"
) + reportedMembersFor("AddedObject") + reportedMembersFor("ExistingClass") + listOf(
"Constructor" to "ExistingClass(java.lang.String)"
) + reportedMembersFor("ExistingClass${'$'}ExistingNestedClass") + listOf(
"Field" to "cathedral"
) + reportedMembersFor("SourceKt") + listOf(
"Method" to "SourceKt.setValTurnedIntoVar(java.lang.String)"
)
private
fun reportedMembersFor(containingType: String) =
listOf(
"Method" to "$containingType.foo()",
"Method" to "$containingType.fooExt(java.lang.String)",
"Method" to "$containingType.fooExt(int)",
"Method" to "$containingType.getBar()",
"Method" to "$containingType.getBarExt(java.lang.String)",
"Method" to "$containingType.getBazar()",
"Method" to "$containingType.getBazarExt(int)",
"Method" to "$containingType.setBazar(java.lang.String)",
"Method" to "$containingType.setBazarExt(int,java.lang.String)"
)
}
| apache-2.0 | a0ac92c049b35ed33ce146edf6737b7d | 22.856031 | 89 | 0.562225 | 4.960356 | false | false | false | false |
rodrigo196/kotlin-marvel-api-client | app/src/main/java/br/com/bulgasoftwares/feedreader/extensions/ActivityExtensions.kt | 1 | 1236 | package br.com.bulgasoftwares.feedreader.extensions
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
inline fun <reified T : Any> Activity.launchActivity(
requestCode: Int = -1,
options: Bundle? = null,
noinline init: Intent.() -> Unit = {}) {
val intent = newIntent<T>(this)
intent.init()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
startActivityForResult(intent, requestCode, options)
} else {
startActivityForResult(intent, requestCode)
}
}
inline fun <reified T : Any> Context.launchActivity(
options: Bundle? = null,
noinline init: Intent.() -> Unit = {}) {
val intent = newIntent<T>(this)
intent.init()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
startActivity(intent, options)
} else {
startActivity(intent)
}
}
inline fun <reified T : Any> newIntent(context: Context): Intent =
Intent(context, T::class.java)
val Activity.analytics: FirebaseAnalytics
get() {
return FirebaseAnalytics.getInstance(this)
} | apache-2.0 | 146257dde12fdf6bf5719703fddbb0d4 | 27.767442 | 66 | 0.675566 | 4.052459 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/business/test/adapter/RouterDelegate.kt | 1 | 814 | package com.binlly.fastpeak.business.test.adapter
import android.content.Context
import android.widget.TextView
import com.binlly.fastpeak.R
import com.binlly.fastpeak.base.adapter.BaseDelegate
import com.binlly.fastpeak.business.test.model.TestModel
import com.chad.library.adapter.base.BaseViewHolder
/**
* Created by binlly on 2017/5/13.
*/
class RouterDelegate(context: Context): BaseDelegate<TestModel>(context) {
override val layoutResId: Int
get() = R.layout.test_item_key_value
override fun childConvert(holder: BaseViewHolder, item: TestModel) {
val key = holder.getView<TextView>(R.id.key)
val value = holder.getView<TextView>(R.id.value)
key.text = item.router.key
value.text = item.router.value
value.setTextColor(item.valueColor)
}
} | mit | 4d29247c180d026983e70a2553949a35 | 29.185185 | 74 | 0.734644 | 3.768519 | false | true | false | false |
industrial-data-space/trusted-connector | ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/CORSResponseFilter.kt | 1 | 1849 | /*-
* ========================LICENSE_START=================================
* ids-webconsole
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api
import java.io.IOException
import javax.ws.rs.container.ContainerRequestContext
import javax.ws.rs.container.ContainerResponseContext
import javax.ws.rs.container.ContainerResponseFilter
import javax.ws.rs.ext.Provider
/**
* This filter adds Cross-Origin Resource Sharing (CORS) headers to each response.
*
* @author Christian Banse
*/
@Provider
class CORSResponseFilter : ContainerResponseFilter {
@Throws(IOException::class)
override fun filter(
requestContext: ContainerRequestContext,
responseContext: ContainerResponseContext
) {
val headers = responseContext.headers
// allow AJAX from everywhere
headers.add("Access-Control-Allow-Origin", "*")
headers.add(
"Access-Control-Allow-Headers",
"origin, content-type, accept, authorization, X-Requested-With"
)
headers.add("Access-Control-Allow-Credentials", "true")
headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
}
}
| apache-2.0 | 235d2641e45ed527a6ee25742bf9309c | 35.254902 | 92 | 0.66901 | 4.476998 | false | false | false | false |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/widget/PicOfDayAppWidgetUnitTests.kt | 6 | 3358 | package fr.free.nrw.commons.widget
import android.appwidget.AppWidgetManager
import android.content.Context
import android.widget.RemoteViews
import com.facebook.imagepipeline.core.ImagePipelineFactory
import com.facebook.soloader.SoLoader
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.TestAppAdapter
import fr.free.nrw.commons.TestCommonsApplication
import fr.free.nrw.commons.media.MediaClient
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.powermock.reflect.Whitebox
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.wikipedia.AppAdapter
import java.lang.reflect.Method
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
class PicOfDayAppWidgetUnitTests {
private lateinit var widget: PicOfDayAppWidget
private lateinit var context: Context
@Mock
private lateinit var views: RemoteViews
@Mock
private lateinit var appWidgetManager: AppWidgetManager
@Mock
private lateinit var mediaClient: MediaClient
@Mock
private lateinit var compositeDisposable: CompositeDisposable
@Before
fun setUp() {
AppAdapter.set(TestAppAdapter())
context = RuntimeEnvironment.application.applicationContext
SoLoader.setInTestMode()
ImagePipelineFactory.initialize(context)
MockitoAnnotations.initMocks(this)
widget = PicOfDayAppWidget()
Whitebox.setInternalState(widget, "compositeDisposable", compositeDisposable)
Whitebox.setInternalState(widget, "mediaClient", mediaClient)
}
@Test
@Throws(Exception::class)
fun testWidgetNotNull() {
Assert.assertNotNull(widget)
}
@Test
@Throws(Exception::class)
fun testOnDisabled() {
widget.onDisabled(context)
}
@Test
@Throws(Exception::class)
fun testOnEnabled() {
widget.onEnabled(context)
}
@Test
@Throws(Exception::class)
fun testOnUpdate() {
widget.onUpdate(context, appWidgetManager, intArrayOf(1))
}
@Test
@Throws(Exception::class)
fun testLoadImageFromUrl() {
val method: Method = PicOfDayAppWidget::class.java.getDeclaredMethod(
"loadImageFromUrl",
String::class.java,
Context::class.java,
RemoteViews::class.java,
AppWidgetManager::class.java,
Int::class.java
)
method.isAccessible = true
method.invoke(widget, "", context, views, appWidgetManager, 1)
}
@Test
@Throws(Exception::class)
fun testLoadPictureOfTheDay() {
`when`(mediaClient.getPictureOfTheDay()).thenReturn(Single.just(Media()))
val method: Method = PicOfDayAppWidget::class.java.getDeclaredMethod(
"loadPictureOfTheDay",
Context::class.java,
RemoteViews::class.java,
AppWidgetManager::class.java,
Int::class.java
)
method.isAccessible = true
method.invoke(widget, context, views, appWidgetManager, 1)
}
} | apache-2.0 | e33d0e6cd81b869d7ae2d34675d91ec1 | 28.725664 | 85 | 0.712031 | 4.756374 | false | true | false | false |
danrien/projectBlue | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/builder/GivenServerIsFoundViaLookup/AndAnAuthKeyIsProvided/WhenScanningForUrls.kt | 2 | 2613 | package com.lasthopesoftware.bluewater.client.connection.builder.GivenServerIsFoundViaLookup.AndAnAuthKeyIsProvided
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.builder.UrlScanner
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.LookupServers
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.ServerInfo
import com.lasthopesoftware.bluewater.client.connection.okhttp.OkHttpFactory
import com.lasthopesoftware.bluewater.client.connection.settings.ConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.settings.LookupConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.testing.TestConnections
import com.lasthopesoftware.bluewater.client.connection.url.IUrlProvider
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
class WhenScanningForUrls {
companion object {
private var urlProvider: IUrlProvider? = null
@BeforeClass
@JvmStatic
fun before() {
val connectionTester = mockk<TestConnections>()
every { connectionTester.promiseIsConnectionPossible(any()) } returns false.toPromise()
every { connectionTester.promiseIsConnectionPossible(match { a -> "http://1.2.3.4:143/MCWS/v1/" == a.urlProvider.baseUrl.toString() && "gooey" == a.urlProvider.authCode }) } returns true.toPromise()
val serverLookup = mockk<LookupServers>()
every { serverLookup.promiseServerInformation(LibraryId(15)) } returns Promise(
ServerInfo(
143,
null,
"1.2.3.4", emptyList(), emptyList(),
null
)
)
val connectionSettingsLookup = mockk<LookupConnectionSettings>()
every { connectionSettingsLookup.lookupConnectionSettings(LibraryId(15)) } returns ConnectionSettings(accessCode = "gooPc", userName = "myuser", password = "myPass").toPromise()
val urlScanner = UrlScanner(
{ "gooey" },
connectionTester,
serverLookup,
connectionSettingsLookup,
OkHttpFactory
)
urlProvider = urlScanner.promiseBuiltUrlProvider(LibraryId(15)).toFuture().get()
}
}
@Test
fun thenTheUrlProviderIsReturned() {
assertThat(urlProvider).isNotNull
}
@Test
fun thenTheBaseUrlIsCorrect() {
assertThat(urlProvider?.baseUrl.toString()).isEqualTo("http://1.2.3.4:143/MCWS/v1/")
}
}
| lgpl-3.0 | e5ef313364b73623d7556ebb3283ed51 | 38 | 201 | 0.794872 | 4.221325 | false | true | false | false |
ryuta46/eval-spec-maker | project/src/main/kotlin/com/ryuta46/evalspecmaker/util/Logger.kt | 1 | 1297 | package com.ryuta46.evalspecmaker.util
class Logger(val tag: String) {
companion object {
val LOG_LEVEL_NONE = 0
val LOG_LEVEL_ERROR = 1
val LOG_LEVEL_WARN = 2
val LOG_LEVEL_INFO = 3
val LOG_LEVEL_DEBUG = 4
val LOG_LEVEL_VERBOSE = 5
var level = LOG_LEVEL_NONE
}
fun e(message: String) {
if (level >= LOG_LEVEL_ERROR) println("|ERR|$tag|$message")
}
fun w(message: String) {
if (level >= LOG_LEVEL_WARN) println("|WRN|$tag|$message")
}
fun i(message: String) {
if (level >= LOG_LEVEL_INFO) println("|INF|$tag|$message")
}
fun d(message: String) {
if (level >= LOG_LEVEL_DEBUG) println("|DBG|$tag|$message")
}
fun v(message: String) {
if (level >= LOG_LEVEL_VERBOSE) println("|VRB|$tag|$message")
}
inline fun <T> trace(body: () -> T): T {
val callerName = if (level >= LOG_LEVEL_DEBUG) {
Throwable().stackTrace[0].methodName
} else {
null
}
try {
callerName?.let {
d("$callerName start")
}
return body()
}
finally {
callerName?.let {
d("$callerName end")
}
}
}
}
| mit | b9aefac7edf0822431e215e6703fcb93 | 22.160714 | 69 | 0.498072 | 3.781341 | false | false | false | false |
RyanAndroidTaylor/Rapido | rapidocommon/src/main/java/com/izeni/rapidocommon/recycler/MultiTypeSectionedAdapter.kt | 1 | 4044 | package com.izeni.rapidocommon.recycler
import android.support.annotation.LayoutRes
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.izeni.rapidocommon.view.inflate
import com.izeni.rapidocommon.recycler.SectionManager.SectionData
/**
* Created by ner on 1/2/17.
*/
//TODO Need to make it so section headers span the recycler view when using a GridLayoutManager
abstract class MultiTypeSectionedAdapter(sections: List<Section<*>>,
private val sectionHeader: SectionedViewHolderData<SectionData>? = null) :
RecyclerView.Adapter<SectionedViewHolder<*>>() {
companion object {
val HEADER = -1
}
private val sectionManager by lazy { SectionManager(this, sections) }
init {
if (sectionHeader == null && sectionManager.hasHeaders())
throw IllegalStateException("One of your sections has a header but there was no SectionedViewHolderData passed for section headers")
}
override fun getItemViewType(position: Int): Int {
return sectionManager.getViewHolderType(position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SectionedViewHolder<*> {
if (viewType == HEADER)
return sectionHeader!!.createViewHolder(parent)
else
return sectionManager.createViewHolder(parent, viewType)
}
override fun onBindViewHolder(holder: SectionedViewHolder<*>, position: Int) {
val type = getItemViewType(position)
if (type == HEADER)
sectionManager.bindHeader(holder, position)
else
sectionManager.bind(holder, position)
}
override fun getItemCount() = sectionManager.count
fun collapseSection(sectionType: Int) {
sectionManager.collapseSection(sectionType)
}
fun expandSection(sectionType: Int) {
sectionManager.expandSection(sectionType)
}
fun addItem(sectionType: Int, item: Any) {
sectionManager.addItem(sectionType, item)
}
fun addItemAt(index: Int, sectionType: Int, item: Any) {
sectionManager.addItemAt(index, sectionType, item)
}
fun addItems(sectionType: Int, items: List<Any>) {
sectionManager.addItems(sectionType, items)
}
fun removeItem(sectionType: Int, item: Any) {
sectionManager.removeItem(sectionType, item)
}
class SectionedViewHolderData<T>(@LayoutRes val layoutId: Int, val viewHolder: (View) -> SectionedViewHolder<T>) {
fun createViewHolder(parent: ViewGroup): SectionedViewHolder<T> {
return viewHolder(parent.inflate(layoutId))
}
}
@Suppress("UNCHECKED_CAST")
abstract class Section<T>(val type: Int,
private val items: MutableList<T>,
val viewHolderData: SectionedViewHolderData<T>,
val hasHeader: Boolean = false,
val isCollapsible: Boolean = false) {
val count: Int
get() = if (isCollapsed) 0 else items.size
val headerCount = if (hasHeader) 1 else 0
var isCollapsed = false
set(value) { if (isCollapsible) field = value }
fun bind(viewHolder: SectionedViewHolder<*>, position: Int) {
(viewHolder as SectionedViewHolder<T>).bind(items[position])
}
fun bindHeader(viewHolder: SectionedViewHolder<*>) {
(viewHolder as SectionedViewHolder<SectionData>).bind(SectionData(type, items.size, isCollapsed))
}
fun addItem(item: Any) {
items.add(item as T)
}
fun addItemAt(index: Int, item: Any) {
items.add(index, item as T)
}
fun addItems(items: List<Any>) {
this.items.addAll(items as List<T>)
}
fun removeItem(item: Any): Int {
val index = items.indexOf(item as T)
items.removeAt(index)
return index
}
}
} | mit | 208718b9a0ae5ccd432dc64be66a8272 | 31.103175 | 144 | 0.638477 | 4.992593 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/checksum.kt | 1 | 7354 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Checksum
import org.apache.tools.ant.types.ResourceCollection
import org.apache.tools.ant.types.selectors.AndSelector
import org.apache.tools.ant.types.selectors.ContainsRegexpSelector
import org.apache.tools.ant.types.selectors.ContainsSelector
import org.apache.tools.ant.types.selectors.DateSelector
import org.apache.tools.ant.types.selectors.DependSelector
import org.apache.tools.ant.types.selectors.DepthSelector
import org.apache.tools.ant.types.selectors.DifferentSelector
import org.apache.tools.ant.types.selectors.ExtendSelector
import org.apache.tools.ant.types.selectors.FileSelector
import org.apache.tools.ant.types.selectors.FilenameSelector
import org.apache.tools.ant.types.selectors.MajoritySelector
import org.apache.tools.ant.types.selectors.NoneSelector
import org.apache.tools.ant.types.selectors.NotSelector
import org.apache.tools.ant.types.selectors.OrSelector
import org.apache.tools.ant.types.selectors.PresentSelector
import org.apache.tools.ant.types.selectors.SelectSelector
import org.apache.tools.ant.types.selectors.SizeSelector
import org.apache.tools.ant.types.selectors.TypeSelector
import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Ant.checksum(
file: String? = null,
todir: String? = null,
algorithm: String? = null,
provider: String? = null,
fileext: String? = null,
property: String? = null,
totalproperty: String? = null,
verifyproperty: String? = null,
forceoverwrite: Boolean? = null,
readbuffersize: Int? = null,
format: FormatElement? = null,
pattern: String? = null,
includes: String? = null,
excludes: String? = null,
defaultexcludes: Boolean? = null,
includesfile: String? = null,
excludesfile: String? = null,
casesensitive: Boolean? = null,
followsymlinks: Boolean? = null,
nested: (KChecksum.() -> Unit)? = null)
{
Checksum().execute("checksum") { task ->
if (file != null)
task.setFile(project.resolveFile(file))
if (todir != null)
task.setTodir(project.resolveFile(todir))
if (algorithm != null)
task.setAlgorithm(algorithm)
if (provider != null)
task.setProvider(provider)
if (fileext != null)
task.setFileext(fileext)
if (property != null)
task.setProperty(property)
if (totalproperty != null)
task.setTotalproperty(totalproperty)
if (verifyproperty != null)
task.setVerifyproperty(verifyproperty)
if (forceoverwrite != null)
task.setForceOverwrite(forceoverwrite)
if (readbuffersize != null)
task.setReadBufferSize(readbuffersize)
if (format != null)
task.setFormat(Checksum.FormatElement().apply { this.value = format.value })
if (pattern != null)
task.setPattern(pattern)
if (includes != null)
task.setIncludes(includes)
if (excludes != null)
task.setExcludes(excludes)
if (defaultexcludes != null)
task.setDefaultexcludes(defaultexcludes)
if (includesfile != null)
task.setIncludesfile(project.resolveFile(includesfile))
if (excludesfile != null)
task.setExcludesfile(project.resolveFile(excludesfile))
if (casesensitive != null)
task.setCaseSensitive(casesensitive)
if (followsymlinks != null)
task.setFollowSymlinks(followsymlinks)
if (nested != null)
nested(KChecksum(task))
}
}
class KChecksum(override val component: Checksum) :
IFileSelectorNested,
IResourceCollectionNested,
ISelectSelectorNested,
IAndSelectorNested,
IOrSelectorNested,
INotSelectorNested,
INoneSelectorNested,
IMajoritySelectorNested,
IDateSelectorNested,
ISizeSelectorNested,
IFilenameSelectorNested,
IExtendSelectorNested,
IContainsSelectorNested,
IPresentSelectorNested,
IDepthSelectorNested,
IDependSelectorNested,
IContainsRegexpSelectorNested,
IDifferentSelectorNested,
ITypeSelectorNested,
IModifiedSelectorNested
{
fun include(name: String? = null, If: String? = null, unless: String? = null) {
component.createInclude().apply {
_init(name, If, unless)
}
}
fun includesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createIncludesFile().apply {
_init(name, If, unless)
}
}
fun exclude(name: String? = null, If: String? = null, unless: String? = null) {
component.createExclude().apply {
_init(name, If, unless)
}
}
fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createExcludesFile().apply {
_init(name, If, unless)
}
}
fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) {
component.createPatternSet().apply {
component.project.setProjectReference(this)
_init(includes, excludes, includesfile, excludesfile, nested)
}
}
override fun _addFileSelector(value: FileSelector) = component.add(value)
override fun _addResourceCollection(value: ResourceCollection) = component.add(value)
override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value)
override fun _addAndSelector(value: AndSelector) = component.addAnd(value)
override fun _addOrSelector(value: OrSelector) = component.addOr(value)
override fun _addNotSelector(value: NotSelector) = component.addNot(value)
override fun _addNoneSelector(value: NoneSelector) = component.addNone(value)
override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value)
override fun _addDateSelector(value: DateSelector) = component.addDate(value)
override fun _addSizeSelector(value: SizeSelector) = component.addSize(value)
override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value)
override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value)
override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value)
override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value)
override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value)
override fun _addDependSelector(value: DependSelector) = component.addDepend(value)
override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value)
override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value)
override fun _addTypeSelector(value: TypeSelector) = component.addType(value)
override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value)
}
enum class FormatElement(val value: String) { CHECKSUM("CHECKSUM"), MD5SUM("MD5SUM"), SVF("SVF") }
| apache-2.0 | 19b7adaf7675250e7a97fad9be61d1cc | 39.629834 | 171 | 0.754691 | 3.752041 | false | false | false | false |
jitsi/jitsi-videobridge | jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/rtp/PaddingVideoPacket.kt | 1 | 2106 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.nlj.rtp
import org.jitsi.nlj.util.BufferPool
import org.jitsi.rtp.rtp.RtpHeader
class PaddingVideoPacket private constructor(
buffer: ByteArray,
offset: Int,
length: Int
) : VideoRtpPacket(buffer, offset, length) {
override fun clone(): PaddingVideoPacket =
throw NotImplementedError("clone() not supported for padding packets.")
companion object {
/**
* Creating a PaddingVideoPacket by directly grabbing a buffer in its
* ctor is problematic because we cannot clear the buffer we retrieve
* before calling the parent class' constructor. Because the buffer
* may contain invalid data, any attempts to parse it by parent class(es)
* could fail, so we use a helper here instead
*/
fun create(length: Int): PaddingVideoPacket {
val buf = BufferPool.getBuffer(length)
// It's possible we the buffer we pulled from the pool already has
// data in it, and we won't be overwriting it with anything so clear
// out the data
buf.fill(0, 0, length)
return PaddingVideoPacket(buf, 0, length).apply {
// Recalculate the header length now that we've zero'd everything out
// and set the fields
version = RtpHeader.VERSION
headerLength = RtpHeader.getTotalLength(buffer, offset)
paddingSize = payloadLength
}
}
}
}
| apache-2.0 | 11c6fbf66055a28597c46996f0015382 | 37.290909 | 85 | 0.660019 | 4.711409 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/observation/sync/AttachmentSyncWorker.kt | 1 | 4009 | package mil.nga.giat.mage.observation.sync
import android.content.Context
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.hilt.work.HiltWorker
import androidx.work.*
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import mil.nga.giat.mage.MageApplication
import mil.nga.giat.mage.R
import mil.nga.giat.mage.data.observation.AttachmentRepository
import mil.nga.giat.mage.sdk.datastore.observation.AttachmentHelper
import java.io.IOException
import java.net.HttpURLConnection
import java.util.concurrent.TimeUnit
@HiltWorker
class AttachmentSyncWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val attachmentRepository: AttachmentRepository
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
// Lock to ensure previous running work will complete when cancelled before new work is started.
return mutex.withLock {
val result = try {
syncAttachments()
} catch (e: Exception) {
Log.e(LOG_NAME, "Failed to sync attachments", e)
RESULT_RETRY_FLAG
}
if (result.containsFlag(RESULT_RETRY_FLAG)) Result.retry() else Result.success()
}
}
override suspend fun getForegroundInfo(): ForegroundInfo {
val notification = NotificationCompat.Builder(applicationContext, MageApplication.MAGE_NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_sync_preference_24dp)
.setContentTitle("Sync Attachments")
.setContentText("Pushing attachments to MAGE.")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.build()
return ForegroundInfo(ATTACHMENT_SYNC_NOTIFICATION_ID, notification)
}
private suspend fun syncAttachments(): Int {
var result = RESULT_SUCCESS_FLAG
val attachmentHelper = AttachmentHelper.getInstance(applicationContext)
for (attachment in attachmentHelper.dirtyAttachments.filter { !it.observation.remoteId.isNullOrEmpty() && it.url.isNullOrEmpty() }) {
val response = attachmentRepository.syncAttachment(attachment)
result = if (response.isSuccessful) {
Result.success()
} else {
if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
Result.failure()
} else {
Result.retry()
}
}.withFlag(result)
}
return result
}
private fun Result.withFlag(flag: Int): Int {
return when (this) {
is Result.Success -> RESULT_FAILURE_FLAG or flag
is Result.Retry -> RESULT_RETRY_FLAG or flag
else -> RESULT_SUCCESS_FLAG or flag
}
}
private fun Int.containsFlag(flag: Int): Boolean {
return (this or flag) == this
}
companion object {
private val LOG_NAME = AttachmentSyncWorker::class.java.simpleName
private const val RESULT_SUCCESS_FLAG = 0
private const val RESULT_FAILURE_FLAG = 1
private const val RESULT_RETRY_FLAG = 2
private const val ATTACHMENT_SYNC_WORK = "mil.nga.mage.ATTACHMENT_SYNC_WORK"
private const val ATTACHMENT_SYNC_NOTIFICATION_ID = 200
private val mutex = Mutex()
fun scheduleWork(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequest.Builder(AttachmentSyncWorker::class.java)
.setConstraints(constraints)
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.setBackoffCriteria(BackoffPolicy.LINEAR, 15, TimeUnit.SECONDS)
.build()
WorkManager
.getInstance(context)
.beginUniqueWork(ATTACHMENT_SYNC_WORK, ExistingWorkPolicy.REPLACE, request)
.enqueue()
}
}
} | apache-2.0 | e43acb9df4d003683d9d68cb67a1f7ca | 34.175439 | 139 | 0.686206 | 4.661628 | false | false | false | false |
wireapp/wire-android | app/src/main/java/com/waz/zclient/pages/extendedcursor/voicefilter2/WaveBinView.kt | 1 | 2895 | package com.waz.zclient.pages.extendedcursor.voicefilter2
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.waz.zclient.R
class WaveBinView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0):
View(context, attrs, defStyleAttr) {
private var duration: Long = 0
private var currentHead: Long = 0
private val activePaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val inactivePaint: Paint
private var levels: FloatArray? = null
private val binWidth: Int
private val binSpaceWidth: Int
init {
activePaint.color = Color.BLUE
inactivePaint = Paint(Paint.ANTI_ALIAS_FLAG)
inactivePaint.color = Color.WHITE
binWidth = resources.getDimensionPixelSize(R.dimen.wave_graph_bin_width)
binSpaceWidth = resources.getDimensionPixelSize(R.dimen.wave_graph_bin_space_width)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (levels == null) {
return
}
val maxNumOfLevels = levels!!.size
val size = levels!!.size
val totalBinWidth = size * binWidth + (size - 1) * binSpaceWidth
val height = canvas.height
val width = canvas.width
var currentX = (width - totalBinWidth) / 2
val breakPoint = (maxNumOfLevels.toFloat() * currentHead.toFloat() * 1.0f / duration).toInt()
for (i in 0 until breakPoint) {
if (i > maxNumOfLevels - 1) {
return
}
var lh = levels!![i] * height
if (lh < binWidth) {
lh = binWidth.toFloat()
}
val top = (height - lh) / 2
canvas.drawRect(
currentX.toFloat(),
top,
(currentX + binWidth).toFloat(),
(top + lh),
activePaint)
currentX += binWidth + binSpaceWidth
}
for (i in breakPoint until maxNumOfLevels) {
var lh = levels!![i] * height
if (lh < binWidth) {
lh = binWidth.toFloat()
}
val top = (height - lh) / 2
canvas.drawRect(
currentX.toFloat(),
top,
(currentX + binWidth).toFloat(),
(top + lh),
inactivePaint)
currentX += binWidth + binSpaceWidth
}
}
fun setAccentColor(accentColor: Int) {
activePaint.color = accentColor
}
fun setAudioLevels(levels: FloatArray) {
this.levels = levels
}
fun setAudioPlayingProgress(current: Long, total: Long) {
this.currentHead = current
this.duration = total
postInvalidate()
}
}
| gpl-3.0 | 06a17f8e362278772556a95b2a470801 | 28.242424 | 114 | 0.57962 | 4.632 | false | false | false | false |
vania-pooh/kotlin-algorithms | src/com/freaklius/kotlin/algorithms/sort/BucketSort.kt | 1 | 1464 | package com.freaklius.kotlin.algorithms.sort
import java.util.LinkedList
/**
* Bucket sort algorithm
* Average performance = O(n)
*/
class BucketSort : SortAlgorithm {
override fun sort(arr: Array<Long>): Array<Long> {
//Number of buckets can depend on input array size
val numberOfBuckets = if (arr.size > 100) Math.floor(arr.size / 10.0).toInt() else 10
val outputArray = arr
val sortArray = Array<LinkedList<Long>>(numberOfBuckets, { i -> LinkedList()}) //We need to store digits in range 0..9
val maxArrayValue = maximum(arr)
for (i in 0..arr.size - 1){
val value = arr[i]
var valueIndex = Math.floor((numberOfBuckets * (value / maxArrayValue)).toDouble()).toInt() // It's a number in range 0..9
if (valueIndex == arr.size){
valueIndex = arr.size - 1 //Maximum values go to the last bucket
}
sortArray[valueIndex].add(value)
}
var outputArrayIndex = 0
for (list in sortArray){
if (list.size > 0){
val arrayFromList = Array<Long>(list.size, { i -> list.get(i)})
for (value in InsertionSort().sort(arrayFromList)){
outputArray[outputArrayIndex] = value
outputArrayIndex++
}
}
}
return outputArray
}
override fun getName(): String {
return "BucketSort"
}
} | mit | 8a72f578a0a981fe2c911078d38ae03b | 34.731707 | 134 | 0.572404 | 4.293255 | false | false | false | false |
Kotlin/dokka | plugins/templating/src/main/kotlin/templates/JsonElementBasedTemplateProcessingStrategy.kt | 1 | 2601 | package org.jetbrains.dokka.allModulesPage.templates
import org.jetbrains.dokka.DokkaConfiguration.DokkaModuleDescription
import org.jetbrains.dokka.base.renderers.html.SearchRecord
import org.jetbrains.dokka.base.templating.AddToSearch
import org.jetbrains.dokka.base.templating.parseJson
import org.jetbrains.dokka.base.templating.toJsonString
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.templates.TemplateProcessingStrategy
import java.io.File
import java.util.concurrent.ConcurrentHashMap
abstract class BaseJsonNavigationTemplateProcessingStrategy(val context: DokkaContext) : TemplateProcessingStrategy {
abstract val navigationFileNameWithoutExtension: String
abstract val path: String
private val fragments = ConcurrentHashMap<String, List<SearchRecord>>()
open fun canProcess(file: File): Boolean =
file.extension == "json" && file.nameWithoutExtension == navigationFileNameWithoutExtension
override fun process(input: File, output: File, moduleContext: DokkaModuleDescription?): Boolean {
val canProcess = canProcess(input)
if (canProcess) {
runCatching { parseJson<AddToSearch>(input.readText()) }.getOrNull()?.let { command ->
moduleContext?.relativePathToOutputDirectory
?.relativeToOrSelf(context.configuration.outputDir)
?.let { key ->
fragments[key.toString()] = command.elements
}
} ?: fallbackToCopy(input, output)
}
return canProcess
}
override fun finish(output: File) {
if (fragments.isNotEmpty()) {
val content = toJsonString(fragments.entries.flatMap { (moduleName, navigation) ->
navigation.map { it.withResolvedLocation(moduleName) }
})
output.resolve(path).mkdirs()
output.resolve("$path/$navigationFileNameWithoutExtension.json").writeText(content)
}
}
private fun fallbackToCopy(input: File, output: File) {
context.logger.warn("Falling back to just copying ${input.name} file even though it should have been processed")
input.copyTo(output)
}
private fun SearchRecord.withResolvedLocation(moduleName: String): SearchRecord =
copy(location = "$moduleName/$location")
}
class PagesSearchTemplateStrategy(val dokkaContext: DokkaContext) :
BaseJsonNavigationTemplateProcessingStrategy(dokkaContext) {
override val navigationFileNameWithoutExtension: String = "pages"
override val path: String = "scripts"
}
| apache-2.0 | c982226d2d42ed3628b29120a2c1587a | 42.35 | 120 | 0.714725 | 5.160714 | false | false | false | false |
google/ksp | integration-tests/src/test/resources/on-error/on-error-processor/src/main/kotlin/NormalProcessor.kt | 1 | 1100 | import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
class NormalProcessor : SymbolProcessor {
lateinit var codeGenerator: CodeGenerator
lateinit var logger: KSPLogger
var rounds = 0
override fun onError() {
logger.error("NormalProcessor called error on $rounds")
}
fun init(
options: Map<String, String>,
kotlinVersion: KotlinVersion,
codeGenerator: CodeGenerator,
logger: KSPLogger
) {
this.logger = logger
this.codeGenerator = codeGenerator
}
override fun process(resolver: Resolver): List<KSAnnotated> {
rounds++
if (rounds == 1) {
codeGenerator.createNewFile(Dependencies.ALL_FILES, "test", "normal", "log")
}
return emptyList()
}
}
class TestProcessorProvider2 : SymbolProcessorProvider {
override fun create(
env: SymbolProcessorEnvironment
): SymbolProcessor {
return NormalProcessor().apply {
init(env.options, env.kotlinVersion, env.codeGenerator, env.logger)
}
}
}
| apache-2.0 | f5bec2abf23d40f9975160a7d4a21234 | 26.5 | 88 | 0.646364 | 4.888889 | false | false | false | false |
devunt/ika | app/src/main/kotlin/org/ozinger/ika/definition/Mode.kt | 1 | 1135 | package org.ozinger.ika.definition
import kotlinx.serialization.Serializable
@Serializable
sealed class IMode
@Serializable
data class Mode(
val mode: Char,
val param: String? = null,
) : IMode()
@Serializable
data class MemberMode(
val target: UniversalUserId,
val mode: Char? = null,
) : IMode() {
constructor(target: String, mode: Char? = null) : this(UniversalUserId(target), mode)
}
@Serializable
data class EphemeralMemberMode(
val target: String,
val mode: Char? = null,
) : IMode()
typealias MutableModes = MutableSet<IMode>
typealias Modes = Set<IMode>
@Serializable
data class ModeChangelist<T : IMode>(
val adding: Set<T> = setOf(),
val removing: Set<T> = setOf(),
)
data class ModeDefinition(
val stackable: List<Char>,
val parameterized: List<Char>,
val parameterizedAdd: List<Char>,
val general: List<Char>,
) {
constructor(modeDefs: List<String>) : this(
modeDefs[0].toList(),
modeDefs[1].toList(),
modeDefs[2].toList(),
modeDefs[3].toList(),
)
constructor(modeDefString: String) : this(modeDefString.split(","))
}
| agpl-3.0 | 86bf1ce0c42424b5b6d3b369bbcd53aa | 21.254902 | 89 | 0.672247 | 3.673139 | false | false | false | false |
javiersantos/PiracyChecker | library/src/main/java/com/github/javiersantos/piracychecker/utils/LibraryUtils.kt | 1 | 21957 | package com.github.javiersantos.piracychecker.utils
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.pm.Signature
import android.opengl.GLES20
import android.os.Build
import android.os.Environment
import android.util.Base64
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import com.github.javiersantos.piracychecker.R
import com.github.javiersantos.piracychecker.enums.AppType
import com.github.javiersantos.piracychecker.enums.InstallerID
import com.github.javiersantos.piracychecker.enums.PirateApp
import java.io.File
import java.security.MessageDigest
import java.util.ArrayList
internal fun Context.buildUnlicensedDialog(title: String, content: String): AlertDialog? {
return (this as? Activity)?.let {
if (isFinishing) return null
AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(title)
.setMessage(content)
.setPositiveButton(
getString(R.string.app_unlicensed_close),
DialogInterface.OnClickListener { _, _ ->
if (isFinishing)
return@OnClickListener
finish()
})
.create()
}
}
@Deprecated(
"Deprecated in favor of apkSignatures, which returns all valid signing signatures",
ReplaceWith("apkSignatures"))
val Context.apkSignature: Array<String>
get() = apkSignatures
val Context.apkSignatures: Array<String>
get() = currentSignatures
@Suppress("DEPRECATION", "RemoveExplicitTypeArguments")
private val Context.currentSignatures: Array<String>
get() {
val actualSignatures = ArrayList<String>()
val signatures: Array<Signature> = try {
val packageInfo =
packageManager.getPackageInfo(
packageName,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
PackageManager.GET_SIGNING_CERTIFICATES
else PackageManager.GET_SIGNATURES)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
if (packageInfo.signingInfo.hasMultipleSigners())
packageInfo.signingInfo.apkContentsSigners
else packageInfo.signingInfo.signingCertificateHistory
} else packageInfo.signatures
} catch (e: Exception) {
arrayOf<Signature>()
}
signatures.forEach { signature ->
val messageDigest = MessageDigest.getInstance("SHA")
messageDigest.update(signature.toByteArray())
try {
actualSignatures.add(
Base64.encodeToString(messageDigest.digest(), Base64.DEFAULT).trim())
} catch (e: Exception) {
}
}
return actualSignatures.filter { it.isNotEmpty() && it.isNotBlank() }.toTypedArray()
}
private fun Context.verifySigningCertificate(appSignature: String?): Boolean =
appSignature?.let { appSign -> currentSignatures.any { it == appSign } } ?: false
internal fun Context.verifySigningCertificates(appSignatures: Array<String>): Boolean {
var validCount = 0
appSignatures.forEach { if (verifySigningCertificate(it)) validCount += 1 }
return validCount >= appSignatures.size
}
internal fun Context.verifyInstallerId(installerID: List<InstallerID>): Boolean {
val validInstallers = ArrayList<String>()
val installer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
packageManager.getInstallSourceInfo(packageName).installingPackageName
} else {
packageManager.getInstallerPackageName(packageName)
}
for (id in installerID) {
validInstallers.addAll(id.toIDs())
}
return installer != null && validInstallers.contains(installer)
}
@Suppress("DEPRECATION")
@SuppressLint("SdCardPath")
internal fun Context.getPirateApp(
lpf: Boolean,
stores: Boolean,
folders: Boolean,
apks: Boolean,
extraApps: ArrayList<PirateApp>
): PirateApp? {
if (!lpf && !stores && extraApps.isEmpty()) return null
val apps = getApps(extraApps)
var installed = false
var theApp: PirateApp? = null
try {
val pm = packageManager
val list = pm?.getInstalledApplications(PackageManager.GET_META_DATA)
for (app in apps) {
val checkLPF = lpf && app.type == AppType.PIRATE
val checkStore = stores && app.type == AppType.STORE
val checkOther = app.type == AppType.OTHER
if (checkLPF || checkStore || checkOther) {
installed = list?.any { it.packageName.contains(app.packageName) } ?: false
if (!installed) {
installed = isIntentAvailable(pm.getLaunchIntentForPackage(app.packageName))
}
}
if (installed) {
theApp = app
break
}
}
} catch (e: Exception) {
}
if ((folders || apks) && theApp == null) {
if (hasPermissions()) {
var apkExist = false
var foldersExist = false
var containsFolder = false
for (app in apps) {
val pack = app.packageName
try {
if (apks) {
val file1 = File("/data/app/$pack-1/base.apk")
val file2 = File("/data/app/$pack-2/base.apk")
val file3 = File("/data/app/$pack.apk")
val file4 = File("/data/data/$pack.apk")
apkExist = file1.exists() || file2.exists() ||
file3.exists() || file4.exists()
}
if (folders) {
val file5 = File("/data/data/$pack")
val file6 =
File(
"${Environment.getExternalStorageDirectory()}/Android/data/$pack")
foldersExist = file5.exists() || file6.exists()
val appsContainer = File("/data/app/")
if (appsContainer.exists()) {
for (f in appsContainer.listFiles().orEmpty()) {
if (f.name.startsWith(pack))
containsFolder = true
}
}
}
} catch (e: Exception) {
}
if (containsFolder || apkExist || foldersExist) {
theApp = app
break
}
}
}
}
return theApp
}
/**
* 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.
*
*
* Copyright (C) 2013, Vladislav Gingo Skoumal (http://www.skoumal.net)
*/
@Suppress("DEPRECATION")
internal fun isInEmulator(deepCheck: Boolean = false): Boolean {
var ratingCheckEmulator = 0
val product = try {
Build.PRODUCT
} catch (e: Exception) {
""
}
if (product.containsIgnoreCase("sdk") || product.containsIgnoreCase("Andy") ||
product.containsIgnoreCase("ttVM_Hdragon") || product.containsIgnoreCase("google_sdk") ||
product.containsIgnoreCase("Droid4X") || product.containsIgnoreCase("nox") ||
product.containsIgnoreCase("sdk_x86") || product.containsIgnoreCase("sdk_google") ||
product.containsIgnoreCase("vbox86p")) {
ratingCheckEmulator++
}
val manufacturer = try {
Build.MANUFACTURER
} catch (e: Exception) {
""
}
if (manufacturer.equalsIgnoreCase("unknown") || manufacturer.equalsIgnoreCase("Genymotion") ||
manufacturer.containsIgnoreCase("Andy") || manufacturer.containsIgnoreCase("MIT") ||
manufacturer.containsIgnoreCase("nox") || manufacturer.containsIgnoreCase("TiantianVM")) {
ratingCheckEmulator++
}
val brand = try {
Build.BRAND
} catch (e: Exception) {
""
}
if (brand.equalsIgnoreCase("generic") || brand.equalsIgnoreCase("generic_x86") ||
brand.equalsIgnoreCase("TTVM") || brand.containsIgnoreCase("Andy")) {
ratingCheckEmulator++
}
val device = try {
Build.DEVICE
} catch (e: Exception) {
""
}
if (device.containsIgnoreCase("generic") || device.containsIgnoreCase("generic_x86") ||
device.containsIgnoreCase("Andy") || device.containsIgnoreCase("ttVM_Hdragon") ||
device.containsIgnoreCase("Droid4X") || device.containsIgnoreCase("nox") ||
device.containsIgnoreCase("generic_x86_64") || device.containsIgnoreCase("vbox86p")) {
ratingCheckEmulator++
}
val model = try {
Build.MODEL
} catch (e: Exception) {
""
}
if (model.equalsIgnoreCase("sdk") || model.equalsIgnoreCase("google_sdk") ||
model.containsIgnoreCase("Droid4X") || model.containsIgnoreCase("TiantianVM") ||
model.containsIgnoreCase("Andy") || model.equalsIgnoreCase(
"Android SDK built for x86_64") ||
model.equalsIgnoreCase("Android SDK built for x86")) {
ratingCheckEmulator++
}
val hardware = try {
Build.HARDWARE
} catch (e: Exception) {
""
}
if (hardware.equalsIgnoreCase("goldfish") || hardware.equalsIgnoreCase("vbox86") ||
hardware.containsIgnoreCase("nox") || hardware.containsIgnoreCase("ttVM_x86")) {
ratingCheckEmulator++
}
val fingerprint = try {
Build.FINGERPRINT
} catch (e: Exception) {
""
}
if (fingerprint.containsIgnoreCase("generic") ||
fingerprint.containsIgnoreCase("generic/sdk/generic") ||
fingerprint.containsIgnoreCase("generic_x86/sdk_x86/generic_x86") ||
fingerprint.containsIgnoreCase("Andy") || fingerprint.containsIgnoreCase("ttVM_Hdragon") ||
fingerprint.containsIgnoreCase("generic_x86_64") ||
fingerprint.containsIgnoreCase("generic/google_sdk/generic") ||
fingerprint.containsIgnoreCase("vbox86p") ||
fingerprint.containsIgnoreCase("generic/vbox86p/vbox86p")) {
ratingCheckEmulator++
}
if (deepCheck) {
try {
GLES20.glGetString(GLES20.GL_RENDERER)?.let {
if (it.containsIgnoreCase("Bluestacks") || it.containsIgnoreCase("Translator"))
ratingCheckEmulator += 10
}
} catch (e: Exception) {
}
try {
val sharedFolder = File(
"${Environment.getExternalStorageDirectory()}${File.separatorChar}windows" +
"${File.separatorChar}BstSharedFolder")
if (sharedFolder.exists())
ratingCheckEmulator += 10
} catch (e: Exception) {
}
}
return ratingCheckEmulator > 3
}
internal fun Context.isDebug(): Boolean =
applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
private fun getApps(extraApps: ArrayList<PirateApp>): ArrayList<PirateApp> {
val apps = ArrayList<PirateApp>()
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf(
"c", "o", "m", ".", "c", "h", "e", "l", "p", "u", "s", ".", "l", "a", "c", "k", "y",
"p", "a", "t", "c", "h"),
AppType.PIRATE))
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf(
"c", "o", "m", ".", "d", "i", "m", "o", "n", "v", "i", "d", "e", "o", ".", "l", "u",
"c", "k", "y", "p", "a", "t", "c", "h", "e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf("c", "o", "m", ".", "f", "o", "r", "p", "d", "a", ".", "l", "p"),
AppType.PIRATE))
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf(
"c", "o", "m", ".", "a", "n", "d", "r", "o", "i", "d", ".", "v", "e", "n", "d", "i",
"n", "g", ".", "b", "i", "l", "l", "i", "n", "g", ".", "I", "n", "A", "p", "p", "B",
"i", "l", "l", "i", "n", "g", "S", "e", "r", "v", "i", "c", "e"),
AppType.PIRATE))
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf(
"c", "o", "m", ".", "a", "n", "d", "r", "o", "i", "d", ".", "v", "e", "n", "d", "i",
"n", "g", ".", "b", "i", "l", "l", "i", "n", "g", ".", "I", "n", "A", "p", "p", "B",
"i", "l", "l", "i", "n", "g", "S", "o", "r", "v", "i", "c", "e"),
AppType.PIRATE))
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf(
"c", "o", "m", ".", "a", "n", "d", "r", "o", "i", "d", ".", "v", "e", "n", "d", "i",
"n", "c"),
AppType.PIRATE))
apps.add(
PirateApp(
"UretPatcher",
arrayOf(
"u", "r", "e", "t", ".", "j", "a", "s", "i", "2", "1", "6", "9", ".", "p", "a", "t",
"c", "h", "e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"UretPatcher",
arrayOf(
"z", "o", "n", "e", ".", "j", "a", "s", "i", "2", "1", "6", "9", ".", "u", "r", "e",
"t", "p", "a", "t", "c", "h", "e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"ActionLauncherPatcher",
arrayOf("p", ".", "j", "a", "s", "i", "2", "1", "6", "9", ".", "a", "l", "3"),
AppType.PIRATE))
apps.add(
PirateApp(
"Freedom",
arrayOf(
"c", "c", ".", "m", "a", "d", "k", "i", "t", "e", ".", "f", "r", "e", "e", "d", "o",
"m"),
AppType.PIRATE))
apps.add(
PirateApp(
"Freedom",
arrayOf(
"c", "c", ".", "c", "z", ".", "m", "a", "d", "k", "i", "t", "e", ".", "f", "r", "e",
"e", "d", "o", "m"),
AppType.PIRATE))
apps.add(
PirateApp(
"CreeHack",
arrayOf(
"o", "r", "g", ".", "c", "r", "e", "e", "p", "l", "a", "y", "s", ".", "h", "a", "c",
"k"),
AppType.PIRATE))
apps.add(
PirateApp(
"HappyMod",
arrayOf("c", "o", "m", ".", "h", "a", "p", "p", "y", "m", "o", "d", ".", "a", "p", "k"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game Hacker",
arrayOf(
"o", "r", "g", ".", "s", "b", "t", "o", "o", "l", "s", ".", "g", "a", "m", "e", "h",
"a", "c", "k"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game Killer Cheats",
arrayOf(
"c", "o", "m", ".", "z", "u", "n", "e", ".", "g", "a", "m", "e", "k", "i", "l", "l",
"e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"AGK - App Killer",
arrayOf("c", "o", "m", ".", "a", "a", "g", ".", "k", "i", "l", "l", "e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game Killer",
arrayOf(
"c", "o", "m", ".", "k", "i", "l", "l", "e", "r", "a", "p", "p", ".", "g", "a", "m",
"e", "k", "i", "l", "l", "e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game Killer", arrayOf("c", "n", ".", "l", "m", ".", "s", "q"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game CheatIng Hacker",
arrayOf(
"n", "e", "t", ".", "s", "c", "h", "w", "a", "r", "z", "i", "s", ".", "g", "a", "m",
"e", "_", "c", "i", "h"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game Hacker",
arrayOf(
"c", "o", "m", ".", "b", "a", "s", "e", "a", "p", "p", "f", "u", "l", "l", ".", "f",
"w", "d"),
AppType.PIRATE))
apps.add(
PirateApp(
"Content Guard Disabler",
arrayOf(
"c", "o", "m", ".", "g", "i", "t", "h", "u", "b", ".", "o", "n", "e", "m", "i", "n",
"u", "s", "o", "n", "e", ".", "d", "i", "s", "a", "b", "l", "e", "c", "o", "n", "t",
"e", "n", "t", "g", "u", "a", "r", "d"),
AppType.PIRATE))
apps.add(
PirateApp(
"Content Guard Disabler",
arrayOf(
"c", "o", "m", ".", "o", "n", "e", "m", "i", "n", "u", "s", "o", "n", "e", ".", "d",
"i", "s", "a", "b", "l", "e", "c", "o", "n", "t", "e", "n", "t", "g", "u", "a", "r",
"d"),
AppType.PIRATE))
apps.add(
PirateApp(
"Aptoide", arrayOf("c", "m", ".", "a", "p", "t", "o", "i", "d", "e", ".", "p", "t"),
AppType.STORE))
apps.add(
PirateApp(
"BlackMart",
arrayOf(
"o", "r", "g", ".", "b", "l", "a", "c", "k", "m", "a", "r", "t", ".", "m", "a", "r",
"k", "e", "t"),
AppType.STORE))
apps.add(
PirateApp(
"BlackMart",
arrayOf(
"c", "o", "m", ".", "b", "l", "a", "c", "k", "m", "a", "r", "t", "a", "l", "p", "h",
"a"),
AppType.STORE))
apps.add(
PirateApp(
"Mobogenie",
arrayOf("c", "o", "m", ".", "m", "o", "b", "o", "g", "e", "n", "i", "e"),
AppType.STORE))
apps.add(
PirateApp(
"1Mobile",
arrayOf(
"m", "e", ".", "o", "n", "e", "m", "o", "b", "i", "l", "e", ".", "a", "n", "d", "r",
"o", "i", "d"),
AppType.STORE))
apps.add(
PirateApp(
"GetApk", arrayOf(
"c", "o", "m", ".", "r", "e", "p", "o", "d", "r", "o", "i", "d", ".", "a", "p", "p"),
AppType.STORE))
apps.add(
PirateApp(
"GetJar",
arrayOf(
"c", "o", "m", ".", "g", "e", "t", "j", "a", "r", ".", "r", "e", "w", "a", "r", "d",
"s"),
AppType.STORE))
apps.add(
PirateApp(
"SlideMe",
arrayOf(
"c", "o", "m", ".", "s", "l", "i", "d", "e", "m", "e", ".", "s", "a", "m", ".", "m",
"a", "n", "a", "g", "e", "r"),
AppType.STORE))
apps.add(
PirateApp(
"ACMarket",
arrayOf("n", "e", "t", ".", "a", "p", "p", "c", "a", "k", "e"),
AppType.STORE))
apps.add(
PirateApp(
"ACMarket",
arrayOf("a", "c", ".", "m", "a", "r", "k", "e", "t", ".", "s", "t", "o", "r", "e"),
AppType.STORE))
apps.add(
PirateApp(
"AppCake",
arrayOf("c", "o", "m", ".", "a", "p", "p", "c", "a", "k", "e"),
AppType.STORE))
apps.add(
PirateApp(
"Z Market",
arrayOf("c", "o", "m", ".", "z", "m", "a", "p", "p"),
AppType.STORE))
apps.add(
PirateApp(
"Modded Play Store",
arrayOf(
"c", "o", "m", ".", "d", "v", ".", "m", "a", "r", "k", "e", "t", "m", "o", "d", ".",
"i", "n", "s", "t", "a", "l", "l", "e", "r"),
AppType.STORE))
apps.add(
PirateApp(
"Mobilism Market",
arrayOf(
"o", "r", "g", ".", "m", "o", "b", "i", "l", "i", "s", "m", ".", "a", "n", "d", "r",
"o", "i", "d"),
AppType.STORE))
apps.add(
PirateApp(
"All-in-one Downloader", arrayOf(
"c", "o", "m", ".", "a", "l", "l", "i", "n", "o", "n", "e", ".", "f", "r", "e", "e"),
AppType.STORE))
apps.addAll(extraApps)
return ArrayList(apps.distinctBy { it.packageName })
}
private fun Context.isIntentAvailable(intent: Intent?): Boolean {
intent ?: return false
return try {
packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
.orEmpty().isNotEmpty()
} catch (e: Exception) {
false
}
}
private fun Context.hasPermissions(): Boolean {
return try {
Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN ||
!shouldAskPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ||
!ActivityCompat.shouldShowRequestPermissionRationale(
this as Activity, Manifest.permission.READ_EXTERNAL_STORAGE)
} catch (e: Exception) {
false
}
}
private fun shouldAskPermission(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
private fun Context.shouldAskPermission(permission: String): Boolean {
if (shouldAskPermission()) {
val permissionResult = ActivityCompat.checkSelfPermission(this, permission)
return permissionResult != PackageManager.PERMISSION_GRANTED
}
return false
}
private fun String.equalsIgnoreCase(other: String) = this.equals(other, true)
private fun String.containsIgnoreCase(other: String) = this.contains(other, true) | apache-2.0 | c92d21e81f6b1025e121a3548c0bd155 | 36.153976 | 100 | 0.478298 | 3.856842 | false | false | false | false |
jrasmuson/Shaphat | src/main/kotlin/ModerationClient.kt | 1 | 1833 | import akka.util.ByteString
import com.amazonaws.services.rekognition.AmazonRekognitionAsyncClient
import com.amazonaws.services.rekognition.model.DetectModerationLabelsRequest
import com.amazonaws.services.rekognition.model.DetectModerationLabelsResult
import com.amazonaws.services.rekognition.model.Image
import org.apache.log4j.Logger
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionStage
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import javax.inject.Inject
class ModerationClient @Inject constructor(val asyncClient: AmazonRekognitionAsyncClient) {
private val logger = Logger.getLogger(ModerationClient::class.java)
fun callModerationService(bytes: ByteString): CompletionStage<DetectModerationLabelsResult> {
val moderationRequest = DetectModerationLabelsRequest()
.withImage(Image().withBytes(bytes.asByteBuffer()))
val resultFuture = asyncClient.detectModerationLabelsAsync(moderationRequest)
val completableFutureResult = makeCompletableFuture(resultFuture)
return completableFutureResult
}
//From https://stackoverflow.com/questions/23301598/transform-java-future-into-a-completablefuture
fun <T> makeCompletableFuture(future: Future<T>): CompletableFuture<T> {
return CompletableFuture.supplyAsync<T> {
try {
val startTime = System.currentTimeMillis()
return@supplyAsync future.get()
.apply { logger.info("Time to call moderation service:${System.currentTimeMillis() - startTime}") }
} catch (e: InterruptedException) {
throw RuntimeException(e)
} catch (e: ExecutionException) {
throw RuntimeException(e)
}
}
}
} | apache-2.0 | bb33ab628911d2929eb216b5b442688a | 42.666667 | 123 | 0.735952 | 5.077562 | false | false | false | false |
http4k/http4k | http4k-core/src/test/kotlin/org/http4k/CurlTest.kt | 1 | 2739 | package org.http4k
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.body.toBody
import org.http4k.core.toCurl
import org.junit.jupiter.api.Test
class CurlTest {
@Test
fun `generates for simple get request`() {
val curl = Request(GET, "http://httpbin.org").toCurl()
assertThat(curl, equalTo("curl -X GET \"http://httpbin.org\""))
}
@Test
fun `generates for request with query`() {
val curl = Request(GET, "http://httpbin.org").query("a", "one two three").toCurl()
assertThat(curl, equalTo("""curl -X GET "http://httpbin.org?a=one+two+three""""))
}
@Test
fun `includes headers`() {
val curl = Request(GET, "http://httpbin.org").header("foo", "my header").toCurl()
assertThat(curl, equalTo("""curl -X GET -H "foo:my header" "http://httpbin.org""""))
}
@Test
fun `deals with headers with quotes`() {
val curl = Request(GET, "http://httpbin.org").header("foo", "my \"quoted\" header").toCurl()
assertThat(curl, equalTo("""curl -X GET -H "foo:my \"quoted\" header" "http://httpbin.org""""))
}
@Test
fun `includes body data`() {
val curl = Request(POST, "http://httpbin.org/post").body(listOf("foo" to "bar").toBody()).toCurl()
assertThat(curl, equalTo("""curl -X POST --data "foo=bar" "http://httpbin.org/post""""))
}
@Test
fun `escapes body form`() {
val curl = Request(GET, "http://httpbin.org").body(listOf("foo" to "bar \"quoted\"").toBody()).toCurl()
assertThat(curl, equalTo("""curl -X GET --data "foo=bar+%22quoted%22" "http://httpbin.org""""))
}
@Test
fun `escapes body string`() {
val curl = Request(GET, "http://httpbin.org").body("my \"quote\"").toCurl()
assertThat(curl, equalTo("""curl -X GET --data "my \"quote\"" "http://httpbin.org""""))
}
@Test
fun `does not realise stream body`() {
val request = Request(POST, "http://httpbin.org").body("any stream".byteInputStream())
val curl = request.toCurl()
assertThat(curl, equalTo("""curl -X POST --data "<<stream>>" "http://httpbin.org""""))
assertThat(String(request.body.stream.readBytes()), equalTo("any stream"))
}
@Test
fun `limits the entity if it's too large`() {
val largeBody = (0..500).joinToString(" ")
val curl = Request(GET, "http://httpbin.org").body(largeBody).toCurl(256)
val data = "data \"([^\"]+)\"".toRegex().find(curl)?.groupValues?.get(1)!!
assertThat(data.length, equalTo(256 + "[truncated]".length))
}
}
| apache-2.0 | edf88a1cd928eea431888834a1dac08d | 37.577465 | 111 | 0.608616 | 3.661765 | false | true | false | false |
nukc/StateView | kotlin/src/main/java/com/github/nukc/stateview/Injector.kt | 1 | 6553 | package com.github.nukc.stateview
import android.content.Context
import android.os.Build
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.NestedScrollingChild
import androidx.core.view.NestedScrollingParent
import androidx.core.view.ScrollingView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
/**
* @author Nukc.
*/
internal object Injector {
val constraintLayoutAvailable = try {
null != Class.forName("androidx.constraintlayout.widget.ConstraintLayout")
} catch (e: Throwable) {
false
}
val swipeRefreshLayoutAvailable = try {
Class.forName("androidx.swiperefreshlayout.widget.SwipeRefreshLayout") != null
} catch (e: Throwable) {
false
}
/**
* Create a new FrameLayout (wrapper), let parent's remove children views, and add to the wrapper,
* stateVew add to wrapper, wrapper add to parent
*
* @param parent target
* @return [StateView]
*/
fun wrapChild(parent: ViewGroup): StateView {
// If there are other complex needs, maybe you can use stateView in layout(.xml)
var screenHeight = 0
// create a new FrameLayout to wrap StateView and parent's childView
val wrapper = FrameLayout(parent.context)
val layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
)
wrapper.layoutParams = layoutParams
if (parent is LinearLayout) {
// create a new LinearLayout to wrap parent's childView
val wrapLayout = LinearLayout(parent.context)
wrapLayout.layoutParams = parent.layoutParams ?: layoutParams
wrapLayout.orientation = parent.orientation
var i = 0
val childCount: Int = parent.getChildCount()
while (i < childCount) {
val childView: View = parent.getChildAt(0)
parent.removeView(childView)
wrapLayout.addView(childView)
i++
}
wrapper.addView(wrapLayout)
} else if (parent is ScrollView || parent is ScrollingView) {
// not recommended to inject Scrollview/NestedScrollView
if (parent.childCount != 1) {
throw IllegalStateException("the ScrollView does not have one direct child")
}
val directView = parent.getChildAt(0)
parent.removeView(directView)
wrapper.addView(directView)
val wm = parent.context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val metrics = DisplayMetrics()
wm.defaultDisplay.getMetrics(metrics)
screenHeight = metrics.heightPixels
} else if (parent is NestedScrollingParent && parent is NestedScrollingChild) {
if (parent.childCount == 2) {
val targetView = parent.getChildAt(1)
parent.removeView(targetView)
wrapper.addView(targetView)
} else if (parent.childCount > 2) {
throw IllegalStateException("the view is not refresh layout? view = $parent")
}
} else {
throw IllegalStateException("the view does not have parent, view = $parent")
}
// parent add wrapper
parent.addView(wrapper)
// StateView will be added to wrapper
val stateView = StateView(parent.context)
if (screenHeight > 0) {
// let StateView be shown in the center
val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, screenHeight)
wrapper.addView(stateView, params)
} else {
wrapper.addView(stateView)
}
return stateView
}
/**
* Set StateView to be the same size and position as the target view,
* layoutParams should be use [ConstraintLayout.LayoutParams] (android.view.ViewGroup.LayoutParams)
*
* @param parent view's parent, [ConstraintLayout]
* @param view target view
* @return [StateView]
*/
fun matchViewIfParentIsConstraintLayout(parent: ConstraintLayout, view: View): StateView {
val stateView = StateView(parent.context)
val lp = ConstraintLayout.LayoutParams(view.layoutParams as ViewGroup.LayoutParams)
lp.leftToLeft = view.id
lp.rightToRight = view.id
lp.topToTop = view.id
lp.bottomToBottom = view.id
parent.addView(stateView, lp)
return stateView
}
/**
* Set StateView to be the same size and position as the target view, If parent is RelativeLayout
*
* @param parent view's parent, [RelativeLayout]
* @param view target view
* @return [StateView]
*/
fun matchViewIfParentIsRelativeLayout(parent: RelativeLayout, view: View): StateView {
val stateView = StateView(parent.context)
val lp = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
RelativeLayout.LayoutParams(view.layoutParams as RelativeLayout.LayoutParams)
} else {
RelativeLayout.LayoutParams(view.layoutParams)
}
parent.addView(stateView, lp)
setStateListAnimator(stateView, view)
return stateView
}
/**
* In order to display on the button top
*/
fun setStateListAnimator(stateView: StateView, target: View) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && target is Button) {
Log.i(
StateView.TAG,
"for normal display, stateView.stateListAnimator = view.stateListAnimator"
)
stateView.stateListAnimator = target.stateListAnimator
}
}
/**
* fix bug: if someone injects SwipeRefreshLayout's child after SwipeRefreshLayout is resumed,
* this child will be hidden.
*/
fun injectIntoSwipeRefreshLayout(layout: SwipeRefreshLayout) {
try {
val mTargetField = SwipeRefreshLayout::class.java.getDeclaredField("mTarget")
mTargetField.isAccessible = true
mTargetField.set(layout, null)
// we replace the mTarget field with 'null', then the SwipeRefreshLayout
// will look for it's real child again.
} catch (e: Throwable) {
e.printStackTrace()
}
}
} | mit | be7b9f70efbd8d032656fccbaa2af56a | 37.757396 | 103 | 0.64422 | 5.014548 | false | false | false | false |
Discord4J-Addons/Discord4K | src/main/kotlin/sx/blah/discord/kotlin/Discord4K.kt | 1 | 573 | package sx.blah.discord.kotlin
import sx.blah.discord.api.IDiscordClient
import sx.blah.discord.modules.IModule
/**
* This represents the base Discord4K module. This does nothing, it's only for show.
*/
class Discord4K : IModule {
override fun getName() = "Discord4k"
override fun enable(client: IDiscordClient?) = true
override fun getVersion() = "1.0.0-SNAPSHOT"
override fun getMinimumDiscord4JVersion() = "2.5.1"
override fun getAuthor() = "austinv11"
override fun disable() {
throw UnsupportedOperationException()
}
}
| gpl-3.0 | 9c573bf8119e2cdbe4eb8f98790c1f23 | 22.875 | 84 | 0.701571 | 3.951724 | false | false | false | false |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/TooGenericExceptionCaughtSpec.kt | 1 | 2875 | package io.gitlab.arturbosch.detekt.rules.exceptions
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.util.regex.PatternSyntaxException
class TooGenericExceptionCaughtSpec : Spek({
describe("a file with many caught exceptions") {
it("should find one of each kind") {
val rule = TooGenericExceptionCaught(Config.empty)
val findings = rule.compileAndLint(tooGenericExceptionCode)
assertThat(findings).hasSize(caughtExceptionDefaults.size)
}
}
describe("a file with a caught exception which is ignored") {
val code = """
class MyTooGenericException : RuntimeException()
fun f() {
try {
throw Throwable()
} catch (myIgnore: MyTooGenericException) {
throw Error()
}
}
"""
it("should not report an ignored catch blocks because of its exception name") {
val config = TestConfig(mapOf(TooGenericExceptionCaught.ALLOWED_EXCEPTION_NAME_REGEX to "myIgnore"))
val rule = TooGenericExceptionCaught(config)
val findings = rule.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report an ignored catch blocks because of its exception type") {
val config = TestConfig(mapOf(TooGenericExceptionCaught.CAUGHT_EXCEPTIONS_PROPERTY to "[MyException]"))
val rule = TooGenericExceptionCaught(config)
val findings = rule.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not fail when disabled with invalid regex on allowed exception names") {
val configRules = mapOf(
"active" to "false",
TooGenericExceptionCaught.ALLOWED_EXCEPTION_NAME_REGEX to "*MyException"
)
val config = TestConfig(configRules)
val rule = TooGenericExceptionCaught(config)
val findings = rule.compileAndLint(tooGenericExceptionCode)
assertThat(findings).isEmpty()
}
it("should fail with invalid regex on allowed exception names") {
val config = TestConfig(mapOf(TooGenericExceptionCaught.ALLOWED_EXCEPTION_NAME_REGEX to "*Foo"))
val rule = TooGenericExceptionCaught(config)
assertThatExceptionOfType(PatternSyntaxException::class.java).isThrownBy {
rule.compileAndLint(tooGenericExceptionCode)
}
}
}
})
| apache-2.0 | a19b8840b43cd549bbb777d5b12502b8 | 36.337662 | 115 | 0.653217 | 5.47619 | false | true | false | false |
IntershopCommunicationsAG/scmversion-gradle-plugin | src/main/kotlin/com/intershop/gradle/scm/utils/IPrefixConfig.kt | 1 | 4355 | /*
* Copyright 2020 Intershop Communications AG.
*
* 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.intershop.gradle.scm.utils
/**
* This is the configuration class for the necessary prefixes
* on special branches, so that it is possible to identify the
* relevant branches and tags for version calculation.
*/
interface IPrefixConfig {
companion object {
/**
* Search pattern for stabilization branches with version information.
*/
const val stabilizationBranchPattern = "(\\d+(\\.\\d+)?(\\.\\d+)?(\\.\\d+)?)"
}
/**
* Prefix for stabilization branches.
*
* @property stabilizationPrefix
*/
var stabilizationPrefix: String
/**
* Prefix for feature branches.
*
* @property featurePrefix
*/
var featurePrefix: String
/**
* Prefix for hotfix branches.
*
* @property hotfixPrefix
*/
var hotfixPrefix: String
/**
* Prefix for bugfix branches.
*
* @property bugfixPrefix
*/
var bugfixPrefix: String
/**
* Prefix for release tags.
*
* @property tagPrefix
*/
var tagPrefix: String
/**
* Separator between prefix and version.
*
* @property prefixSeperator
*/
var prefixSeperator: String
/**
* Separator between prefix and version for branches.
*
* @property branchPrefixSeperator
*/
var branchPrefixSeperator: String?
/**
* Separator between prefix and version for tags.
*
* @property tagPrefixSeperator
*/
var tagPrefixSeperator: String?
/**
* Creates a search pattern for feature branches.
*
* @property featureBranchPattern Search pattern for feature branches.
*/
val featureBranchPattern: String
get() {
return if(branchPrefixSeperator != null) {
"${featurePrefix}${branchPrefixSeperator}(.*)"
} else {
"${featurePrefix}${prefixSeperator}(.*)"
}
}
/**
* Creates a search pattern for hotfix branches.
*
* @property hotfixBranchPattern Search pattern for hotfix branches.
*/
val hotfixBranchPattern : String
get() {
if(branchPrefixSeperator != null) {
return "${hotfixPrefix}${branchPrefixSeperator}(.*)"
}
return "${hotfixPrefix}${prefixSeperator}(.*)"
}
/**
* Creates a search pattern for bugfix branches.
*
* @property bugfixBranchPattern Search pattern for bugfix branches.
*/
val bugfixBranchPattern: String
get() {
if(branchPrefixSeperator != null) {
return "${bugfixPrefix}${branchPrefixSeperator}(.*)"
}
return "${bugfixPrefix}${prefixSeperator}(.*)"
}
/**
* Creates a search pattern for stabilization branches.
*
* @property stabilizationBranchPattern Search pattern for stabilization branches.
*/
val stabilizationBranchPattern: String
get() {
if(branchPrefixSeperator != null) {
return "${stabilizationPrefix}${branchPrefixSeperator}(.*)"
}
return "${stabilizationPrefix}${prefixSeperator}(.*)"
}
/**
* Returns the prefix for the special branch.
*
* @param type branch type
* @return the prefix for the specified branch type
*/
fun getPrefix(type: BranchType): String {
return when (type) {
BranchType.BRANCH -> stabilizationPrefix
BranchType.FEATUREBRANCH -> featurePrefix
BranchType.HOTFIXBBRANCH -> hotfixPrefix
BranchType.BUGFIXBRANCH -> bugfixPrefix
else -> tagPrefix
}
}
}
| apache-2.0 | 993cbbee6dc4b19bbf741eed1f174cd2 | 26.916667 | 86 | 0.599311 | 5.285194 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/process/processModel/IXmlResultType.kt | 1 | 3129 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.processModel
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import nl.adaptivity.serialutil.DelegatingSerializer
import nl.adaptivity.xmlutil.Namespace
import nl.adaptivity.xmlutil.XmlReader
@Serializable(with = IXmlResultType.Serializer::class)
interface IXmlResultType {
val content: CharArray?
/**
* The value of the name property.
*/
fun getName(): String
fun setName(value: String)
/**
* Gets the value of the path property.
*
* @return possible object is [String]
*/
fun getPath(): String?
/**
* Sets the value of the path property.
*
* @param namespaceContext
*
* @param value allowed object is [String]
*/
fun setPath(namespaceContext: Iterable<Namespace>, value: String?)
/**
* A reader for the underlying body stream.
*/
val bodyStreamReader: XmlReader
/**
* Get the namespace context for evaluating the xpath expression.
* @return the context
*/
val originalNSContext: Iterable<Namespace>
companion object Serializer : DelegatingSerializer<IXmlResultType, XmlResultType>(XmlResultType.serializer()) {
fun serializer(): Serializer = this
override fun fromDelegate(delegate: XmlResultType): IXmlResultType = delegate
override fun IXmlResultType.toDelegate(): XmlResultType {
return this as? XmlResultType ?: XmlResultType(this)
}
}
}
val IXmlResultType.path: String?
inline get() = getPath()
var IXmlResultType.name: String
inline get(): String = getName()
inline set(value) {
setName(value)
}
fun IXmlResultType.getOriginalNSContext(): Iterable<Namespace> = originalNSContext
object IXmlResultTypeListSerializer : KSerializer<List<IXmlResultType>> {
val delegate = ListSerializer(XmlResultType)
override val descriptor: SerialDescriptor = delegate.descriptor
override fun deserialize(decoder: Decoder): List<IXmlResultType> {
return delegate.deserialize(decoder)
}
override fun serialize(encoder: Encoder, value: List<IXmlResultType>) {
delegate.serialize(encoder, value.map(::XmlResultType))
}
}
| lgpl-3.0 | e4809b4acfbf7d30e3b1b005b49ddb96 | 28.8 | 115 | 0.721956 | 4.904389 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/settings/NumberPickerPreferenceDialog.kt | 2 | 1749 | package de.westnordost.streetcomplete.settings
import androidx.preference.PreferenceDialogFragmentCompat
import android.view.View
import android.widget.NumberPicker
import de.westnordost.streetcomplete.R
/** Preference dialog where user should pick a number */
class NumberPickerPreferenceDialog : PreferenceDialogFragmentCompat() {
private lateinit var picker: NumberPicker
private lateinit var values: Array<String>
private val pref: NumberPickerPreference
get() = preference as NumberPickerPreference
override fun onBindDialogView(view: View) {
super.onBindDialogView(view)
picker = view.findViewById(R.id.numberPicker)
val intValues = (pref.minValue..pref.maxValue step pref.step).toList()
values = intValues.map { "$it" }.toTypedArray()
var index = values.indexOf(pref.value.toString())
if(index == -1) {
do ++index while(index < intValues.lastIndex && intValues[index] < pref.value)
}
picker.apply {
displayedValues = values
minValue = 0
maxValue = values.size - 1
value = index
wrapSelectorWheel = false
}
}
override fun onDialogClosed(positiveResult: Boolean) {
// hackfix: The Android number picker accepts input via soft keyboard (which makes sense
// from a UX viewpoint) but is not designed for that. By default, it does not apply the
// input there. See http://stackoverflow.com/questions/18944997/numberpicker-doesnt-work-with-keyboard
// A workaround is to clear the focus before saving.
picker.clearFocus()
if (positiveResult) {
pref.value = values[picker.value].toInt()
}
}
}
| gpl-3.0 | f71ccde12269ddc0ba4298ab4f2191f5 | 36.212766 | 110 | 0.674099 | 4.831492 | false | false | false | false |
alex-tavella/MooV | core-lib/tmdb/src/main/java/br/com/core/tmdb/TmdbModule.kt | 1 | 2816 | /*
* Copyright 2020 Alex Almeida Tavella
*
* 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 br.com.core.tmdb
import android.content.Context
import br.com.core.tmdb.api.TmdbApiKeyStore
import br.com.core.tmdb.image.ImageConfigurationApi
import br.com.moov.core.di.AppScope
import com.squareup.anvil.annotations.ContributesTo
import dagger.Module
import dagger.Provides
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Qualifier
@Qualifier
private annotation class BaseUrl
@Module(
includes = [
TmdbInternalModule::class
]
)
@ContributesTo(AppScope::class)
interface TmdbModule
private const val CACHE_SIZE: Long = 10 * 1024 * 1024
@Module
internal object TmdbInternalModule {
@[Provides BaseUrl]
fun providesBaseUrl(): String = "https://api.themoviedb.org"
@Provides
fun providesApiKey(apiKeyStore: TmdbApiKeyStore): String = apiKeyStore.getApiKey()
@Provides
fun providesCacheDuration(): Long = TimeUnit.DAYS.toSeconds(1)
@Provides
fun providesCache(context: Context): Cache = Cache(context.cacheDir, CACHE_SIZE)
@Provides
fun providesOkHttpClient(
cache: Cache,
interceptor: Interceptor
): OkHttpClient {
val builder = OkHttpClient().newBuilder()
if (BuildConfig.DEBUG) {
builder.addInterceptor(
HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
.setLevel(HttpLoggingInterceptor.Level.BODY)
)
}
return builder
.cache(cache)
.addInterceptor(interceptor)
.build()
}
@Provides
fun providesRetrofit(
okHttpClient: OkHttpClient,
@BaseUrl baseUrl: String
): Retrofit {
return Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(MoshiConverterFactory.create())
.build()
}
@Provides
fun providesImageConfigurationApi(retrofit: Retrofit): ImageConfigurationApi {
return retrofit.create(ImageConfigurationApi::class.java)
}
}
| apache-2.0 | beaced0130e2ac9b315bb7877b29b1a2 | 28.333333 | 86 | 0.709162 | 4.601307 | false | true | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/addons/AddOnsRestClient.kt | 2 | 2117 | package org.wordpress.android.fluxc.network.rest.wpcom.wc.addons
import android.content.Context
import com.android.volley.RequestQueue
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload
import org.wordpress.android.fluxc.network.rest.wpcom.wc.addons.dto.AddOnGroupDto
import org.wordpress.android.fluxc.network.rest.wpcom.wc.toWooError
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
@Singleton
class AddOnsRestClient @Inject constructor(
appContext: Context,
dispatcher: Dispatcher,
@Named("regular") requestQueue: RequestQueue,
accessToken: AccessToken,
userAgent: UserAgent,
private val requestBuilder: JetpackTunnelGsonRequestBuilder
) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) {
suspend fun fetchGlobalAddOnGroups(site: SiteModel): WooPayload<List<AddOnGroupDto>> {
val url = WOOCOMMERCE.product_add_ons.pathV1Addons
val response = requestBuilder.syncGetRequest(
restClient = this,
site = site,
url = url,
params = emptyMap(),
clazz = Array<AddOnGroupDto>::class.java
)
return when (response) {
is JetpackSuccess -> WooPayload(response.data?.toList())
is JetpackError -> WooPayload(response.error.toWooError())
}
}
}
| gpl-2.0 | e53f35bf42585dc012ea59638063e5fc | 45.021739 | 130 | 0.772319 | 4.652747 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/protobuf/commonMain/src/kotlinx/serialization/protobuf/internal/ProtobufTaggedBase.kt | 1 | 1594 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.protobuf.internal
import kotlinx.serialization.*
import kotlin.jvm.*
/*
* In ProtoBuf spec, ids from 19000 to 19999 are reserved for protocol use,
* thus we are leveraging it here and use 19_500 as a marker no one us allowed to use.
* It does not leak to the resulting output.
*/
internal const val MISSING_TAG = 19_500L
internal abstract class ProtobufTaggedBase {
private var tagsStack = LongArray(8)
@JvmField
protected var stackSize = -1
protected val currentTag: ProtoDesc
get() = tagsStack[stackSize]
protected val currentTagOrDefault: ProtoDesc
get() = if (stackSize == -1) MISSING_TAG else tagsStack[stackSize]
protected fun popTagOrDefault(): ProtoDesc = if (stackSize == -1) MISSING_TAG else tagsStack[stackSize--]
protected fun pushTag(tag: ProtoDesc) {
if (tag == MISSING_TAG) return // Missing tag is never added
val idx = ++stackSize
if (stackSize >= tagsStack.size) {
expand()
}
tagsStack[idx] = tag
}
private fun expand() {
tagsStack = tagsStack.copyOf(tagsStack.size * 2)
}
protected fun popTag(): ProtoDesc {
if (stackSize >= 0) return tagsStack[stackSize--]
// Unreachable
throw SerializationException("No tag in stack for requested element")
}
protected inline fun <E> tagBlock(tag: ProtoDesc, block: () -> E): E {
pushTag(tag)
return block()
}
}
| apache-2.0 | fe0e164796d3a46148719cbe08f578d4 | 29.075472 | 109 | 0.660602 | 4.343324 | false | false | false | false |
kropp/intellij-makefile | src/main/kotlin/name/kropp/intellij/makefile/MakefileRunConfigurationProducer.kt | 1 | 1894 | package name.kropp.intellij.makefile
import com.intellij.execution.actions.*
import com.intellij.execution.configurations.*
import com.intellij.openapi.components.*
import com.intellij.openapi.util.*
import com.intellij.psi.*
import name.kropp.intellij.makefile.psi.*
import java.io.*
class MakefileRunConfigurationProducer : LazyRunConfigurationProducer<MakefileRunConfiguration>() {
override fun setupConfigurationFromContext(configuration: MakefileRunConfiguration, context: ConfigurationContext, sourceElement: Ref<PsiElement>): Boolean {
if (context.psiLocation?.containingFile !is MakefileFile) {
return false
}
val macroManager = PathMacroManager.getInstance(context.project)
val path = context.location?.virtualFile?.path
configuration.filename = macroManager.collapsePath(path) ?: ""
configuration.target = findTarget(context)?.name ?: ""
if (configuration.target.isNotEmpty()) {
configuration.name = configuration.target
} else {
configuration.name = File(path).name
}
return true
}
override fun isConfigurationFromContext(configuration: MakefileRunConfiguration, context: ConfigurationContext): Boolean {
val macroManager = PathMacroManager.getInstance(context.project)
return macroManager.expandPath(configuration.filename) == context.location?.virtualFile?.path &&
configuration.target == findTarget(context)?.name
}
private fun findTarget(context: ConfigurationContext): MakefileTarget? {
var element = context.psiLocation
while (element != null && element !is MakefileTarget) {
element = element.parent
}
val target = element as? MakefileTarget
if (target?.isSpecialTarget == false) {
return target
}
return null
}
override fun getConfigurationFactory(): ConfigurationFactory = MakefileRunConfigurationFactory(MakefileRunConfigurationType)
} | mit | 2510297cbb9b18052f1f20f9c668868f | 37.673469 | 159 | 0.758184 | 5.305322 | false | true | false | false |
hastebrot/Riker.kt | projects/riker-core/src/test/kotlin/de/entera/riker/suite/SuiteTest.kt | 1 | 1794 | package de.entera.riker.suite
import org.junit.Test
import kotlin.test.expect
class SuiteTest {
@Test
fun `transform() test test`() {
// given:
val source = Node("suite",
Node("test"),
Node("test")
)
val expected = Node("suite",
Node("testCase",
Node("test")
),
Node("testCase",
Node("test")
)
)
// expect:
expect(expected) { transform(source) }
}
@Test
fun `transform() testSetup test test`() {
// given:
val source = Node("suite",
Node("testSetup"),
Node("test"),
Node("test")
)
val expected = Node("suite",
Node("testCase",
Node("testSetup"),
Node("test")
),
Node("testCase",
Node("testSetup"),
Node("test")
)
)
// expect:
expect(expected) { transform(source) }
}
}
data class Node<T>(val data: T,
val children: MutableList<Node<T>> = arrayListOf()) {
constructor(data: T,
vararg children: Node<T>) : this(data) {
this.children.addAll(children)
}
}
fun transform(node: Node<String>): Node<String> {
val target = Node(node.data)
// collect setups and cleanups.
val testSetups = node.children.filter { it.data == "testSetup" }
val testCleanups = node.children.filter { it.data == "testCleanup" }
// populate test cases.
val testCases = node.children.filter { it.data == "test" }
.map { Node("testCase", (testSetups + it + testCleanups).toArrayList() ) }
target.children.addAll(testCases)
return target
}
| bsd-3-clause | fa73e1b94f134d208898e62c037805ce | 23.916667 | 82 | 0.5 | 4.261283 | false | true | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/util/TvChannels.kt | 1 | 6748 | /*****************************************************************************
* TvChannels.kt
*****************************************************************************
* Copyright © 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.util
import android.content.ComponentName
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.tvprovider.media.tv.TvContractCompat
import androidx.tvprovider.media.tv.WatchNextProgram
import kotlinx.coroutines.*
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.resources.util.getFromMl
import org.videolan.tools.AppScope
import org.videolan.tools.Settings
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.PreviewVideoInputService
import org.videolan.vlc.R
import org.videolan.vlc.getFileUri
import videolan.org.commontools.*
private const val TAG = "VLC/TvChannels"
private const val MAX_RECOMMENDATIONS = 3
@ExperimentalCoroutinesApi
@RequiresApi(Build.VERSION_CODES.O)
fun setChannel(context: Context) = GlobalScope.launch(start = CoroutineStart.UNDISPATCHED) {
val channelId = withContext(Dispatchers.IO) {
val prefs = Settings.getInstance(context)
val name = context.getString(R.string.tv_my_new_videos)
createOrUpdateChannel(prefs, context, name, R.drawable.ic_channel_icon, BuildConfig.APP_ID)
}
if (Permissions.canReadStorage(context)) updatePrograms(context, channelId)
}
private suspend fun updatePrograms(context: Context, channelId: Long) {
if (channelId == -1L) return
val videoList = context.getFromMl { recentVideos }
val programs = withContext(Dispatchers.IO) { existingPrograms(context, channelId) }
if (videoList.isNullOrEmpty()) return
val cn = ComponentName(context, PreviewVideoInputService::class.java)
for ((count, mw) in videoList.withIndex()) {
if (mw == null) continue
val index = programs.indexOfId(mw.id)
if (index != -1) {
programs.removeAt(index)
continue
}
if (mw.isThumbnailGenerated) {
if (mw.artworkMrl === null) continue
} else if (withContext(Dispatchers.IO) { ThumbnailsProvider.getMediaThumbnail(mw, 272.toPixel()) } === null
|| mw.artworkMrl === null) {
continue
}
val desc = ProgramDesc(channelId, mw.id, mw.title, mw.description,
mw.artUri(), mw.length.toInt(), mw.time.toInt(),
mw.width, mw.height, BuildConfig.APP_ID)
val program = buildProgram(cn, desc)
GlobalScope.launch(Dispatchers.IO) {
context.contentResolver.insert(TvContractCompat.PreviewPrograms.CONTENT_URI, program.toContentValues())
}
if (count - programs.size >= MAX_RECOMMENDATIONS) break
}
for (program in programs) {
withContext(Dispatchers.IO) { context.contentResolver.delete(TvContractCompat.buildPreviewProgramUri(program.programId), null, null) }
}
}
fun Context.launchChannelUpdate() = AppScope.launch {
val id = withContext(Dispatchers.IO) { Settings.getInstance(this@launchChannelUpdate).getLong(KEY_TV_CHANNEL_ID, -1L) }
updatePrograms(this@launchChannelUpdate, id)
}
suspend fun setResumeProgram(context: Context, mw: MediaWrapper) {
var cursor: Cursor? = null
var isProgramPresent = false
val mw = context.getFromMl { findMedia(mw) }
try {
cursor = context.contentResolver.query(
TvContractCompat.WatchNextPrograms.CONTENT_URI, WATCH_NEXT_MAP_PROJECTION, null,
null, null)
cursor?.let {
while (it.moveToNext()) {
if (!it.isNull(1) && TextUtils.equals(mw.id.toString(), cursor.getString(1))) {
// Found a row that contains the matching ID
val watchNextProgramId = cursor.getLong(0)
if (it.getInt(2) == 0 || mw.time == 0L) { //Row removed by user or progress null
if (deleteWatchNext(context, watchNextProgramId) < 1) {
Log.e(TAG, "Delete program failed")
return
}
} else { // Update the program
val existingProgram = WatchNextProgram.fromCursor(cursor)
updateWatchNext(context, existingProgram, mw.time, watchNextProgramId)
isProgramPresent = true
}
break
}
}
}
if (!isProgramPresent && mw.time != 0L) {
val desc = ProgramDesc(0L, mw.id, mw.title, mw.description,
mw.artUri(), mw.length.toInt(), mw.time.toInt(),
mw.width, mw.height, BuildConfig.APP_ID)
val cn = ComponentName(context, PreviewVideoInputService::class.java)
val program = buildWatchNextProgram(cn, desc)
val watchNextProgramUri = context.contentResolver.insert(TvContractCompat.WatchNextPrograms.CONTENT_URI, program.toContentValues())
if (watchNextProgramUri == null || watchNextProgramUri == Uri.EMPTY) Log.e(TAG, "Insert watch next program failed")
}
} finally {
cursor?.close()
}
}
private suspend fun MediaWrapper.artUri() : Uri {
if (!isThumbnailGenerated) {
withContext(Dispatchers.IO) { ThumbnailsProvider.getVideoThumbnail(this@artUri, 512) }
}
val mrl = artworkMrl
?: return Uri.parse("android.resource://${BuildConfig.APP_ID}/${R.drawable.ic_browser_video_big_normal}")
return try {
getFileUri(mrl)
} catch (ex: IllegalArgumentException) {
Uri.parse("android.resource://${BuildConfig.APP_ID}/${R.drawable.ic_browser_video_big_normal}")
}
} | gpl-2.0 | b6c4b96c2755ff7e48c52278e6e3bd79 | 43.98 | 143 | 0.644085 | 4.491345 | false | false | false | false |
adrcotfas/Goodtime | app/src/main/java/com/apps/adrcotfas/goodtime/settings/SettingsFragment.kt | 1 | 18692 | /*
* Copyright 2016-2021 Adrian Cotfas
*
* 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.apps.adrcotfas.goodtime.settings
import com.apps.adrcotfas.goodtime.util.BatteryUtils.Companion.isIgnoringBatteryOptimizations
import com.apps.adrcotfas.goodtime.util.UpgradeDialogHelper.Companion.launchUpgradeDialog
import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback
import android.os.Bundle
import com.apps.adrcotfas.goodtime.R
import android.view.LayoutInflater
import android.view.ViewGroup
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.annotation.TargetApi
import android.app.NotificationManager
import android.content.Context
import android.media.RingtoneManager
import android.net.Uri
import android.provider.Settings
import android.text.format.DateFormat
import android.view.View
import androidx.preference.*
import com.apps.adrcotfas.goodtime.ui.common.TimePickerDialogBuilder
import com.apps.adrcotfas.goodtime.util.*
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import xyz.aprildown.ultimateringtonepicker.RingtonePickerDialog
import xyz.aprildown.ultimateringtonepicker.UltimateRingtonePicker
import java.time.DayOfWeek
import java.time.LocalTime
import javax.inject.Inject
@AndroidEntryPoint
class SettingsFragment : PreferenceFragmentCompat(), OnRequestPermissionsResultCallback {
private lateinit var prefDisableSoundCheckbox: CheckBoxPreference
private lateinit var prefDndMode: CheckBoxPreference
@Inject
lateinit var preferenceHelper: PreferenceHelper
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.settings, rootKey)
setupReminderPreference()
setupStartOfDayPreference()
prefDisableSoundCheckbox = findPreference(PreferenceHelper.DISABLE_SOUND_AND_VIBRATION)!!
prefDndMode = findPreference(PreferenceHelper.DND_MODE)!!
}
private fun setupTimePickerPreference(
preference: Preference,
getTimeAction: () -> Int,
setTimeAction: (Int) -> Unit
) {
preference.setOnPreferenceClickListener {
val dialog = TimePickerDialogBuilder(requireContext())
.buildDialog(LocalTime.ofSecondOfDay(getTimeAction().toLong()))
dialog.addOnPositiveButtonClickListener {
val newValue = LocalTime.of(dialog.hour, dialog.minute).toSecondOfDay()
setTimeAction(newValue)
updateTimePickerPreferenceSummary(preference, getTimeAction())
}
dialog.showOnce(parentFragmentManager, "MaterialTimePicker")
true
}
updateTimePickerPreferenceSummary(preference, getTimeAction())
}
private fun setupReminderPreference() {
// restore from preferences
val dayOfWeekPref = findPreference<DayOfWeekPreference>(PreferenceHelper.REMINDER_DAYS)
dayOfWeekPref!!.setCheckedDays(
preferenceHelper.getBooleanArray(
PreferenceHelper.REMINDER_DAYS, DayOfWeek.values().size
)
)
val timePickerPref: Preference = findPreference(PreferenceHelper.REMINDER_TIME)!!
setupTimePickerPreference(
timePickerPref,
{ preferenceHelper.getReminderTime() },
{ preferenceHelper.setReminderTime(it) })
}
private fun setupStartOfDayPreference() {
val pref: Preference = findPreference(PreferenceHelper.WORK_DAY_START)!!
setupTimePickerPreference(
pref,
{ preferenceHelper.getStartOfDay() },
{ preferenceHelper.setStartOfDay(it) })
}
private fun updateTimePickerPreferenceSummary(pref: Preference, secondOfDay: Int) {
pref.summary = secondsOfDayToTimerFormat(
secondOfDay, DateFormat.is24HourFormat(context)
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view = super.onCreateView(inflater, container, savedInstanceState)
view!!.alpha = 0f
view.animate().alpha(1f).duration = 100
return view
}
@SuppressLint("BatteryLife")
override fun onResume() {
super.onResume()
requireActivity().title = getString(R.string.settings)
setupTheme()
setupRingtone()
setupScreensaver()
setupAutoStartSessionVsInsistentNotification()
setupDisableSoundCheckBox()
setupDnDCheckBox()
setupFlashingNotificationPref()
setupOneMinuteLeftNotificationPref()
val disableBatteryOptimizationPref =
findPreference<Preference>(PreferenceHelper.DISABLE_BATTERY_OPTIMIZATION)
if (!isIgnoringBatteryOptimizations(requireContext())) {
disableBatteryOptimizationPref!!.isVisible = true
disableBatteryOptimizationPref.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
val intent = Intent()
intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
intent.data = Uri.parse("package:" + requireActivity().packageName)
startActivity(intent)
true
}
} else {
disableBatteryOptimizationPref!!.isVisible = false
}
findPreference<Preference>(PreferenceHelper.DISABLE_WIFI)!!.isVisible =
Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
prefDndMode.isVisible = true
}
override fun onDisplayPreferenceDialog(preference: Preference) {
when (preference.key) {
PreferenceHelper.TIMER_STYLE -> {
super.onDisplayPreferenceDialog(preference)
}
PreferenceHelper.VIBRATION_TYPE -> {
val dialog = VibrationPreferenceDialogFragment.newInstance(preference.key)
dialog.setTargetFragment(this, 0)
dialog.showOnce(parentFragmentManager, "VibrationType")
}
else -> {
super.onDisplayPreferenceDialog(preference)
}
}
}
private fun setupAutoStartSessionVsInsistentNotification() {
// Continuous mode versus insistent notification
val autoWork = findPreference<CheckBoxPreference>(PreferenceHelper.AUTO_START_WORK)
autoWork!!.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _: Preference?, newValue: Any ->
val pref = findPreference<CheckBoxPreference>(PreferenceHelper.INSISTENT_RINGTONE)
if (newValue as Boolean) {
pref!!.isChecked = false
}
true
}
val autoBreak = findPreference<CheckBoxPreference>(PreferenceHelper.AUTO_START_BREAK)
autoBreak!!.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _: Preference?, newValue: Any ->
val pref = findPreference<CheckBoxPreference>(PreferenceHelper.INSISTENT_RINGTONE)
if (newValue as Boolean) {
pref!!.isChecked = false
}
true
}
val insistentRingPref =
findPreference<CheckBoxPreference>(PreferenceHelper.INSISTENT_RINGTONE)
insistentRingPref!!.onPreferenceClickListener =
if (preferenceHelper.isPro()) null else Preference.OnPreferenceClickListener {
launchUpgradeDialog(requireActivity().supportFragmentManager)
insistentRingPref.isChecked = false
true
}
insistentRingPref.onPreferenceChangeListener =
if (preferenceHelper.isPro()) Preference.OnPreferenceChangeListener { _, newValue: Any ->
val p1 = findPreference<CheckBoxPreference>(PreferenceHelper.AUTO_START_BREAK)
val p2 = findPreference<CheckBoxPreference>(PreferenceHelper.AUTO_START_WORK)
if (newValue as Boolean) {
p1!!.isChecked = false
p2!!.isChecked = false
}
true
} else null
}
private fun handleRingtonePrefClick(preference: Preference) {
if (preference.key == PreferenceHelper.RINGTONE_BREAK_FINISHED && !preferenceHelper.isPro()) {
launchUpgradeDialog(requireActivity().supportFragmentManager)
} else {
val selectedUri =
Uri.parse(toRingtone(preferenceHelper.getNotificationSoundFinished(preference.key)!!).uri)
val settings = UltimateRingtonePicker.Settings(
preSelectUris = listOf(selectedUri),
systemRingtonePicker = UltimateRingtonePicker.SystemRingtonePicker(
customSection = UltimateRingtonePicker.SystemRingtonePicker.CustomSection(),
defaultSection = UltimateRingtonePicker.SystemRingtonePicker.DefaultSection(
showSilent = false
),
ringtoneTypes = listOf(
RingtoneManager.TYPE_NOTIFICATION,
)
),
deviceRingtonePicker = UltimateRingtonePicker.DeviceRingtonePicker(
alwaysUseSaf = true
)
)
val dialog = RingtonePickerDialog.createEphemeralInstance(
settings = settings,
dialogTitle = preference.title,
listener = object : UltimateRingtonePicker.RingtonePickerListener {
override fun onRingtonePicked(ringtones: List<UltimateRingtonePicker.RingtoneEntry>) {
preference.apply {
val ringtone = if (ringtones.isNotEmpty()) {
Ringtone(ringtones.first().uri.toString(), ringtones.first().name)
} else {
Ringtone("", resources.getString(R.string.pref_ringtone_summary))
}
val json = Gson().toJson(ringtone)
preferenceHelper.setNotificationSoundFinished(preference.key, json)
summary = ringtone.name
callChangeListener(ringtone)
}
}
}
)
dialog.showOnce(parentFragmentManager, "RingtonePref")
}
}
private fun setupRingtone() {
val prefWork = findPreference<Preference>(PreferenceHelper.RINGTONE_WORK_FINISHED)
val prefBreak = findPreference<Preference>(PreferenceHelper.RINGTONE_BREAK_FINISHED)
val defaultSummary = resources.getString(
R.string.pref_ringtone_summary
)
prefWork!!.summary =
toRingtone(preferenceHelper.getNotificationSoundWorkFinished()!!, defaultSummary).name
prefBreak!!.summary =
toRingtone(preferenceHelper.getNotificationSoundBreakFinished()!!, defaultSummary).name
prefWork.setOnPreferenceClickListener {
handleRingtonePrefClick(prefWork)
true
}
prefBreak.setOnPreferenceClickListener {
handleRingtonePrefClick(prefBreak)
true
}
if (preferenceHelper.isPro()) {
prefWork.onPreferenceChangeListener = null
} else {
preferenceHelper.setNotificationSoundBreakFinished(preferenceHelper.getNotificationSoundWorkFinished()!!)
prefWork.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _, newValue: Any? ->
preferenceHelper.setNotificationSoundBreakFinished(Gson().toJson(newValue))
prefBreak.summary = prefWork.summary
true
}
}
val prefEnableRingtone =
findPreference<SwitchPreferenceCompat>(PreferenceHelper.ENABLE_RINGTONE)
toggleEnableRingtonePreference(prefEnableRingtone!!.isChecked)
prefEnableRingtone.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _, newValue: Any ->
toggleEnableRingtonePreference(newValue as Boolean)
true
}
}
private fun setupScreensaver() {
val screensaverPref =
findPreference<CheckBoxPreference>(PreferenceHelper.ENABLE_SCREENSAVER_MODE)
findPreference<Preference>(PreferenceHelper.ENABLE_SCREENSAVER_MODE)!!.onPreferenceClickListener =
if (preferenceHelper.isPro()) null else Preference.OnPreferenceClickListener {
launchUpgradeDialog(requireActivity().supportFragmentManager)
screensaverPref!!.isChecked = false
true
}
findPreference<Preference>(PreferenceHelper.ENABLE_SCREEN_ON)!!.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _: Preference?, newValue: Any ->
if (!(newValue as Boolean)) {
if (screensaverPref!!.isChecked) {
screensaverPref.isChecked = false
}
}
true
}
}
private fun setupTheme() {
val prefAmoled = findPreference<SwitchPreferenceCompat>(PreferenceHelper.AMOLED)
prefAmoled!!.onPreferenceClickListener =
if (preferenceHelper.isPro()) null else Preference.OnPreferenceClickListener {
launchUpgradeDialog(requireActivity().supportFragmentManager)
prefAmoled.isChecked = true
true
}
prefAmoled.onPreferenceChangeListener =
if (preferenceHelper.isPro()) Preference.OnPreferenceChangeListener { _, _ ->
ThemeHelper.setTheme(activity as SettingsActivity, preferenceHelper.isAmoledTheme())
requireActivity().recreate()
true
} else null
}
private fun updateDisableSoundCheckBoxSummary(
pref: CheckBoxPreference?,
notificationPolicyAccessGranted: Boolean
) {
if (notificationPolicyAccessGranted) {
pref!!.summary = ""
} else {
pref!!.setSummary(R.string.settings_grant_permission)
}
}
private fun setupDisableSoundCheckBox() {
if (isNotificationPolicyAccessDenied) {
updateDisableSoundCheckBoxSummary(prefDisableSoundCheckbox, false)
prefDisableSoundCheckbox.isChecked = false
prefDisableSoundCheckbox.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
requestNotificationPolicyAccess()
false
}
} else {
updateDisableSoundCheckBoxSummary(prefDisableSoundCheckbox, true)
prefDisableSoundCheckbox.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
if (prefDndMode.isChecked) {
prefDndMode.isChecked = false
true
} else {
false
}
}
}
}
private fun setupFlashingNotificationPref() {
val pref =
findPreference<SwitchPreferenceCompat>(PreferenceHelper.ENABLE_FLASHING_NOTIFICATION)
pref!!.onPreferenceClickListener =
if (preferenceHelper.isPro()) null else Preference.OnPreferenceClickListener {
launchUpgradeDialog(requireActivity().supportFragmentManager)
pref.isChecked = false
true
}
}
private fun setupOneMinuteLeftNotificationPref() {
val pref =
findPreference<SwitchPreferenceCompat>(PreferenceHelper.ENABLE_ONE_MINUTE_BEFORE_NOTIFICATION)
pref!!.onPreferenceClickListener =
if (preferenceHelper.isPro()) null else Preference.OnPreferenceClickListener {
launchUpgradeDialog(requireActivity().supportFragmentManager)
pref.isChecked = false
true
}
}
private fun setupDnDCheckBox() {
if (isNotificationPolicyAccessDenied) {
updateDisableSoundCheckBoxSummary(prefDndMode, false)
prefDndMode.isChecked = false
prefDndMode.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
requestNotificationPolicyAccess()
false
}
} else {
updateDisableSoundCheckBoxSummary(prefDndMode, true)
prefDndMode.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
if (prefDisableSoundCheckbox.isChecked) {
prefDisableSoundCheckbox.isChecked = false
true
} else {
false
}
}
}
}
private fun requestNotificationPolicyAccess() {
if (isNotificationPolicyAccessDenied) {
val intent = Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
startActivity(intent)
}
}
@get:TargetApi(Build.VERSION_CODES.M)
private val isNotificationPolicyAccessDenied: Boolean
get() {
val notificationManager =
requireActivity().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
return !notificationManager.isNotificationPolicyAccessGranted
}
private fun toggleEnableRingtonePreference(newValue: Boolean) {
findPreference<Preference>(PreferenceHelper.RINGTONE_WORK_FINISHED)!!.isVisible =
newValue
findPreference<Preference>(PreferenceHelper.RINGTONE_BREAK_FINISHED)!!.isVisible =
newValue
findPreference<Preference>(PreferenceHelper.PRIORITY_ALARM)!!.isVisible =
newValue
}
companion object {
private const val TAG = "SettingsFragment"
}
} | apache-2.0 | d22c7b76e33f76e7d5337d2ecede1719 | 41.972414 | 128 | 0.638669 | 6.32341 | false | false | false | false |
coconautti/sequel | src/main/kotlin/coconautti/sql/Statement.kt | 1 | 1343 | package coconautti.sql
import org.joda.time.DateTime
import java.sql.Connection
import kotlin.reflect.KClass
abstract class Statement(private val database: Database) {
fun execute(): Any? = database.execute(this)
fun execute(conn: Connection): Any? = database.execute(conn, this)
abstract fun values(): List<Value>
}
abstract class Query(val database: Database) : Statement(database) {
fun query(): List<Record> = database.query(this)
fun <T> fetch(klass: KClass<*>): List<T> = database.fetch(this, klass)
abstract fun columns(): List<Column>
}
abstract class BatchStatement(private val database: Database) {
fun execute(): List<Any> = database.execute(this)
fun execute(conn: Connection): List<Any> = database.execute(conn, this)
abstract fun values(): List<List<Value>>
}
class Column(private val name: String) {
override fun toString(): String = name
}
class Value(internal val value: Any?) {
override fun toString(): String = when (value) {
null -> "NULL"
is String -> if (isFunction(value)) value else "'$value'"
is Boolean -> if (value) "TRUE" else "FALSE"
is DateTime -> value.toString("YYYY-mm-dd hh:mm:ss.sss")
else -> value.toString()
}
private fun isFunction(value: String): Boolean = (value.contains("(") && value.endsWith(")"))
}
| apache-2.0 | dc60daedea9f4ed42dd6ea16f1cc9d62 | 32.575 | 97 | 0.674609 | 3.783099 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-indicators/src/test/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLTypeIndicatorCategoryReportIT.kt | 1 | 34338 | package net.nemerosa.ontrack.extension.indicators.ui.graphql
import net.nemerosa.ontrack.extension.indicators.AbstractIndicatorsTestSupport
import net.nemerosa.ontrack.extension.indicators.model.Rating
import net.nemerosa.ontrack.extension.indicators.support.Percentage
import net.nemerosa.ontrack.test.assertJsonNull
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class GQLTypeIndicatorCategoryReportIT : AbstractIndicatorsTestSupport() {
@Test
fun `Getting report for a category filtered on rate`() {
// Creating a view with 1 category
val category = category()
val types = (1..3).map { no ->
category.percentageType(id = "${category.id}-$no", threshold = 100) // Percentage == Compliance
}
// Projects with indicator values for this category
val projects = (1..3).map { project() }
projects.forEachIndexed { pi, project ->
types.forEachIndexed { ti, type ->
project.indicator(type, Percentage((pi * 3 + ti) * 10))
/**
* List of values
*
* Project 0
* Type 0 Value = 0 Rating = F
* Type 1 Value = 10 Rating = F
* Type 2 Value = 20 Rating = F
* Project 1
* Type 0 Value = 30 Rating = E
* Type 1 Value = 40 Rating = D
* Type 2 Value = 50 Rating = D
* Project 2
* Type 0 Value = 60 Rating = C
* Type 1 Value = 70 Rating = C
* Type 2 Value = 80 Rating = B
*/
}
}
// Getting the view report for different rates
val expectedRates = mapOf(
Rating.A to (0..2),
Rating.B to (0..2),
Rating.C to (0..2),
Rating.D to (0..1),
Rating.E to (0..1),
Rating.F to (0..0),
)
expectedRates.forEach { (rating, expectedProjects) ->
run("""
{
indicatorCategories {
categories(id: "${category.id}") {
report {
projectReport(rate: "$rating") {
project {
name
}
indicators {
rating
}
}
}
}
}
}
""").let { data ->
val reports = data.path("indicatorCategories").path("categories").first()
.path("report").path("projectReport")
val projectNames = reports.map { it.path("project").path("name").asText() }
val expectedProjectNames = expectedProjects.map { index ->
projects[index].name
}
println("---- Checking for rate $rating")
println("Expecting: $expectedProjectNames")
println("Actual : $projectNames")
assertEquals(
expectedProjectNames,
projectNames,
"Expecting ${expectedProjectNames.size} projects having rating worse or equal than $rating"
)
}
}
}
@Test
fun `Getting indicator values for all types in a category for all projects`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isNull || actualValue.isMissingNode)
}
}
}
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isNull || actualValue.isMissingNode)
}
}
}
}
}
}
@Test
fun `Getting indicator values for all types in a category only for projects having an indicator`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report(filledOnly: true) {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertJsonNull(projectReport)
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertJsonNull(projectIndicator)
}
}
}
}
}
@Test
fun `Getting indicator values for all types in a category for a project identified by name`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report(projectName: "${projects[0].name}") {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
} else {
assertJsonNull(projectReport)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertJsonNull(projectReport)
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
} else {
assertJsonNull(projectIndicator)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertJsonNull(projectIndicator)
}
}
}
}
}
@Test
fun `Getting indicator values for all types in a category for a project identified by ID`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report(projectId: ${projects[0].id}) {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
} else {
assertJsonNull(projectReport)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertJsonNull(projectReport)
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
} else {
assertJsonNull(projectIndicator)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertJsonNull(projectIndicator)
}
}
}
}
}
@Test
fun `Getting indicator values for all types in a category for projects identified by a portfolio`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
val label = label()
val portfolio = portfolio(categories = listOf(category), label = label)
projects[0].labels = listOf(label)
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report(portfolio: "${portfolio.id}") {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
} else {
assertJsonNull(projectReport)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertJsonNull(projectReport)
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
} else {
assertJsonNull(projectIndicator)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertJsonNull(projectIndicator)
}
}
}
}
}
@Test
fun `Getting indicator values for all types in a category for projects identified by a label`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
val label = label()
projects[0].labels = listOf(label)
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report(label: "${label.getDisplay()}") {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
} else {
assertJsonNull(projectReport)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertJsonNull(projectReport)
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
} else {
assertJsonNull(projectIndicator)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertJsonNull(projectIndicator)
}
}
}
}
}
} | mit | e2ddbbc55f6ea0def11377e050394a01 | 39.115654 | 111 | 0.387734 | 7.082921 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/serialization/KonanIrlinker.kt | 1 | 11312 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.serialization
import org.jetbrains.kotlin.backend.common.LoggingContext
import org.jetbrains.kotlin.backend.common.overrides.FakeOverrideBuilder
import org.jetbrains.kotlin.backend.common.overrides.PlatformFakeOverrideClassFilter
import org.jetbrains.kotlin.backend.common.serialization.*
import org.jetbrains.kotlin.backend.common.serialization.encodings.BinarySymbolData
import org.jetbrains.kotlin.backend.common.serialization.signature.IdSignatureSerializer
import org.jetbrains.kotlin.backend.konan.CachedLibraries
import org.jetbrains.kotlin.backend.konan.descriptors.isInteropLibrary
import org.jetbrains.kotlin.backend.konan.descriptors.konanLibrary
import org.jetbrains.kotlin.backend.konan.ir.interop.IrProviderForCEnumAndCStructStubs
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.konan.isNativeStdlib
import org.jetbrains.kotlin.descriptors.konan.kotlinLibrary
import org.jetbrains.kotlin.ir.builders.TranslationPluginContext
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFileImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrModuleFragmentImpl
import org.jetbrains.kotlin.ir.descriptors.IrAbstractFunctionFactory
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrFileSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrPublicSymbolBase
import org.jetbrains.kotlin.ir.types.classOrNull
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.library.IrLibrary
import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.module
object KonanFakeOverrideClassFilter : PlatformFakeOverrideClassFilter {
private fun IdSignature.isInteropSignature(): Boolean = with(this) {
IdSignature.Flags.IS_NATIVE_INTEROP_LIBRARY.test()
}
// This is an alternative to .isObjCClass that doesn't need to walk up all the class heirarchy,
// rather it only looks at immediate super class symbols.
private fun IrClass.hasInteropSuperClass() = this.superTypes
.mapNotNull { it.classOrNull }
.filter { it is IrPublicSymbolBase<*> }
.any { it.signature.isInteropSignature() }
override fun constructFakeOverrides(clazz: IrClass): Boolean {
return !clazz.hasInteropSuperClass()
}
}
internal class KonanIrLinker(
private val currentModule: ModuleDescriptor,
override val functionalInterfaceFactory: IrAbstractFunctionFactory,
override val translationPluginContext: TranslationPluginContext?,
logger: LoggingContext,
builtIns: IrBuiltIns,
symbolTable: SymbolTable,
private val forwardModuleDescriptor: ModuleDescriptor?,
private val stubGenerator: DeclarationStubGenerator,
private val cenumsProvider: IrProviderForCEnumAndCStructStubs,
exportedDependencies: List<ModuleDescriptor>,
deserializeFakeOverrides: Boolean,
private val cachedLibraries: CachedLibraries
) : KotlinIrLinker(currentModule, logger, builtIns, symbolTable, exportedDependencies, deserializeFakeOverrides) {
companion object {
private val C_NAMES_NAME = Name.identifier("cnames")
private val OBJC_NAMES_NAME = Name.identifier("objcnames")
val FORWARD_DECLARATION_ORIGIN = object : IrDeclarationOriginImpl("FORWARD_DECLARATION_ORIGIN") {}
const val offset = SYNTHETIC_OFFSET
}
override fun isBuiltInModule(moduleDescriptor: ModuleDescriptor): Boolean = moduleDescriptor.isNativeStdlib()
override val fakeOverrideBuilder = FakeOverrideBuilder(symbolTable, IdSignatureSerializer(KonanManglerIr), builtIns, KonanFakeOverrideClassFilter)
private val forwardDeclarationDeserializer = forwardModuleDescriptor?.let { KonanForwardDeclarationModuleDeserializer(it) }
override fun createModuleDeserializer(moduleDescriptor: ModuleDescriptor, klib: IrLibrary?, strategy: DeserializationStrategy): IrModuleDeserializer {
if (moduleDescriptor === forwardModuleDescriptor) {
return forwardDeclarationDeserializer ?: error("forward declaration deserializer expected")
}
if (klib is KotlinLibrary && klib.isInteropLibrary()) {
val isCached = cachedLibraries.isLibraryCached(klib)
return KonanInteropModuleDeserializer(moduleDescriptor, isCached)
}
return KonanModuleDeserializer(moduleDescriptor, klib ?: error("Expecting kotlin library"), strategy)
}
private inner class KonanModuleDeserializer(moduleDescriptor: ModuleDescriptor, klib: IrLibrary, strategy: DeserializationStrategy):
KotlinIrLinker.BasicIrModuleDeserializer(moduleDescriptor, klib, strategy)
private inner class KonanInteropModuleDeserializer(
moduleDescriptor: ModuleDescriptor,
private val isLibraryCached: Boolean
) : IrModuleDeserializer(moduleDescriptor) {
init {
assert(moduleDescriptor.kotlinLibrary.isInteropLibrary())
}
private val descriptorByIdSignatureFinder = DescriptorByIdSignatureFinder(
moduleDescriptor, KonanManglerDesc,
DescriptorByIdSignatureFinder.LookupMode.MODULE_ONLY
)
private fun IdSignature.isInteropSignature(): Boolean = IdSignature.Flags.IS_NATIVE_INTEROP_LIBRARY.test()
override fun contains(idSig: IdSignature): Boolean {
if (idSig.isPublic) {
if (idSig.isInteropSignature()) {
// TODO: add descriptor cache??
return descriptorByIdSignatureFinder.findDescriptorBySignature(idSig) != null
}
}
return false
}
private fun DeclarationDescriptor.isCEnumsOrCStruct(): Boolean = cenumsProvider.isCEnumOrCStruct(this)
private val fileMap = mutableMapOf<PackageFragmentDescriptor, IrFile>()
private fun getIrFile(packageFragment: PackageFragmentDescriptor): IrFile = fileMap.getOrPut(packageFragment) {
IrFileImpl(NaiveSourceBasedFileEntryImpl(IrProviderForCEnumAndCStructStubs.cTypeDefinitionsFileName), packageFragment).also {
moduleFragment.files.add(it)
}
}
private fun resolveCEnumsOrStruct(descriptor: DeclarationDescriptor, idSig: IdSignature, symbolKind: BinarySymbolData.SymbolKind): IrSymbol {
val file = getIrFile(descriptor.findPackage())
return cenumsProvider.getDeclaration(descriptor, idSig, file, symbolKind).symbol
}
override fun deserializeIrSymbol(idSig: IdSignature, symbolKind: BinarySymbolData.SymbolKind): IrSymbol {
val descriptor = descriptorByIdSignatureFinder.findDescriptorBySignature(idSig) ?: error("Expecting descriptor for $idSig")
// If library is cached we don't need to create an IrClass for struct or enum.
if (!isLibraryCached && descriptor.isCEnumsOrCStruct()) return resolveCEnumsOrStruct(descriptor, idSig, symbolKind)
val symbolOwner = stubGenerator.generateMemberStub(descriptor) as IrSymbolOwner
return symbolOwner.symbol
}
override val moduleFragment: IrModuleFragment = IrModuleFragmentImpl(moduleDescriptor, builtIns)
override val moduleDependencies: Collection<IrModuleDeserializer> = listOfNotNull(forwardDeclarationDeserializer)
}
private inner class KonanForwardDeclarationModuleDeserializer(moduleDescriptor: ModuleDescriptor) : IrModuleDeserializer(moduleDescriptor) {
init {
assert(moduleDescriptor.isForwardDeclarationModule)
}
private val declaredDeclaration = mutableMapOf<IdSignature, IrClass>()
private fun IdSignature.isForwardDeclarationSignature(): Boolean {
if (isPublic) {
return packageFqName().run {
startsWith(C_NAMES_NAME) || startsWith(OBJC_NAMES_NAME)
}
}
return false
}
override fun contains(idSig: IdSignature): Boolean = idSig.isForwardDeclarationSignature()
private fun resolveDescriptor(idSig: IdSignature): ClassDescriptor =
with(idSig as IdSignature.PublicSignature) {
val classId = ClassId(packageFqName(), FqName(declarationFqName), false)
moduleDescriptor.findClassAcrossModuleDependencies(classId) ?: error("No declaration found with $idSig")
}
private fun buildForwardDeclarationStub(descriptor: ClassDescriptor): IrClass {
return stubGenerator.generateClassStub(descriptor).also {
it.origin = FORWARD_DECLARATION_ORIGIN
}
}
override fun deserializeIrSymbol(idSig: IdSignature, symbolKind: BinarySymbolData.SymbolKind): IrSymbol {
assert(symbolKind == BinarySymbolData.SymbolKind.CLASS_SYMBOL) { "Only class could be a Forward declaration $idSig (kind $symbolKind)" }
val descriptor = resolveDescriptor(idSig)
val actualModule = descriptor.module
if (actualModule !== moduleDescriptor) {
val moduleDeserializer = deserializersForModules[actualModule] ?: error("No module deserializer for $actualModule")
moduleDeserializer.addModuleReachableTopLevel(idSig)
return symbolTable.referenceClassFromLinker(descriptor, idSig)
}
return declaredDeclaration.getOrPut(idSig) { buildForwardDeclarationStub(descriptor) }.symbol
}
override val moduleFragment: IrModuleFragment = IrModuleFragmentImpl(moduleDescriptor, builtIns)
override val moduleDependencies: Collection<IrModuleDeserializer> = emptyList()
}
val modules: Map<String, IrModuleFragment>
get() = mutableMapOf<String, IrModuleFragment>().apply {
deserializersForModules
.filter { !it.key.isForwardDeclarationModule && it.value.moduleDescriptor !== currentModule }
.forEach { this.put(it.key.konanLibrary!!.libraryName, it.value.moduleFragment) }
}
class KonanPluginContext(
override val moduleDescriptor: ModuleDescriptor,
override val bindingContext: BindingContext,
override val symbolTable: ReferenceSymbolTable,
override val typeTranslator: TypeTranslator,
override val irBuiltIns: IrBuiltIns
):TranslationPluginContext
}
| apache-2.0 | b5af51f7ae79007683766efe2314993c | 48.39738 | 154 | 0.736828 | 5.37132 | false | false | false | false |
goodwinnk/intellij-community | platform/configuration-store-impl/src/FileBasedStorage.kt | 1 | 11703 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.debugOrInfoIfTestMode
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtil
import com.intellij.util.LineSeparator
import com.intellij.util.io.readChars
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.loadElement
import org.jdom.Element
import org.jdom.JDOMException
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
open class FileBasedStorage(file: Path,
fileSpec: String,
rootElementName: String?,
pathMacroManager: TrackingPathMacroSubstitutor? = null,
roamingType: RoamingType? = null,
provider: StreamProvider? = null) :
XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider) {
@Volatile private var cachedVirtualFile: VirtualFile? = null
protected var lineSeparator: LineSeparator? = null
protected var blockSavingTheContent = false
@Volatile var file = file
private set
init {
if (ApplicationManager.getApplication().isUnitTestMode && file.toString().startsWith('$')) {
throw AssertionError("It seems like some macros were not expanded for path: $file")
}
}
protected open val isUseXmlProlog = false
protected open val isUseVfsForWrite = true
private val isUseUnixLineSeparator: Boolean
// only ApplicationStore doesn't use xml prolog
get() = !isUseXmlProlog
// we never set io file to null
fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: Path?) {
cachedVirtualFile = virtualFile
if (ioFileIfChanged != null) {
file = ioFileIfChanged
}
}
override fun createSaveSession(states: StateMap) = FileSaveSession(states, this)
protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) :
XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) {
override fun save() {
if (storage.blockSavingTheContent) {
LOG.info("Save blocked for ${storage.fileSpec}")
}
else {
super.save()
}
}
override fun saveLocally(dataWriter: DataWriter?) {
var lineSeparator = storage.lineSeparator
if (lineSeparator == null) {
lineSeparator = if (storage.isUseUnixLineSeparator) LineSeparator.LF else LineSeparator.getSystemLineSeparator()
storage.lineSeparator = lineSeparator
}
val isUseVfs = storage.isUseVfsForWrite
val virtualFile = if (isUseVfs) storage.virtualFile else null
if (dataWriter == null) {
if (isUseVfs && virtualFile == null) {
LOG.warn("Cannot find virtual file $virtualFile")
}
deleteFile(storage.file, this, virtualFile)
storage.cachedVirtualFile = null
}
else if (!isUseVfs) {
val file = storage.file
LOG.debugOrInfoIfTestMode { "Save $file" }
dataWriter.writeTo(file, lineSeparator.separatorString)
}
else {
storage.cachedVirtualFile = writeFile(storage.file, this, virtualFile, dataWriter, lineSeparator, storage.isUseXmlProlog)
}
}
}
val virtualFile: VirtualFile?
get() {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByPath(file.systemIndependentPath)
// otherwise virtualFile.contentsToByteArray() will query expensive FileTypeManager.getInstance()).getByFile()
result?.charset = StandardCharsets.UTF_8
cachedVirtualFile = result
}
return cachedVirtualFile
}
protected inline fun <T> runAndHandleExceptions(task: () -> T): T? {
try {
return task()
}
catch (e: JDOMException) {
processReadException(e)
}
catch (e: IOException) {
processReadException(e)
}
return null
}
fun preloadStorageData(isEmpty: Boolean) {
if (isEmpty) {
storageDataRef.set(StateMap.EMPTY)
}
else {
getStorageData()
}
}
override fun loadLocalData(): Element? {
blockSavingTheContent = false
return runAndHandleExceptions { loadLocalDataUsingIo() }
}
private fun loadLocalDataUsingIo(): Element? {
val attributes: BasicFileAttributes?
try {
attributes = Files.readAttributes(file, BasicFileAttributes::class.java)
}
catch (e: NoSuchFileException) {
LOG.debug { "Document was not loaded for $fileSpec, doesn't exist" }
return null
}
if (!attributes.isRegularFile) {
LOG.debug { "Document was not loaded for $fileSpec, not a file" }
}
else if (attributes.size() == 0L) {
processReadException(null)
}
else if (isUseUnixLineSeparator) {
// do not load the whole data into memory if no need to detect line separator
lineSeparator = LineSeparator.LF
return loadElement(file)
}
else {
val data = file.readChars()
lineSeparator = detectLineSeparators(data, if (isUseXmlProlog) null else LineSeparator.LF)
return loadElement(data)
}
return null
}
protected fun processReadException(e: Exception?) {
val contentTruncated = e == null
blockSavingTheContent = !contentTruncated &&
(PROJECT_FILE == fileSpec || fileSpec.startsWith(PROJECT_CONFIG_DIR) ||
fileSpec == StoragePathMacros.MODULE_FILE || fileSpec == StoragePathMacros.WORKSPACE_FILE)
if (e != null) {
LOG.warn(e)
}
val app = ApplicationManager.getApplication()
if (!app.isUnitTestMode && !app.isHeadlessEnvironment) {
val reason = if (contentTruncated) "content truncated" else e!!.message
val action = if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"
Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID,
"Load Settings",
"Cannot load settings from file '$file': $reason\n$action",
NotificationType.WARNING)
.notify(null)
}
}
override fun toString(): String = file.systemIndependentPath
}
internal fun writeFile(file: Path?,
requestor: Any,
virtualFile: VirtualFile?,
dataWriter: DataWriter,
lineSeparator: LineSeparator,
prependXmlProlog: Boolean): VirtualFile {
val result = if (file != null && (virtualFile == null || !virtualFile.isValid)) {
getOrCreateVirtualFile(requestor, file)
}
else {
virtualFile!!
}
if ((LOG.isDebugEnabled || ApplicationManager.getApplication().isUnitTestMode) && !FileUtilRt.isTooLarge(result.length)) {
val content = dataWriter.toBufferExposingByteArray(lineSeparator)
if (isEqualContent(result, lineSeparator, content, prependXmlProlog)) {
val contentString = content.toByteArray().toString(StandardCharsets.UTF_8)
LOG.warn("Content equals, but it must be handled not on this level: file ${result.name}, content:\n$contentString")
}
else if (DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode) {
DEBUG_LOG = "${result.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}"
}
}
doWrite(requestor, result, dataWriter, lineSeparator, prependXmlProlog)
return result
}
internal val XML_PROLOG = """<?xml version="1.0" encoding="UTF-8"?>""".toByteArray()
private fun isEqualContent(result: VirtualFile,
lineSeparator: LineSeparator,
content: BufferExposingByteArrayOutputStream,
prependXmlProlog: Boolean): Boolean {
val headerLength = if (!prependXmlProlog) 0 else XML_PROLOG.size + lineSeparator.separatorBytes.size
if (result.length.toInt() != (headerLength + content.size())) {
return false
}
val oldContent = result.contentsToByteArray()
if (prependXmlProlog && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) ||
!ArrayUtil.startsWith(oldContent, XML_PROLOG.size, lineSeparator.separatorBytes))) {
return false
}
return (headerLength until oldContent.size).all { oldContent[it] == content.internalBuffer[it - headerLength] }
}
private fun doWrite(requestor: Any, file: VirtualFile, dataWriterOrByteArray: Any, lineSeparator: LineSeparator, prependXmlProlog: Boolean) {
LOG.debugOrInfoIfTestMode { "Save ${file.presentableUrl}" }
if (!file.isWritable) {
// may be element is not long-lived, so, we must write it to byte array
val byteArray = when (dataWriterOrByteArray) {
is DataWriter -> dataWriterOrByteArray.toBufferExposingByteArray(lineSeparator)
else -> dataWriterOrByteArray as BufferExposingByteArrayOutputStream
}
throw ReadOnlyModificationException(file, object : StateStorage.SaveSession {
override fun save() {
doWrite(requestor, file, byteArray, lineSeparator, prependXmlProlog)
}
})
}
runUndoTransparentWriteAction {
file.getOutputStream(requestor).use { output ->
if (prependXmlProlog) {
output.write(XML_PROLOG)
output.write(lineSeparator.separatorBytes)
}
if (dataWriterOrByteArray is DataWriter) {
dataWriterOrByteArray.write(output, lineSeparator.separatorString)
}
else {
(dataWriterOrByteArray as BufferExposingByteArrayOutputStream).writeTo(output)
}
}
}
}
internal fun detectLineSeparators(chars: CharSequence, defaultSeparator: LineSeparator? = null): LineSeparator {
for (c in chars) {
if (c == '\r') {
return LineSeparator.CRLF
}
else if (c == '\n') {
// if we are here, there was no \r before
return LineSeparator.LF
}
}
return defaultSeparator ?: LineSeparator.getSystemLineSeparator()
}
private fun deleteFile(file: Path, requestor: Any, virtualFile: VirtualFile?) {
if (virtualFile == null) {
try {
Files.delete(file)
}
catch (ignored: NoSuchFileException) {
}
}
else if (virtualFile.exists()) {
if (virtualFile.isWritable) {
deleteFile(requestor, virtualFile)
}
else {
throw ReadOnlyModificationException(virtualFile, object : StateStorage.SaveSession {
override fun save() {
deleteFile(requestor, virtualFile)
}
})
}
}
}
internal fun deleteFile(requestor: Any, virtualFile: VirtualFile) {
runUndoTransparentWriteAction { virtualFile.delete(requestor) }
}
internal class ReadOnlyModificationException(val file: VirtualFile, val session: StateStorage.SaveSession?) : RuntimeException("File is read-only: $file") | apache-2.0 | 64d8727bba544bc9e5036571b79690ef | 34.792049 | 154 | 0.694865 | 5.011991 | false | false | false | false |
goodwinnk/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/IconsClassGenerator.kt | 1 | 13958 | // 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.intellij.build.images
import com.intellij.openapi.util.io.FileUtilRt
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.nio.charset.StandardCharsets
import java.nio.file.*
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
data class ModifiedClass(val module: JpsModule, val file: Path, val result: CharSequence)
class IconsClassGenerator(private val projectHome: File, val util: JpsModule, private val writeChangesToDisk: Boolean = true) {
private val processedClasses = AtomicInteger()
private val processedIcons = AtomicInteger()
private val processedPhantom = AtomicInteger()
private val modifiedClasses = ContainerUtil.createConcurrentList<ModifiedClass>()
fun processModule(module: JpsModule) {
val customLoad: Boolean
val packageName: String
val className: String
val outFile: Path
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 = Paths.get(dir, "AllIcons.java")
}
else {
customLoad = true
packageName = "icons"
val firstRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).firstOrNull() ?: return
val firstRootDir = firstRoot.file.toPath().resolve("icons")
var oldClassName: String?
// this is added to remove unneeded empty directories created by previous version of this script
if (Files.isDirectory(firstRootDir)) {
try {
Files.delete(firstRootDir)
println("deleting empty directory $firstRootDir")
}
catch (ignore: DirectoryNotEmptyException) {
}
oldClassName = findIconClass(firstRootDir)
}
else {
oldClassName = null
}
val generatedRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).find { it.properties.isForGeneratedSources }
val targetRoot = (generatedRoot ?: firstRoot).file.toPath().resolve("icons")
if (generatedRoot != null && oldClassName != null) {
val oldFile = firstRootDir.resolve("$oldClassName.java")
println("deleting $oldFile from source root which isn't marked as 'generated'")
Files.delete(oldFile)
}
if (oldClassName == null) {
try {
oldClassName = findIconClass(targetRoot)
}
catch (ignored: NoSuchFileException) {
}
}
className = oldClassName ?: directoryName(module) + "Icons"
outFile = targetRoot.resolve("$className.java")
}
val oldText = if (Files.exists(outFile)) Files.readAllBytes(outFile).toString(StandardCharsets.UTF_8) else null
val newText = generate(module, className, packageName, customLoad, getCopyrightComment(oldText))
val oldLines = oldText?.lines() ?: emptyList()
val newLines = newText?.lines() ?: emptyList()
if (newLines.isNotEmpty()) {
processedClasses.incrementAndGet()
if (oldLines != newLines) {
if (writeChangesToDisk) {
val separator = getSeparators(oldText)
Files.createDirectories(outFile.parent)
Files.write(outFile, newLines.joinToString(separator = separator.separatorString).toByteArray())
println("Updated icons class: ${outFile.fileName}")
}
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(ModifiedClass(module, outFile, sb))
}
}
}
}
fun printStats() {
println()
println("Generated classes: ${processedClasses.get()}. Processed icons: ${processedIcons.get()}. Phantom icons: ${processedPhantom.get()}")
}
fun getModifiedClasses(): List<ModifiedClass> = modifiedClasses
private fun findIconClass(dir: Path): String? {
Files.newDirectoryStream(dir).use { stream ->
for (it in stream) {
val name = it.fileName.toString()
if (name.endsWith("Icons.java")) {
return name.substring(0, name.length - ".java".length)
}
}
}
return null
}
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.toPath(), iconsOnly = true, className = className)
val images = imageCollector.collect(module, includePhantom = true)
if (images.isEmpty()) {
return null
}
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) }
fun getWeight(key: String): Int {
val image = leafMap[key]
if (image == null) {
return 0
}
return if (image.deprecated) 1 else 0
}
val sortedKeys = (nodeMap.keys + leafMap.keys)
.sortedWith(NAME_COMPARATOR)
.sortedWith(kotlin.Comparator(function = { o1, o2 ->
getWeight(o1) - getWeight(o2)
}))
for (key in sortedKeys) {
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 ?: return
if (!image.phantom && !isIcon(file)) {
return
}
processedIcons.incrementAndGet()
if (image.phantom) {
processedPhantom.incrementAndGet()
}
if (image.used || image.deprecated) {
val deprecationComment = image.deprecation?.comment
append(answer, "", level)
if (deprecationComment != null) {
append(answer, "/** @deprecated $deprecationComment */", level)
}
append(answer, "@SuppressWarnings(\"unused\")", level)
}
if (image.deprecated) {
append(answer, "@Deprecated", level)
}
val sourceRoot = image.sourceRoot
var rootPrefix = "/"
if (sourceRoot.rootType == JavaSourceRootType.SOURCE) {
@Suppress("UNCHECKED_CAST")
val packagePrefix = (sourceRoot.properties as JpsSimpleElement<JavaSourceRootProperties>).data.packagePrefix
if (!packagePrefix.isEmpty()) {
rootPrefix += packagePrefix.replace('.', '/') + "/"
}
}
val iconName = iconName(file)
val deprecation = image.deprecation
if (deprecation?.replacementContextClazz != null) {
val method = if (customLoad) "load" else "IconLoader.getIcon"
append(answer,
"public static final Icon $iconName = $method(\"${deprecation.replacement}\", ${deprecation.replacementContextClazz}.class);",
level)
return
}
else if (deprecation?.replacementReference != null) {
append(answer, "public static final Icon $iconName = ${deprecation.replacementReference};", level)
return
}
val sourceRootFile = Paths.get(JpsPathUtil.urlToPath(sourceRoot.url))
val imageFile: Path
if (deprecation?.replacement == null) {
imageFile = file
}
else {
imageFile = sourceRootFile.resolve(deprecation.replacement.removePrefix("/").removePrefix(File.separator))
assert(isIcon(imageFile)) { "Overriding icon should be valid: $iconName - $imageFile" }
}
val size = if (Files.exists(imageFile)) imageSize(imageFile) else null
val comment: String
when {
size != null -> comment = " // ${size.width}x${size.height}"
image.phantom -> comment = ""
else -> error("Can't get icon size: $imageFile")
}
val method = if (customLoad) "load" else "IconLoader.getIcon"
val relativePath = rootPrefix + FileUtilRt.toSystemIndependentName(sourceRootFile.relativize(imageFile).toString())
append(answer,
"public static final Icon $iconName = $method(\"$relativePath\");$comment",
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 = image.id.removePrefix("/").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, 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: Path): String {
val name = capitalize(file.fileName.toString().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 | 97811525921e1f8b5d895fe120018162 | 33.982456 | 143 | 0.652601 | 4.400378 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/language/VariableDefinition.kt | 1 | 1129 | package graphql.language
class VariableDefinition : AbstractNode {
val name: String
var type: Type? = null
var defaultValue: Value? = null
constructor(name: String) {
this.name = name
}
constructor(name: String, type: Type) : this(name){
this.type = type
}
constructor(name: String, type: Type, defaultValue: Value) : this(name, type){
this.defaultValue = defaultValue
}
override val children: List<Node>
get() {
val result = mutableListOf<Node>()
type?.let { result.add(it) }
defaultValue?.let { result.add(it) }
return result
}
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
val that = node as VariableDefinition
return name == that.name
}
override fun toString(): String {
return "VariableDefinition{" +
"name='" + name + '\'' +
", type=" + type +
", defaultValue=" + defaultValue +
'}'
}
}
| mit | 531095c7b011663fdb6ae77d5b3f34a4 | 23.543478 | 82 | 0.546501 | 4.608163 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/operators/IteratorOperator.kt | 2 | 583 | package me.ztiany.operators
import java.time.LocalDate
operator fun ClosedRange<LocalDate>.iterator(): Iterator<LocalDate> =
object : Iterator<LocalDate> {
var current = start
override fun hasNext() =
current <= endInclusive
override fun next() = current.apply {
current = plusDays(1)
}
}
fun main(args: Array<String>) {
val newYear = LocalDate.ofYearDay(2017, 1)
val daysOff = newYear.minusDays(1)..newYear
for (dayOff in daysOff) {
println(dayOff)
}
}
| apache-2.0 | 51bd930729954a32264087df61c1dac3 | 24.347826 | 69 | 0.584906 | 4.286765 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/PushNotificationStatusPreference.kt | 1 | 3142 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.preference
import android.content.Context
import android.content.SharedPreferences
import android.support.v7.preference.Preference
import android.text.TextUtils
import android.util.AttributeSet
import org.mariotaku.abstask.library.AbstractTask
import org.mariotaku.abstask.library.TaskStarter
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.TwittnukerConstants.*
import de.vanita5.twittnuker.constant.SharedPreferenceConstants
import de.vanita5.twittnuker.push.PushBackendServer
class PushNotificationStatusPreference @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = R.attr.preferenceStyle
) : Preference(context, attrs, defStyle) {
private val preferences: SharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
init {
setTitle(R.string.push_status_title)
if (preferences.getBoolean(SharedPreferenceConstants.GCM_TOKEN_SENT, false)) {
setSummary(R.string.push_status_connected)
} else {
setSummary(R.string.push_status_disconnected)
}
}
override fun onClick() {
setSummary(R.string.push_status_disconnecting)
super.onClick()
val task = object : AbstractTask<Any?, Unit, PushNotificationStatusPreference>() {
override fun afterExecute(pushNotificationStatusPreference: PushNotificationStatusPreference?, result: Unit?) {
pushNotificationStatusPreference!!.setSummary(R.string.push_status_disconnected)
}
override fun doLongOperation(param: Any?) {
val currentToken = preferences.getString(SharedPreferenceConstants.GCM_CURRENT_TOKEN, null)
if (!TextUtils.isEmpty(currentToken)) {
val backend = PushBackendServer(context)
backend.remove(currentToken)
preferences.edit().putBoolean(SharedPreferenceConstants.GCM_TOKEN_SENT, false).apply()
preferences.edit().putString(SharedPreferenceConstants.GCM_CURRENT_TOKEN, null).apply()
}
}
}
task.callback = this
TaskStarter.execute(task)
}
}
| gpl-3.0 | 0d01c54694bd07ef37734093611d5c41 | 37.790123 | 124 | 0.711649 | 4.668648 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/PaymentAuthConfig.kt | 1 | 22042 | package com.stripe.android
import android.app.Activity
import android.os.Parcelable
import androidx.annotation.IntRange
import com.stripe.android.stripe3ds2.init.ui.ButtonCustomization
import com.stripe.android.stripe3ds2.init.ui.LabelCustomization
import com.stripe.android.stripe3ds2.init.ui.StripeButtonCustomization
import com.stripe.android.stripe3ds2.init.ui.StripeLabelCustomization
import com.stripe.android.stripe3ds2.init.ui.StripeTextBoxCustomization
import com.stripe.android.stripe3ds2.init.ui.StripeToolbarCustomization
import com.stripe.android.stripe3ds2.init.ui.StripeUiCustomization
import com.stripe.android.stripe3ds2.init.ui.TextBoxCustomization
import com.stripe.android.stripe3ds2.init.ui.ToolbarCustomization
import com.stripe.android.stripe3ds2.init.ui.UiCustomization
import kotlinx.parcelize.Parcelize
/**
* Configuration for authentication mechanisms via [StripePaymentController]
*/
class PaymentAuthConfig private constructor(
internal val stripe3ds2Config: Stripe3ds2Config
) {
class Builder : ObjectBuilder<PaymentAuthConfig> {
private var stripe3ds2Config: Stripe3ds2Config? = null
fun set3ds2Config(stripe3ds2Config: Stripe3ds2Config): Builder = apply {
this.stripe3ds2Config = stripe3ds2Config
}
override fun build(): PaymentAuthConfig {
return PaymentAuthConfig(requireNotNull(stripe3ds2Config))
}
}
@Parcelize
data class Stripe3ds2Config internal constructor(
@IntRange(from = 5, to = 99) internal val timeout: Int,
internal val uiCustomization: Stripe3ds2UiCustomization
) : Parcelable {
init {
checkValidTimeout(timeout)
}
private fun checkValidTimeout(timeout: Int) {
require(!(timeout < 5 || timeout > 99)) {
"Timeout value must be between 5 and 99, inclusive"
}
}
class Builder : ObjectBuilder<Stripe3ds2Config> {
private var timeout = DEFAULT_TIMEOUT
private var uiCustomization =
Stripe3ds2UiCustomization.Builder().build()
/**
* The 3DS2 challenge flow timeout, in minutes.
*
* If the timeout is reached, the challenge screen will close, control will return to
* the launching Activity/Fragment, payment authentication will not succeed, and the
* outcome will be represented as [StripeIntentResult.Outcome.TIMEDOUT].
*
* Must be a value between 5 and 99, inclusive.
*/
fun setTimeout(@IntRange(from = 5, to = 99) timeout: Int): Builder = apply {
this.timeout = timeout
}
fun setUiCustomization(uiCustomization: Stripe3ds2UiCustomization): Builder = apply {
this.uiCustomization = uiCustomization
}
override fun build(): Stripe3ds2Config {
return Stripe3ds2Config(
timeout = timeout,
uiCustomization = uiCustomization
)
}
}
internal companion object {
internal const val DEFAULT_TIMEOUT = 5
}
}
/**
* Customization for 3DS2 buttons
*/
data class Stripe3ds2ButtonCustomization internal constructor(
internal val buttonCustomization: ButtonCustomization
) {
class Builder : ObjectBuilder<Stripe3ds2ButtonCustomization> {
private val buttonCustomization: ButtonCustomization = StripeButtonCustomization()
/**
* Set the button's background color
*
* @param hexColor The button's background color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setBackgroundColor(hexColor: String): Builder = apply {
buttonCustomization.backgroundColor = hexColor
}
/**
* Set the corner radius of the button
*
* @param cornerRadius The radius of the button in pixels
* @throws RuntimeException If the corner radius is less than 0
*/
@Throws(RuntimeException::class)
fun setCornerRadius(cornerRadius: Int): Builder = apply {
buttonCustomization.cornerRadius = cornerRadius
}
/**
* Set the button's text font
*
* @param fontName The name of the font. If not found, default system font used
* @throws RuntimeException If font name is null or empty
*/
@Throws(RuntimeException::class)
fun setTextFontName(fontName: String): Builder = apply {
buttonCustomization.textFontName = fontName
}
/**
* Set the button's text color
*
* @param hexColor The button's text color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setTextColor(hexColor: String): Builder = apply {
buttonCustomization.textColor = hexColor
}
/**
* Set the button's text size
*
* @param fontSize The size of the font in scaled-pixels (sp)
* @throws RuntimeException If the font size is 0 or less
*/
@Throws(RuntimeException::class)
fun setTextFontSize(fontSize: Int): Builder = apply {
buttonCustomization.textFontSize = fontSize
}
/**
* Build the button customization
*
* @return The built button customization
*/
override fun build(): Stripe3ds2ButtonCustomization {
return Stripe3ds2ButtonCustomization(buttonCustomization)
}
}
}
/**
* Customization for 3DS2 labels
*/
data class Stripe3ds2LabelCustomization internal constructor(
internal val labelCustomization: LabelCustomization
) {
class Builder : ObjectBuilder<Stripe3ds2LabelCustomization> {
private val labelCustomization: LabelCustomization = StripeLabelCustomization()
/**
* Set the text color for heading labels
*
* @param hexColor The heading labels's text color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setHeadingTextColor(hexColor: String): Builder = apply {
labelCustomization.headingTextColor = hexColor
}
/**
* Set the heading label's font
*
* @param fontName The name of the font. Defaults to system font if not found
* @throws RuntimeException If the font name is null or empty
*/
@Throws(RuntimeException::class)
fun setHeadingTextFontName(fontName: String): Builder = apply {
labelCustomization.headingTextFontName = fontName
}
/**
* Set the heading label's text size
*
* @param fontSize The size of the heading label in scaled-pixels (sp).
* @throws RuntimeException If the font size is 0 or less
*/
@Throws(RuntimeException::class)
fun setHeadingTextFontSize(fontSize: Int): Builder = apply {
labelCustomization.headingTextFontSize = fontSize
}
/**
* Set the label's font
*
* @param fontName The name of the font. Defaults to system font if not found
* @throws RuntimeException If the font name is null or empty
*/
@Throws(RuntimeException::class)
fun setTextFontName(fontName: String): Builder = apply {
labelCustomization.textFontName = fontName
}
/**
* Set the label's text color
*
* @param hexColor The labels's text color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setTextColor(hexColor: String): Builder = apply {
labelCustomization.textColor = hexColor
}
/**
* Set the label's text size
*
* @param fontSize The label's font size in scaled-pixels (sp)
* @throws RuntimeException If the font size is 0 or less
*/
@Throws(RuntimeException::class)
fun setTextFontSize(fontSize: Int): Builder = apply {
labelCustomization.textFontSize = fontSize
}
/**
* Build the configured label customization
*
* @return The built label customization
*/
override fun build(): Stripe3ds2LabelCustomization {
return Stripe3ds2LabelCustomization(labelCustomization)
}
}
}
/**
* Customization for 3DS2 text entry
*/
data class Stripe3ds2TextBoxCustomization internal constructor(
internal val textBoxCustomization: TextBoxCustomization
) {
class Builder : ObjectBuilder<Stripe3ds2TextBoxCustomization> {
private val textBoxCustomization: TextBoxCustomization = StripeTextBoxCustomization()
/**
* Set the width of the border around the text entry box
*
* @param borderWidth Width of the border in pixels
* @throws RuntimeException If the border width is less than 0
*/
@Throws(RuntimeException::class)
fun setBorderWidth(borderWidth: Int): Builder = apply {
textBoxCustomization.borderWidth = borderWidth
}
/**
* Set the color of the border around the text entry box
*
* @param hexColor The border's color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setBorderColor(hexColor: String): Builder = apply {
textBoxCustomization.borderColor = hexColor
}
/**
* Set the corner radius of the text entry box
*
* @param cornerRadius The corner radius in pixels
* @throws RuntimeException If the corner radius is less than 0
*/
@Throws(RuntimeException::class)
fun setCornerRadius(cornerRadius: Int): Builder = apply {
textBoxCustomization.cornerRadius = cornerRadius
}
/**
* Set the font for text entry
*
* @param fontName The name of the font. The system default is used if not found.
* @throws RuntimeException If the font name is null or empty.
*/
@Throws(RuntimeException::class)
fun setTextFontName(fontName: String): Builder = apply {
textBoxCustomization.textFontName = fontName
}
/**
* Set the text color for text entry
*
* @param hexColor The text color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setTextColor(hexColor: String): Builder = apply {
textBoxCustomization.textColor = hexColor
}
/**
* Set the text entry font size
*
* @param fontSize The font size in scaled-pixels (sp)
* @throws RuntimeException If the font size is 0 or less
*/
@Throws(RuntimeException::class)
fun setTextFontSize(fontSize: Int): Builder = apply {
textBoxCustomization.textFontSize = fontSize
}
/**
* Build the text box customization
*
* @return The text box customization
*/
override fun build(): Stripe3ds2TextBoxCustomization {
return Stripe3ds2TextBoxCustomization(textBoxCustomization)
}
}
}
/**
* Customization for the 3DS2 toolbar
*/
data class Stripe3ds2ToolbarCustomization internal constructor(
internal val toolbarCustomization: ToolbarCustomization
) {
class Builder : ObjectBuilder<Stripe3ds2ToolbarCustomization> {
private val toolbarCustomization: ToolbarCustomization = StripeToolbarCustomization()
/**
* Set the toolbar's background color
*
* @param hexColor The background color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setBackgroundColor(hexColor: String): Builder = apply {
toolbarCustomization.backgroundColor = hexColor
}
/**
* Set the status bar color, if not provided a darkened version of the background
* color will be used.
*
* @param hexColor The status bar color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setStatusBarColor(hexColor: String): Builder = apply {
toolbarCustomization.statusBarColor = hexColor
}
/**
* Set the toolbar's title
*
* @param headerText The toolbar's title text
* @throws RuntimeException if the title is null or empty
*/
@Throws(RuntimeException::class)
fun setHeaderText(headerText: String): Builder = apply {
toolbarCustomization.headerText = headerText
}
/**
* Set the toolbar's cancel button text
*
* @param buttonText The cancel button's text
* @throws RuntimeException If the button text is null or empty
*/
@Throws(RuntimeException::class)
fun setButtonText(buttonText: String): Builder = apply {
toolbarCustomization.buttonText = buttonText
}
/**
* Set the font for the title text
*
* @param fontName The name of the font. System default is used if not found
* @throws RuntimeException If the font name is null or empty
*/
@Throws(RuntimeException::class)
fun setTextFontName(fontName: String): Builder = apply {
toolbarCustomization.textFontName = fontName
}
/**
* Set the color of the title text
*
* @param hexColor The title's text color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setTextColor(hexColor: String): Builder = apply {
toolbarCustomization.textColor = hexColor
}
/**
* Set the title text's font size
*
* @param fontSize The size of the title text in scaled-pixels (sp)
* @throws RuntimeException If the font size is 0 or less
*/
@Throws(RuntimeException::class)
fun setTextFontSize(fontSize: Int): Builder = apply {
toolbarCustomization.textFontSize = fontSize
}
/**
* Build the toolbar customization
*
* @return The built toolbar customization
*/
override fun build(): Stripe3ds2ToolbarCustomization {
return Stripe3ds2ToolbarCustomization(toolbarCustomization)
}
}
}
/**
* Customizations for the 3DS2 UI
*/
@Parcelize
data class Stripe3ds2UiCustomization internal constructor(
val uiCustomization: StripeUiCustomization
) : Parcelable {
/**
* The type of button for which customization can be set
*/
enum class ButtonType {
SUBMIT,
CONTINUE,
NEXT,
CANCEL,
RESEND,
SELECT
}
class Builder private constructor(
private val uiCustomization: StripeUiCustomization
) : ObjectBuilder<Stripe3ds2UiCustomization> {
constructor() : this(StripeUiCustomization())
private constructor(activity: Activity) : this(
StripeUiCustomization.createWithAppTheme(activity)
)
@Throws(RuntimeException::class)
private fun getUiButtonType(buttonType: ButtonType): UiCustomization.ButtonType {
return when (buttonType) {
ButtonType.SUBMIT ->
UiCustomization.ButtonType.SUBMIT
ButtonType.CONTINUE ->
UiCustomization.ButtonType.CONTINUE
ButtonType.NEXT ->
UiCustomization.ButtonType.NEXT
ButtonType.CANCEL ->
UiCustomization.ButtonType.CANCEL
ButtonType.RESEND ->
UiCustomization.ButtonType.RESEND
ButtonType.SELECT ->
UiCustomization.ButtonType.SELECT
}
}
/**
* Set the customization for a particular button
*
* @param buttonCustomization The button customization data
* @param buttonType The type of button to customize
* @throws RuntimeException If any customization data is invalid
*/
@Throws(RuntimeException::class)
fun setButtonCustomization(
buttonCustomization: Stripe3ds2ButtonCustomization,
buttonType: ButtonType
): Builder = apply {
uiCustomization.setButtonCustomization(
buttonCustomization.buttonCustomization,
getUiButtonType(buttonType)
)
}
/**
* Set the customization data for the 3DS2 toolbar
*
* @param toolbarCustomization Toolbar customization data
* @throws RuntimeException If any customization data is invalid
*/
@Throws(RuntimeException::class)
fun setToolbarCustomization(
toolbarCustomization: Stripe3ds2ToolbarCustomization
): Builder = apply {
uiCustomization
.setToolbarCustomization(toolbarCustomization.toolbarCustomization)
}
/**
* Set the 3DS2 label customization
*
* @param labelCustomization Label customization data
* @throws RuntimeException If any customization data is invalid
*/
@Throws(RuntimeException::class)
fun setLabelCustomization(
labelCustomization: Stripe3ds2LabelCustomization
): Builder = apply {
uiCustomization.setLabelCustomization(labelCustomization.labelCustomization)
}
/**
* Set the 3DS2 text box customization
*
* @param textBoxCustomization Text box customization data
* @throws RuntimeException If any customization data is invalid
*/
@Throws(RuntimeException::class)
fun setTextBoxCustomization(
textBoxCustomization: Stripe3ds2TextBoxCustomization
): Builder = apply {
uiCustomization
.setTextBoxCustomization(textBoxCustomization.textBoxCustomization)
}
/**
* Set the accent color
*
* @param hexColor The accent color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setAccentColor(hexColor: String): Builder = apply {
uiCustomization.setAccentColor(hexColor)
}
/**
* Build the UI customization
*
* @return the built UI customization
*/
override fun build(): Stripe3ds2UiCustomization {
return Stripe3ds2UiCustomization(uiCustomization)
}
companion object {
@JvmStatic
fun createWithAppTheme(activity: Activity): Builder {
return Builder(activity)
}
}
}
}
companion object {
private var instance: PaymentAuthConfig? = null
private val DEFAULT = Builder()
.set3ds2Config(Stripe3ds2Config.Builder().build())
.build()
@JvmStatic
fun init(config: PaymentAuthConfig) {
instance = config
}
@JvmStatic
fun get(): PaymentAuthConfig {
return instance ?: DEFAULT
}
@JvmSynthetic
internal fun reset() {
instance = null
}
}
}
| mit | cd9a25111be234497c6bb9438e971634 | 36.42275 | 97 | 0.569368 | 6.010908 | false | false | false | false |
exponent/exponent | packages/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/ForegroundLocationRequester.kt | 2 | 1216 | package expo.modules.permissions.requesters
import android.Manifest
import android.os.Bundle
import expo.modules.interfaces.permissions.PermissionsResponse
import expo.modules.interfaces.permissions.PermissionsStatus
class ForegroundLocationRequester : PermissionRequester {
override fun getAndroidPermissions() = listOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
override fun parseAndroidPermissions(permissionsResponse: Map<String, PermissionsResponse>): Bundle {
return parseBasicLocationPermissions(permissionsResponse).apply {
val accessFineLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_FINE_LOCATION)
val accessCoarseLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_COARSE_LOCATION)
val accuracy = when {
accessFineLocation.status == PermissionsStatus.GRANTED -> {
"fine"
}
accessCoarseLocation.status == PermissionsStatus.GRANTED -> {
"coarse"
}
else -> {
"none"
}
}
putBundle(
"android",
Bundle().apply {
putString("accuracy", accuracy)
}
)
}
}
}
| bsd-3-clause | ea64c61269d7c57c8ffdb6f84ec4ee13 | 30.179487 | 105 | 0.70477 | 5.428571 | false | false | false | false |
exponent/exponent | packages/expo-application/android/src/main/java/expo/modules/application/ApplicationModule.kt | 2 | 5546 | package expo.modules.application
import android.app.Activity
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager.NameNotFoundException
import android.os.Build
import android.os.RemoteException
import android.provider.Settings
import android.util.Log
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.Promise
import expo.modules.core.interfaces.ActivityProvider
import expo.modules.core.interfaces.ExpoMethod
import expo.modules.core.interfaces.RegistryLifecycleListener
import java.util.*
private const val NAME = "ExpoApplication"
private val TAG = ApplicationModule::class.java.simpleName
class ApplicationModule(private val mContext: Context) : ExportedModule(mContext), RegistryLifecycleListener {
private var mModuleRegistry: ModuleRegistry? = null
private var mActivityProvider: ActivityProvider? = null
private var mActivity: Activity? = null
override fun getName(): String {
return NAME
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
mModuleRegistry = moduleRegistry
mActivityProvider = moduleRegistry.getModule(ActivityProvider::class.java)
mActivity = mActivityProvider?.currentActivity
}
override fun getConstants(): Map<String, Any?> {
val constants = HashMap<String, Any?>()
val applicationName = mContext.applicationInfo.loadLabel(mContext.packageManager).toString()
val packageName = mContext.packageName
constants["applicationName"] = applicationName
constants["applicationId"] = packageName
val packageManager = mContext.packageManager
try {
val pInfo = packageManager.getPackageInfo(packageName, 0)
constants["nativeApplicationVersion"] = pInfo.versionName
val versionCode = getLongVersionCode(pInfo).toInt()
constants["nativeBuildVersion"] = versionCode.toString()
} catch (e: NameNotFoundException) {
Log.e(TAG, "Exception: ", e)
}
constants["androidId"] = Settings.Secure.getString(mContext.contentResolver, Settings.Secure.ANDROID_ID)
return constants
}
@ExpoMethod
fun getInstallationTimeAsync(promise: Promise) {
val packageManager = mContext.packageManager
val packageName = mContext.packageName
try {
val info = packageManager.getPackageInfo(packageName, 0)
promise.resolve(info.firstInstallTime.toDouble())
} catch (e: NameNotFoundException) {
Log.e(TAG, "Exception: ", e)
promise.reject("ERR_APPLICATION_PACKAGE_NAME_NOT_FOUND", "Unable to get install time of this application. Could not get package info or package name.", e)
}
}
@ExpoMethod
fun getLastUpdateTimeAsync(promise: Promise) {
val packageManager = mContext.packageManager
val packageName = mContext.packageName
try {
val info = packageManager.getPackageInfo(packageName, 0)
promise.resolve(info.lastUpdateTime.toDouble())
} catch (e: NameNotFoundException) {
Log.e(TAG, "Exception: ", e)
promise.reject("ERR_APPLICATION_PACKAGE_NAME_NOT_FOUND", "Unable to get last update time of this application. Could not get package info or package name.", e)
}
}
@ExpoMethod
fun getInstallReferrerAsync(promise: Promise) {
val installReferrer = StringBuilder()
val referrerClient = InstallReferrerClient.newBuilder(mContext).build()
referrerClient.startConnection(object : InstallReferrerStateListener {
override fun onInstallReferrerSetupFinished(responseCode: Int) {
when (responseCode) {
InstallReferrerClient.InstallReferrerResponse.OK -> {
// Connection established and response received
try {
val response = referrerClient.installReferrer
installReferrer.append(response.installReferrer)
} catch (e: RemoteException) {
Log.e(TAG, "Exception: ", e)
promise.reject("ERR_APPLICATION_INSTALL_REFERRER_REMOTE_EXCEPTION", "RemoteException getting install referrer information. This may happen if the process hosting the remote object is no longer available.", e)
}
promise.resolve(installReferrer.toString())
}
InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> // API not available in the current Play Store app
promise.reject("ERR_APPLICATION_INSTALL_REFERRER_UNAVAILABLE", "The current Play Store app doesn't provide the installation referrer API, or the Play Store may not be installed.")
InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> // Connection could not be established
promise.reject("ERR_APPLICATION_INSTALL_REFERRER_CONNECTION", "Could not establish a connection to Google Play")
else -> promise.reject("ERR_APPLICATION_INSTALL_REFERRER", "General error retrieving the install referrer: response code $responseCode")
}
referrerClient.endConnection()
}
override fun onInstallReferrerServiceDisconnected() {
promise.reject("ERR_APPLICATION_INSTALL_REFERRER_SERVICE_DISCONNECTED", "Connection to install referrer service was lost.")
}
})
}
companion object {
private fun getLongVersionCode(info: PackageInfo): Long {
return if (Build.VERSION.SDK_INT >= 28) {
info.longVersionCode
} else {
info.versionCode.toLong()
}
}
}
}
| bsd-3-clause | 2bcf612369447fce6a39b32adc6331b1 | 40.699248 | 222 | 0.736567 | 4.978456 | false | false | false | false |
snumr/logic-games-framework | src/logicgames/ui/FXBasic.kt | 1 | 2862 | /*
* The MIT License
*
* Copyright 2014 Alexander Alexeev.
*
*/
package org.mumidol.logicgames.ui
import javafx.application.Application
import java.util.concurrent.Executors
import org.mumidol.logicgames.MultiPlayerGame
import org.mumidol.logicgames.Player
import org.mumidol.logicgames.IllegalTurnException
import javafx.stage.Stage
import org.mumidol.logicgames.Game
import javafx.concurrent.Task
import kotlin.util.measureTimeMillis
import java.util.concurrent.locks.ReentrantLock
import kotlin.properties.Delegates
/**
* Created on 27.11.2014.
*/
class PlayerTurnTask<G : MultiPlayerGame>(val game: G, val player: Player<G>, val onSuccess: (Game.Turn<G>) -> Unit):
Task<Game.Turn<G>>() {
override fun call(): Game.Turn<G>? {
var t: Game.Turn<G>? = null
val time = measureTimeMillis { t = player.turn(game) }
println("Time: $time")
return t
}
override fun failed() {
super<Task>.failed()
println("Failure :-(. ${ getException()?.toString() ?: ""}")
getException()?.printStackTrace()
}
override fun succeeded() {
super<Task>.succeeded()
onSuccess(get())
}
}
trait GameObserver<G : MultiPlayerGame> {
public fun started(game: G)
public fun turn(game: G)
public fun gameOver(game: G)
}
public fun play<G : MultiPlayerGame>(start: G, o: GameObserver<G>, vararg players: Player<G>) {
// var game = start
// val pool = Executors.newFixedThreadPool(1)
fun submit(game: G) {
Thread(PlayerTurnTask(game, players[game.currPlayer], { turn ->
if (turn.game == game) {
val g = turn.move()
if (g.isOver) {
// pool.shutdown()
o.gameOver(g)
} else {
o.turn(g)
submit(turn.move())
}
} else {
throw IllegalTurnException()
}
})).start()
}
o.started(start)
submit(start)
}
public abstract class AsyncHumanPlayer<G : MultiPlayerGame> : Player<G> {
val lock = ReentrantLock()
val waiting = lock.newCondition()
var turn: Game.Turn<G> by Delegates.notNull()
public override fun turn(game: G): Game.Turn<G> {
lock.lock()
try {
startWaiting(game)
waiting.await()
return turn
} finally {
lock.unlock()
}
}
public fun moved(turn: Game.Turn<G>) {
lock.lock()
try {
this.turn = turn
waiting.signal()
} finally {
lock.unlock()
}
}
public fun interrupt() {
lock.lock()
try {
waiting.signal()
} finally {
lock.unlock()
}
}
public abstract fun startWaiting(game: G)
}
| mit | f52d1ff298638347cb09d7bb811259ae | 23.672414 | 117 | 0.567435 | 4.100287 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/actions/runAnything/RsRunAnythingProvider.kt | 2 | 3396 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions.runAnything
import com.intellij.execution.Executor
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.ide.actions.runAnything.RunAnythingAction
import com.intellij.ide.actions.runAnything.RunAnythingContext
import com.intellij.ide.actions.runAnything.activity.RunAnythingProviderBase
import com.intellij.ide.actions.runAnything.getPath
import com.intellij.ide.actions.runAnything.items.RunAnythingItem
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil.trimStart
import com.intellij.util.execution.ParametersListUtil
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.runconfig.getAppropriateCargoProject
import org.rust.cargo.runconfig.hasCargoProject
import org.rust.cargo.util.RsCommandCompletionProvider
import org.rust.stdext.toPath
import java.nio.file.Path
abstract class RsRunAnythingProvider : RunAnythingProviderBase<String>() {
abstract override fun getMainListItem(dataContext: DataContext, value: String): RunAnythingItem
protected abstract fun run(
executor: Executor,
command: String,
params: List<String>,
workingDirectory: Path,
cargoProject: CargoProject
)
abstract fun getCompletionProvider(project: Project, dataContext: DataContext) : RsCommandCompletionProvider
override fun findMatchingValue(dataContext: DataContext, pattern: String): String? =
if (pattern.startsWith(helpCommand)) getCommand(pattern) else null
override fun getValues(dataContext: DataContext, pattern: String): Collection<String> {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return emptyList()
if (!project.hasCargoProject) return emptyList()
val completionProvider = getCompletionProvider(project, dataContext)
return when {
pattern.startsWith(helpCommand) -> {
val context = trimStart(pattern, helpCommand).substringBeforeLast(' ')
val prefix = pattern.substringBeforeLast(' ')
completionProvider.complete(context).map { "$prefix ${it.lookupString}" }
}
pattern.isNotBlank() && helpCommand.startsWith(pattern) ->
completionProvider.complete("").map { "$helpCommand ${it.lookupString}" }
else -> emptyList()
}
}
override fun execute(dataContext: DataContext, value: String) {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return
if (!project.hasCargoProject) return
val cargoProject = getAppropriateCargoProject(dataContext) ?: return
val params = ParametersListUtil.parse(trimStart(value, helpCommand))
val executionContext = dataContext.getData(EXECUTING_CONTEXT) ?: RunAnythingContext.ProjectContext(project)
val path = executionContext.getPath()?.toPath() ?: return
val executor = dataContext.getData(RunAnythingAction.EXECUTOR_KEY) ?: DefaultRunExecutor.getRunExecutorInstance()
run(executor, params.firstOrNull() ?: "--help", params.drop(1), path, cargoProject)
}
abstract override fun getHelpCommand(): String
}
| mit | 15382a7947001112c3c39f7e60ed3b7b | 44.891892 | 121 | 0.745583 | 5.076233 | false | false | false | false |
Gh0u1L5/WechatMagician | app/src/main/kotlin/com/gh0u1l5/wechatmagician/backend/plugins/SnsBlock.kt | 1 | 1446 | package com.gh0u1l5.wechatmagician.backend.plugins
import com.gh0u1l5.wechatmagician.Global.SETTINGS_SNS_KEYWORD_BLACKLIST
import com.gh0u1l5.wechatmagician.Global.SETTINGS_SNS_KEYWORD_BLACKLIST_CONTENT
import com.gh0u1l5.wechatmagician.backend.WechatHook
import com.gh0u1l5.wechatmagician.backend.storage.list.SnsBlacklist
import com.gh0u1l5.wechatmagician.spellbook.interfaces.IXmlParserHook
object SnsBlock : IXmlParserHook {
private const val ROOT_TAG = "TimelineObject"
private const val CONTENT_TAG = ".TimelineObject.contentDesc"
private const val ID_TAG = ".TimelineObject.id"
private const val PRIVATE_TAG = ".TimelineObject.private"
private val pref = WechatHook.settings
private fun isPluginEnabled() = pref.getBoolean(SETTINGS_SNS_KEYWORD_BLACKLIST, false)
override fun onXmlParsed(xml: String, root: String, result: MutableMap<String, String>) {
if (!isPluginEnabled()) {
return
}
if (root == ROOT_TAG && result[PRIVATE_TAG] != "1") {
val content = result[CONTENT_TAG] ?: return
val keywords = pref.getStringList(SETTINGS_SNS_KEYWORD_BLACKLIST_CONTENT, emptyList())
keywords.forEach { keyword ->
if (content.contains(keyword)) {
SnsBlacklist += result[ID_TAG]
result[PRIVATE_TAG] = "1"
return
}
}
}
}
}
| gpl-3.0 | 729532e741c0999abf135b66c8779b70 | 39.166667 | 98 | 0.666667 | 4.084746 | false | false | false | false |
michael71/LanbahnPanel | app/src/main/java/de/blankedv/lanbahnpanel/railroad/Commands.kt | 1 | 2868 | package de.blankedv.lanbahnpanel.railroad
import android.util.Log
import de.blankedv.lanbahnpanel.elements.ActivePanelElement
import de.blankedv.lanbahnpanel.model.*
class Commands {
companion object {
fun readChannel(addr: Int, peClass: Class<*> = Object::class.java) {
if (addr == INVALID_INT) return
var cmd = "READ $addr"
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "readChannel failed, queue full")
}
}
fun readMultipleChannels(aArray: ArrayList<Int>) {
var cmd = "";
val aArr = aArray.sorted()
for (a in aArr) {
if (a != INVALID_INT) {
cmd += ";READ $a"
}
}
if (cmd.isEmpty()) return
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "readChannel failed, queue full")
}
}
fun setChannel(addr: Int, data: Int, peClass: Class<*> = Object::class.java) {
if ((addr == INVALID_INT) or (data == INVALID_INT)) return
var cmd = "SET $addr $data"
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "setChannel failed, queue full")
}
}
fun setPower(state: Int) {
var cmd = "SETPOWER "
when (state) {
POWER_ON -> cmd += "1"
POWER_OFF -> cmd += "0"
POWER_UNKNOWN -> cmd += "1" // switch on in this case
}
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "setPower failed, queue full")
}
}
fun readPower() {
var cmd = "READPOWER "
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "readPower failed, queue full")
}
}
fun setLocoData(addr : Int, data : Int) {
if ((addr == INVALID_INT) or (data == INVALID_INT)) return
var cmd = "SETLOCO $addr $data"
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "setLocoData failed, queue full")
}
}
fun readLocoData(addr : Int) {
if (addr == INVALID_INT) return
var cmd = "READLOCO $addr"
val success = sendQ.offer(cmd)
if (!success && DEBUG) {
Log.d(TAG, "readChannel failed, queue full")
}
}
/** needed for sx loco control TODO works only for SX */
fun requestAllLocoData() {
for (l in locolist) {
readLocoData(l.adr) // TODO works only for SX
}
}
}
} | gpl-3.0 | e428ce32e6c628fc8fb92481fa216620 | 27.979798 | 86 | 0.470014 | 4.186861 | false | false | false | false |
deva666/anko | anko/library/static/appcompatV7/src/SupportAlertBuilder.kt | 2 | 4652 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.anko.appcompat.v7
import org.jetbrains.anko.*
import android.content.Context
import android.content.DialogInterface
import android.graphics.drawable.Drawable
import android.support.v7.app.AlertDialog
import android.view.KeyEvent
import android.view.View
import org.jetbrains.anko.internals.AnkoInternals
import org.jetbrains.anko.internals.AnkoInternals.NO_GETTER
import kotlin.DeprecationLevel.ERROR
val Appcompat: AlertBuilderFactory<AlertDialog> = ::AppcompatAlertBuilder
internal class AppcompatAlertBuilder(override val ctx: Context) : AlertBuilder<AlertDialog> {
private val builder = AlertDialog.Builder(ctx)
override var title: CharSequence
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setTitle(value) }
override var titleResource: Int
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setTitle(value) }
override var message: CharSequence
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setMessage(value) }
override var messageResource: Int
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setMessage(value) }
override var icon: Drawable
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setIcon(value) }
override var iconResource: Int
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setIcon(value) }
override var customTitle: View
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setCustomTitle(value) }
override var customView: View
@Deprecated(NO_GETTER, level = ERROR) get() = AnkoInternals.noGetter()
set(value) { builder.setView(value) }
override fun onCancelled(handler: (DialogInterface) -> Unit) {
builder.setOnCancelListener(handler)
}
override fun onKeyPressed(handler: (dialog: DialogInterface, keyCode: Int, e: KeyEvent) -> Boolean) {
builder.setOnKeyListener(handler)
}
override fun positiveButton(buttonText: String, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setPositiveButton(buttonText) { dialog, _ -> onClicked(dialog) }
}
override fun positiveButton(buttonTextResource: Int, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setPositiveButton(buttonTextResource) { dialog, _ -> onClicked(dialog) }
}
override fun negativeButton(buttonText: String, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setNegativeButton(buttonText) { dialog, _ -> onClicked(dialog) }
}
override fun negativeButton(buttonTextResource: Int, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setNegativeButton(buttonTextResource) { dialog, _ -> onClicked(dialog) }
}
override fun neutralPressed(buttonText: String, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setNeutralButton(buttonText) { dialog, _ -> onClicked(dialog) }
}
override fun neutralPressed(buttonTextResource: Int, onClicked: (dialog: DialogInterface) -> Unit) {
builder.setNeutralButton(buttonTextResource) { dialog, _ -> onClicked(dialog) }
}
override fun items(items: List<CharSequence>, onItemSelected: (dialog: DialogInterface, index: Int) -> Unit) {
builder.setItems(Array(items.size) { i -> items[i].toString() }) { dialog, which ->
onItemSelected(dialog, which)
}
}
override fun <T> items(items: List<T>, onItemSelected: (dialog: DialogInterface, item: T, index: Int) -> Unit) {
builder.setItems(Array(items.size) { i -> items[i].toString() }) { dialog, which ->
onItemSelected(dialog, items[which], which)
}
}
override fun build(): AlertDialog = builder.create()
override fun show(): AlertDialog = builder.show()
} | apache-2.0 | 7167a1e2a79ea9235ce41e1a31db8546 | 39.815789 | 116 | 0.701204 | 4.430476 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/challenges/ChallengeListFragment.kt | 1 | 7431 | package com.habitrpg.android.habitica.ui.fragments.social.challenges
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ChallengeRepository
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.databinding.FragmentRefreshRecyclerviewBinding
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.social.Challenge
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.modules.AppModule
import com.habitrpg.android.habitica.ui.adapter.social.ChallengesListViewAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import com.habitrpg.android.habitica.ui.helpers.EmptyItem
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import com.habitrpg.android.habitica.utils.Action1
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.kotlin.Flowables
import javax.inject.Inject
import javax.inject.Named
class ChallengeListFragment : BaseFragment<FragmentRefreshRecyclerviewBinding>(), androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener {
@Inject
lateinit var challengeRepository: ChallengeRepository
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var userRepository: UserRepository
@field:[Inject Named(AppModule.NAMED_USER_ID)]
lateinit var userId: String
override var binding: FragmentRefreshRecyclerviewBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentRefreshRecyclerviewBinding {
return FragmentRefreshRecyclerviewBinding.inflate(inflater, container, false)
}
private var challengeAdapter: ChallengesListViewAdapter? = null
private var viewUserChallengesOnly: Boolean = false
private var nextPageToLoad = 0
private var loadedAllData = false
private var challenges: List<Challenge>? = null
private var filterGroups: MutableList<Group>? = null
private var filterOptions: ChallengeFilterOptions? = null
fun setViewUserChallengesOnly(only: Boolean) {
this.viewUserChallengesOnly = only
}
override fun onDestroy() {
challengeRepository.close()
super.onDestroy()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
challengeAdapter = ChallengesListViewAdapter(viewUserChallengesOnly, userId)
challengeAdapter?.getOpenDetailFragmentFlowable()?.subscribe({ openDetailFragment(it) }, RxErrorHandler.handleEmptyError())
?.let { compositeSubscription.add(it) }
binding?.refreshLayout?.setOnRefreshListener(this)
if (viewUserChallengesOnly) {
binding?.recyclerView?.emptyItem = EmptyItem(
getString(R.string.empty_challenge_list),
getString(R.string.empty_discover_description)
)
}
binding?.recyclerView?.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this.activity)
binding?.recyclerView?.adapter = challengeAdapter
if (!viewUserChallengesOnly) {
binding?.recyclerView?.setBackgroundResource(R.color.content_background)
}
compositeSubscription.add(
Flowables.combineLatest(socialRepository.getGroup(Group.TAVERN_ID), socialRepository.getUserGroups("guild")).subscribe(
{
this.filterGroups = mutableListOf()
filterGroups?.add(it.first)
filterGroups?.addAll(it.second)
},
RxErrorHandler.handleEmptyError()
)
)
binding?.recyclerView?.itemAnimator = SafeDefaultItemAnimator()
challengeAdapter?.updateUnfilteredData(challenges)
loadLocalChallenges()
binding?.recyclerView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (!recyclerView.canScrollVertically(1)) {
retrieveChallengesPage()
}
}
})
}
private fun openDetailFragment(challengeID: String) {
MainNavigationController.navigate(ChallengesOverviewFragmentDirections.openChallengeDetail(challengeID))
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onRefresh() {
nextPageToLoad = 0
loadedAllData = false
retrieveChallengesPage(true)
}
private fun setRefreshing(state: Boolean) {
binding?.refreshLayout?.isRefreshing = state
}
private fun loadLocalChallenges() {
val observable: Flowable<out List<Challenge>> = if (viewUserChallengesOnly) {
challengeRepository.getUserChallenges()
} else {
challengeRepository.getChallenges()
}
compositeSubscription.add(
observable.subscribe(
{ challenges ->
if (challenges.size == 0) {
retrieveChallengesPage()
}
this.challenges = challenges
challengeAdapter?.updateUnfilteredData(challenges)
},
RxErrorHandler.handleEmptyError()
)
)
}
internal fun retrieveChallengesPage(forced: Boolean = false) {
if ((!forced && binding?.refreshLayout?.isRefreshing == true) || loadedAllData || !this::challengeRepository.isInitialized) {
return
}
setRefreshing(true)
compositeSubscription.add(
challengeRepository.retrieveChallenges(nextPageToLoad, viewUserChallengesOnly).doOnComplete {
setRefreshing(false)
}.subscribe(
{
if (it.size < 10) {
loadedAllData = true
}
nextPageToLoad += 1
},
RxErrorHandler.handleEmptyError()
)
)
}
internal fun showFilterDialog() {
activity?.let {
ChallengeFilterDialogHolder.showDialog(
it,
filterGroups ?: emptyList(),
filterOptions,
object : Action1<ChallengeFilterOptions> {
override fun call(t: ChallengeFilterOptions) {
changeFilter(t)
}
}
)
}
}
private fun changeFilter(challengeFilterOptions: ChallengeFilterOptions) {
filterOptions = challengeFilterOptions
challengeAdapter?.filter(challengeFilterOptions)
}
}
| gpl-3.0 | e90b381038e8ceba7780e447405e67c1 | 36.703125 | 155 | 0.658054 | 5.837392 | false | false | false | false |
androidx/androidx | health/health-services-client/src/main/java/androidx/health/services/client/data/ExerciseType.kt | 3 | 14094 | /*
* Copyright (C) 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.health.services.client.data
import androidx.annotation.RestrictTo
import androidx.health.services.client.proto.DataProto
/** Exercise type used to configure sensors and algorithms. */
public class ExerciseType @RestrictTo(RestrictTo.Scope.LIBRARY) public constructor(
/** Returns a unique identifier of for the [ExerciseType], as an `int`. */
public val id: Int,
/** Returns a human readable name to represent this [ExerciseType]. */
public val name: String
) {
override fun toString(): String {
return name
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ExerciseType) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id
}
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY)
public fun toProto(): DataProto.ExerciseType =
DataProto.ExerciseType.forNumber(id) ?: DataProto.ExerciseType.EXERCISE_TYPE_UNKNOWN
public companion object {
// Next ID: 93
/** The current exercise type of the user is unknown or not set. */
@JvmField public val UNKNOWN: ExerciseType = ExerciseType(0, "UNKNOWN")
@JvmField public val ALPINE_SKIING: ExerciseType = ExerciseType(92, "ALPINE_SKIING")
@JvmField public val BACKPACKING: ExerciseType = ExerciseType(84, "BACKPACKING")
@JvmField public val BACK_EXTENSION: ExerciseType = ExerciseType(1, "BACK_EXTENSION")
@JvmField public val BADMINTON: ExerciseType = ExerciseType(2, "BADMINTON")
@JvmField
public val BARBELL_SHOULDER_PRESS: ExerciseType = ExerciseType(3, "BARBELL_SHOULDER_PRESS")
@JvmField public val BASEBALL: ExerciseType = ExerciseType(4, "BASEBALL")
@JvmField public val BASKETBALL: ExerciseType = ExerciseType(5, "BASKETBALL")
@JvmField public val BENCH_PRESS: ExerciseType = ExerciseType(6, "BENCH_PRESS")
@JvmField internal val BENCH_SIT_UP: ExerciseType = ExerciseType(7, "BENCH_SIT_UP")
@JvmField public val BIKING: ExerciseType = ExerciseType(8, "BIKING")
@JvmField public val BIKING_STATIONARY: ExerciseType = ExerciseType(9, "BIKING_STATIONARY")
@JvmField public val BOOT_CAMP: ExerciseType = ExerciseType(10, "BOOT_CAMP")
@JvmField public val BOXING: ExerciseType = ExerciseType(11, "BOXING")
@JvmField public val BURPEE: ExerciseType = ExerciseType(12, "BURPEE")
/** Calisthenics (E.g., push ups, sit ups, pull-ups, jumping jacks). */
@JvmField public val CALISTHENICS: ExerciseType = ExerciseType(13, "CALISTHENICS")
@JvmField public val CRICKET: ExerciseType = ExerciseType(14, "CRICKET")
@JvmField
public val CROSS_COUNTRY_SKIING: ExerciseType = ExerciseType(91, "CROSS_COUNTRY_SKIING")
@JvmField public val CRUNCH: ExerciseType = ExerciseType(15, "CRUNCH")
@JvmField public val DANCING: ExerciseType = ExerciseType(16, "DANCING")
@JvmField public val DEADLIFT: ExerciseType = ExerciseType(17, "DEADLIFT")
@JvmField
internal val DUMBBELL_CURL_RIGHT_ARM: ExerciseType =
ExerciseType(18, "DUMBBELL_CURL_RIGHT_ARM")
@JvmField
internal val DUMBBELL_CURL_LEFT_ARM: ExerciseType =
ExerciseType(19, "DUMBBELL_CURL_LEFT_ARM")
@JvmField
internal val DUMBBELL_FRONT_RAISE: ExerciseType = ExerciseType(20, "DUMBBELL_FRONT_RAISE")
@JvmField
internal val DUMBBELL_LATERAL_RAISE: ExerciseType =
ExerciseType(21, "DUMBBELL_LATERAL_RAISE")
@JvmField
internal val DUMBBELL_TRICEPS_EXTENSION_LEFT_ARM: ExerciseType =
ExerciseType(22, "DUMBBELL_TRICEPS_EXTENSION_LEFT_ARM")
@JvmField
internal val DUMBBELL_TRICEPS_EXTENSION_RIGHT_ARM: ExerciseType =
ExerciseType(23, "DUMBBELL_TRICEPS_EXTENSION_RIGHT_ARM")
@JvmField
internal val DUMBBELL_TRICEPS_EXTENSION_TWO_ARM: ExerciseType =
ExerciseType(24, "DUMBBELL_TRICEPS_EXTENSION_TWO_ARM")
@JvmField public val ELLIPTICAL: ExerciseType = ExerciseType(25, "ELLIPTICAL")
@JvmField public val EXERCISE_CLASS: ExerciseType = ExerciseType(26, "EXERCISE_CLASS")
@JvmField public val FENCING: ExerciseType = ExerciseType(27, "FENCING")
@JvmField public val FRISBEE_DISC: ExerciseType = ExerciseType(28, "FRISBEE_DISC")
@JvmField public val FOOTBALL_AMERICAN: ExerciseType = ExerciseType(29, "FOOTBALL_AMERICAN")
@JvmField
public val FOOTBALL_AUSTRALIAN: ExerciseType = ExerciseType(30, "FOOTBALL_AUSTRALIAN")
@JvmField public val FORWARD_TWIST: ExerciseType = ExerciseType(31, "FORWARD_TWIST")
@JvmField public val GOLF: ExerciseType = ExerciseType(32, "GOLF")
@JvmField public val GUIDED_BREATHING: ExerciseType = ExerciseType(33, "GUIDED_BREATHING")
@JvmField public val HORSE_RIDING: ExerciseType = ExerciseType(88, "HORSE_RIDING")
@JvmField public val GYMNASTICS: ExerciseType = ExerciseType(34, "GYMNASTICS")
@JvmField public val HANDBALL: ExerciseType = ExerciseType(35, "HANDBALL")
@JvmField
public val HIGH_INTENSITY_INTERVAL_TRAINING: ExerciseType =
ExerciseType(36, "HIGH_INTENSITY_INTERVAL_TRAINING")
@JvmField public val HIKING: ExerciseType = ExerciseType(37, "HIKING")
@JvmField public val ICE_HOCKEY: ExerciseType = ExerciseType(38, "ICE_HOCKEY")
@JvmField public val ICE_SKATING: ExerciseType = ExerciseType(39, "ICE_SKATING")
@JvmField public val INLINE_SKATING: ExerciseType = ExerciseType(87, "INLINE_SKATING")
@JvmField public val JUMP_ROPE: ExerciseType = ExerciseType(40, "JUMP_ROPE")
@JvmField public val JUMPING_JACK: ExerciseType = ExerciseType(41, "JUMPING_JACK")
@JvmField public val LAT_PULL_DOWN: ExerciseType = ExerciseType(42, "LAT_PULL_DOWN")
@JvmField public val LUNGE: ExerciseType = ExerciseType(43, "LUNGE")
@JvmField public val MARTIAL_ARTS: ExerciseType = ExerciseType(44, "MARTIAL_ARTS")
@JvmField public val MEDITATION: ExerciseType = ExerciseType(45, "MEDITATION")
@JvmField public val MOUNTAIN_BIKING: ExerciseType = ExerciseType(85, "MOUNTAIN_BIKING")
@JvmField public val ORIENTEERING: ExerciseType = ExerciseType(86, "ORIENTEERING")
@JvmField public val PADDLING: ExerciseType = ExerciseType(46, "PADDLING")
@JvmField public val PARA_GLIDING: ExerciseType = ExerciseType(47, "PARA_GLIDING")
@JvmField public val PILATES: ExerciseType = ExerciseType(48, "PILATES")
@JvmField public val PLANK: ExerciseType = ExerciseType(49, "PLANK")
@JvmField public val RACQUETBALL: ExerciseType = ExerciseType(50, "RACQUETBALL")
@JvmField public val ROCK_CLIMBING: ExerciseType = ExerciseType(51, "ROCK_CLIMBING")
@JvmField public val ROLLER_HOCKEY: ExerciseType = ExerciseType(52, "ROLLER_HOCKEY")
@JvmField public val ROLLER_SKATING: ExerciseType = ExerciseType(89, "ROLLER_SKATING")
@JvmField public val ROWING: ExerciseType = ExerciseType(53, "ROWING")
@JvmField public val ROWING_MACHINE: ExerciseType = ExerciseType(54, "ROWING_MACHINE")
@JvmField public val RUNNING: ExerciseType = ExerciseType(55, "RUNNING")
@JvmField public val RUNNING_TREADMILL: ExerciseType = ExerciseType(56, "RUNNING_TREADMILL")
@JvmField public val RUGBY: ExerciseType = ExerciseType(57, "RUGBY")
@JvmField public val SAILING: ExerciseType = ExerciseType(58, "SAILING")
@JvmField public val SCUBA_DIVING: ExerciseType = ExerciseType(59, "SCUBA_DIVING")
@JvmField public val SKATING: ExerciseType = ExerciseType(60, "SKATING")
@JvmField public val SKIING: ExerciseType = ExerciseType(61, "SKIING")
@JvmField public val SNOWBOARDING: ExerciseType = ExerciseType(62, "SNOWBOARDING")
@JvmField public val SNOWSHOEING: ExerciseType = ExerciseType(63, "SNOWSHOEING")
@JvmField public val SOCCER: ExerciseType = ExerciseType(64, "SOCCER")
@JvmField public val SOFTBALL: ExerciseType = ExerciseType(65, "SOFTBALL")
@JvmField public val SQUASH: ExerciseType = ExerciseType(66, "SQUASH")
@JvmField public val SQUAT: ExerciseType = ExerciseType(67, "SQUAT")
@JvmField public val STAIR_CLIMBING: ExerciseType = ExerciseType(68, "STAIR_CLIMBING")
@JvmField
public val STAIR_CLIMBING_MACHINE: ExerciseType = ExerciseType(69, "STAIR_CLIMBING_MACHINE")
@JvmField public val STRENGTH_TRAINING: ExerciseType = ExerciseType(70, "STRENGTH_TRAINING")
@JvmField public val STRETCHING: ExerciseType = ExerciseType(71, "STRETCHING")
@JvmField public val SURFING: ExerciseType = ExerciseType(72, "SURFING")
@JvmField
public val SWIMMING_OPEN_WATER: ExerciseType = ExerciseType(73, "SWIMMING_OPEN_WATER")
@JvmField public val SWIMMING_POOL: ExerciseType = ExerciseType(74, "SWIMMING_POOL")
@JvmField public val TABLE_TENNIS: ExerciseType = ExerciseType(75, "TABLE_TENNIS")
@JvmField public val TENNIS: ExerciseType = ExerciseType(76, "TENNIS")
@JvmField public val UPPER_TWIST: ExerciseType = ExerciseType(77, "UPPER_TWIST")
@JvmField public val VOLLEYBALL: ExerciseType = ExerciseType(78, "VOLLEYBALL")
@JvmField public val WALKING: ExerciseType = ExerciseType(79, "WALKING")
@JvmField public val WATER_POLO: ExerciseType = ExerciseType(80, "WATER_POLO")
@JvmField public val WEIGHTLIFTING: ExerciseType = ExerciseType(81, "WEIGHTLIFTING")
@JvmField public val WORKOUT: ExerciseType = ExerciseType(82, "WORKOUT")
@JvmField public val YACHTING: ExerciseType = ExerciseType(90, "YACHTING")
@JvmField public val YOGA: ExerciseType = ExerciseType(83, "YOGA")
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
public val VALUES: List<ExerciseType> =
listOf(
UNKNOWN,
ALPINE_SKIING,
BACKPACKING,
BACK_EXTENSION,
BADMINTON,
BARBELL_SHOULDER_PRESS,
BASEBALL,
BASKETBALL,
BENCH_PRESS,
BENCH_SIT_UP,
BIKING,
BIKING_STATIONARY,
BOOT_CAMP,
BOXING,
BURPEE,
CALISTHENICS,
CRICKET,
CROSS_COUNTRY_SKIING,
CRUNCH,
DANCING,
DEADLIFT,
DUMBBELL_CURL_RIGHT_ARM,
DUMBBELL_CURL_LEFT_ARM,
DUMBBELL_FRONT_RAISE,
DUMBBELL_LATERAL_RAISE,
DUMBBELL_TRICEPS_EXTENSION_LEFT_ARM,
DUMBBELL_TRICEPS_EXTENSION_RIGHT_ARM,
DUMBBELL_TRICEPS_EXTENSION_TWO_ARM,
ELLIPTICAL,
EXERCISE_CLASS,
FENCING,
FRISBEE_DISC,
FOOTBALL_AMERICAN,
FOOTBALL_AUSTRALIAN,
FORWARD_TWIST,
GOLF,
GUIDED_BREATHING,
HORSE_RIDING,
GYMNASTICS,
HANDBALL,
HIGH_INTENSITY_INTERVAL_TRAINING,
HIKING,
ICE_HOCKEY,
ICE_SKATING,
INLINE_SKATING,
JUMP_ROPE,
JUMPING_JACK,
LAT_PULL_DOWN,
LUNGE,
MARTIAL_ARTS,
MEDITATION,
MOUNTAIN_BIKING,
ORIENTEERING,
PADDLING,
PARA_GLIDING,
PILATES,
PLANK,
RACQUETBALL,
ROCK_CLIMBING,
ROLLER_HOCKEY,
ROLLER_SKATING,
ROWING,
ROWING_MACHINE,
RUNNING,
RUNNING_TREADMILL,
RUGBY,
SAILING,
SCUBA_DIVING,
SKATING,
SKIING,
SNOWBOARDING,
SNOWSHOEING,
SOCCER,
SOFTBALL,
SQUASH,
SQUAT,
STAIR_CLIMBING,
STAIR_CLIMBING_MACHINE,
STRENGTH_TRAINING,
STRETCHING,
SURFING,
SWIMMING_OPEN_WATER,
SWIMMING_POOL,
TABLE_TENNIS,
TENNIS,
UPPER_TWIST,
VOLLEYBALL,
WALKING,
WATER_POLO,
WEIGHTLIFTING,
WORKOUT,
YACHTING,
YOGA,
)
private val IDS = VALUES.map { it.id to it }.toMap()
/**
* Returns the [ExerciseType] based on its unique `id`.
*
* If the `id` doesn't map to an particular [ExerciseType], then [ExerciseType.UNKNOWN] is
* returned by default.
*/
@JvmStatic
public fun fromId(id: Int): ExerciseType {
val exerciseType = IDS[id]
return exerciseType ?: UNKNOWN
}
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY)
public fun fromProto(proto: DataProto.ExerciseType): ExerciseType = fromId(proto.number)
}
}
| apache-2.0 | 1cf32f44029a4621cd3d61508c3de5fe | 47.768166 | 100 | 0.629062 | 4.487106 | false | false | false | false |
androidx/androidx | compose/animation/animation-core/src/commonMain/kotlin/androidx/compose/animation/core/FloatAnimationSpec.kt | 3 | 10247 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.core
import androidx.compose.animation.core.AnimationConstants.DefaultDurationMillis
import androidx.compose.animation.core.internal.JvmDefaultWithCompatibility
/**
* [FloatAnimationSpec] interface is similar to [VectorizedAnimationSpec], except it deals
* exclusively with floats.
*
* Like [VectorizedAnimationSpec], [FloatAnimationSpec] is entirely stateless as well. It requires
* start/end values and start velocity to be passed in for the query of velocity and value of the
* animation. The [FloatAnimationSpec] itself stores only the animation configuration (such as the
* delay, duration and easing curve for [FloatTweenSpec], or spring constants for
* [FloatSpringSpec].
*
* A [FloatAnimationSpec] can be converted to an [VectorizedAnimationSpec] using [vectorize].
*
* @see [VectorizedAnimationSpec]
*/
@JvmDefaultWithCompatibility
interface FloatAnimationSpec : AnimationSpec<Float> {
/**
* Calculates the value of the animation at given the playtime, with the provided start/end
* values, and start velocity.
*
* @param playTimeNanos time since the start of the animation
* @param initialValue start value of the animation
* @param targetValue end value of the animation
* @param initialVelocity start velocity of the animation
*/
fun getValueFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float
/**
* Calculates the velocity of the animation at given the playtime, with the provided start/end
* values, and start velocity.
*
* @param playTimeNanos time since the start of the animation
* @param initialValue start value of the animation
* @param targetValue end value of the animation
* @param initialVelocity start velocity of the animation
*/
fun getVelocityFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float
/**
* Calculates the end velocity of the animation with the provided start/end values, and start
* velocity. For duration-based animations, end velocity will be the velocity of the
* animation at the duration time. This is also the default assumption. However, for
* spring animations, the transient trailing velocity will be snapped to zero.
*
* @param initialValue start value of the animation
* @param targetValue end value of the animation
* @param initialVelocity start velocity of the animation
*/
fun getEndVelocity(
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float =
getVelocityFromNanos(
getDurationNanos(initialValue, targetValue, initialVelocity),
initialValue,
targetValue,
initialVelocity
)
/**
* Calculates the duration of an animation. For duration-based animations, this will return the
* pre-defined duration. For physics-based animations, the duration will be estimated based on
* the physics configuration (such as spring stiffness, damping ratio, visibility threshold)
* as well as the [initialValue], [targetValue] values, and [initialVelocity].
*
* __Note__: this may be a computation that is expensive - especially with spring based
* animations
*
* @param initialValue start value of the animation
* @param targetValue end value of the animation
* @param initialVelocity start velocity of the animation
*/
@Suppress("MethodNameUnits")
fun getDurationNanos(
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Long
/**
* Create an [VectorizedAnimationSpec] that animates [AnimationVector] from a [FloatAnimationSpec]. Every
* dimension of the [AnimationVector] will be animated using the given [FloatAnimationSpec].
*/
override fun <V : AnimationVector> vectorize(converter: TwoWayConverter<Float, V>) =
VectorizedFloatAnimationSpec<V>(this)
}
/**
* [FloatSpringSpec] animation uses a spring animation to animate a [Float] value. Its
* configuration can be tuned via adjusting the spring parameters, namely damping ratio and
* stiffness.
*
* @param dampingRatio damping ratio of the spring. Defaults to [Spring.DampingRatioNoBouncy]
* @param stiffness Stiffness of the spring. Defaults to [Spring.StiffnessMedium]
* @param visibilityThreshold The value threshold such that the animation is no longer
* significant. e.g. 1px for translation animations. Defaults to
* [Spring.DefaultDisplacementThreshold]
*/
class FloatSpringSpec(
val dampingRatio: Float = Spring.DampingRatioNoBouncy,
val stiffness: Float = Spring.StiffnessMedium,
private val visibilityThreshold: Float = Spring.DefaultDisplacementThreshold
) : FloatAnimationSpec {
private val spring = SpringSimulation(1f).also {
it.dampingRatio = dampingRatio
it.stiffness = stiffness
}
override fun getValueFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float {
// TODO: Properly support Nanos in the spring impl
val playTimeMillis = playTimeNanos / MillisToNanos
spring.finalPosition = targetValue
val value = spring.updateValues(initialValue, initialVelocity, playTimeMillis).value
return value
}
override fun getVelocityFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float {
// TODO: Properly support Nanos in the spring impl
val playTimeMillis = playTimeNanos / MillisToNanos
spring.finalPosition = targetValue
val velocity = spring.updateValues(initialValue, initialVelocity, playTimeMillis).velocity
return velocity
}
override fun getEndVelocity(
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float = 0f
@Suppress("MethodNameUnits")
override fun getDurationNanos(
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Long =
estimateAnimationDurationMillis(
stiffness = spring.stiffness,
dampingRatio = spring.dampingRatio,
initialDisplacement = (initialValue - targetValue) / visibilityThreshold,
initialVelocity = initialVelocity / visibilityThreshold,
delta = 1f
) * MillisToNanos
}
/**
* [FloatTweenSpec] animates a Float value from any start value to any end value using a provided
* [easing] function. The animation will finish within the [duration] time. Unless a [delay] is
* specified, the animation will start right away.
*
* @param duration the amount of time (in milliseconds) the animation will take to finish.
* Defaults to [DefaultDuration]
* @param delay the amount of time the animation will wait before it starts running. Defaults to 0.
* @param easing the easing function that will be used to interoplate between the start and end
* value of the animation. Defaults to [FastOutSlowInEasing].
*/
class FloatTweenSpec(
val duration: Int = DefaultDurationMillis,
val delay: Int = 0,
private val easing: Easing = FastOutSlowInEasing
) : FloatAnimationSpec {
override fun getValueFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float {
// TODO: Properly support Nanos in the impl
val playTimeMillis = playTimeNanos / MillisToNanos
val clampedPlayTime = clampPlayTime(playTimeMillis)
val rawFraction = if (duration == 0) 1f else clampedPlayTime / duration.toFloat()
val fraction = easing.transform(rawFraction.coerceIn(0f, 1f))
return lerp(initialValue, targetValue, fraction)
}
private fun clampPlayTime(playTime: Long): Long {
return (playTime - delay).coerceIn(0, duration.toLong())
}
@Suppress("MethodNameUnits")
override fun getDurationNanos(
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Long {
return (delay + duration) * MillisToNanos
}
// Calculate velocity by difference between the current value and the value 1 ms ago. This is a
// preliminary way of calculating velocity used by easing curve based animations, and keyframe
// animations. Physics-based animations give a much more accurate velocity.
override fun getVelocityFromNanos(
playTimeNanos: Long,
initialValue: Float,
targetValue: Float,
initialVelocity: Float
): Float {
// TODO: Properly support Nanos in the impl
val playTimeMillis = playTimeNanos / MillisToNanos
val clampedPlayTime = clampPlayTime(playTimeMillis)
if (clampedPlayTime < 0) {
return 0f
} else if (clampedPlayTime == 0L) {
return initialVelocity
}
val startNum = getValueFromNanos(
(clampedPlayTime - 1) * MillisToNanos,
initialValue,
targetValue,
initialVelocity
)
val endNum = getValueFromNanos(
clampedPlayTime * MillisToNanos,
initialValue,
targetValue,
initialVelocity
)
return (endNum - startNum) * 1000f
}
}
| apache-2.0 | 42e82a9b736d2faa68f8211ee47bd7c1 | 37.961977 | 109 | 0.687226 | 5.244115 | false | false | false | false |
androidx/androidx | wear/watchface/watchface-complications/src/main/java/androidx/wear/watchface/complications/ComplicationSlotBounds.kt | 3 | 12690 | /*
* 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.
*/
/** Removes the KT class from the public API */
@file:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
package androidx.wear.watchface.complications
import android.content.res.Resources
import android.content.res.XmlResourceParser
import android.graphics.RectF
import android.util.TypedValue
import androidx.annotation.RestrictTo
import androidx.wear.watchface.complications.data.ComplicationType
import java.io.DataOutputStream
const val NAMESPACE_APP = "http://schemas.android.com/apk/res-auto"
const val NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android"
/**
* ComplicationSlotBounds are defined by fractional screen space coordinates in unit-square [0..1].
* These bounds will be subsequently clamped to the unit square and converted to screen space
* coordinates. NB 0 and 1 are included in the unit square.
*
* One bound is expected per [ComplicationType] to allow [androidx.wear.watchface.ComplicationSlot]s
* to change shape depending on the type.
*
* Taps on the watch are tested first against each ComplicationSlot's [perComplicationTypeBounds]
* for the relevant [ComplicationType]. Its assumed that [perComplicationTypeBounds] don't overlap.
* If no intersection was found then taps are checked against [perComplicationTypeBounds] expanded
* by [perComplicationTypeMargins]. Expanded bounds can overlap so the ComplicationSlot with the
* lowest id that intersects the coordinates, if any, is selected.
*
* @param perComplicationTypeBounds Per [ComplicationType] fractional unit-square screen space
* complication bounds.
* @param perComplicationTypeMargins Per [ComplicationType] fractional unit-square screen space
* complication margins for tap detection (doesn't affect rendering).
*/
public class ComplicationSlotBounds(
public val perComplicationTypeBounds: Map<ComplicationType, RectF>,
public val perComplicationTypeMargins: Map<ComplicationType, RectF>
) {
@Deprecated(
"Use a constructor that specifies perComplicationTypeMargins",
ReplaceWith(
"ComplicationSlotBounds(Map<ComplicationType, RectF>, Map<ComplicationType, RectF>)"
)
)
constructor(perComplicationTypeBounds: Map<ComplicationType, RectF>) : this(
perComplicationTypeBounds,
perComplicationTypeBounds.mapValues { RectF() }
)
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun write(dos: DataOutputStream) {
perComplicationTypeBounds.keys.toSortedSet().forEach { type ->
dos.writeInt(type.toWireComplicationType())
perComplicationTypeBounds[type]!!.write(dos)
perComplicationTypeMargins[type]!!.write(dos)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ComplicationSlotBounds
if (perComplicationTypeBounds != other.perComplicationTypeBounds) return false
return perComplicationTypeMargins == other.perComplicationTypeMargins
}
override fun hashCode(): Int {
var result = perComplicationTypeBounds.toSortedMap().hashCode()
result = 31 * result + perComplicationTypeMargins.toSortedMap().hashCode()
return result
}
override fun toString(): String {
return "ComplicationSlotBounds(perComplicationTypeBounds=$perComplicationTypeBounds, " +
"perComplicationTypeMargins=$perComplicationTypeMargins)"
}
/**
* Constructs a ComplicationSlotBounds where all complication types have the same screen space
* unit-square [bounds] and [margins].
*/
@JvmOverloads
public constructor(
bounds: RectF,
margins: RectF = RectF()
) : this(
ComplicationType.values().associateWith { bounds },
ComplicationType.values().associateWith { margins }
)
init {
require(perComplicationTypeBounds.size == ComplicationType.values().size) {
"perComplicationTypeBounds must contain entries for each ComplicationType"
}
require(perComplicationTypeMargins.size == ComplicationType.values().size) {
"perComplicationTypeMargins must contain entries for each ComplicationType"
}
for (type in ComplicationType.values()) {
require(perComplicationTypeBounds.containsKey(type)) {
"Missing bounds for $type"
}
require(perComplicationTypeMargins.containsKey(type)) {
"Missing margins for $type"
}
}
}
/** @hide */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
companion object {
internal const val NODE_NAME = "ComplicationSlotBounds"
/**
* Constructs a [ComplicationSlotBounds] from a potentially incomplete
* Map<ComplicationType, RectF>, backfilling with empty [RectF]s. This method is necessary
* because there can be a skew between the version of the library between the watch face and
* the system which would otherwise be problematic if new complication types have been
* introduced.
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun createFromPartialMap(
partialPerComplicationTypeBounds: Map<ComplicationType, RectF>,
partialPerComplicationTypeMargins: Map<ComplicationType, RectF>
): ComplicationSlotBounds {
val boundsMap = HashMap(partialPerComplicationTypeBounds)
val marginsMap = HashMap(partialPerComplicationTypeMargins)
for (type in ComplicationType.values()) {
boundsMap.putIfAbsent(type, RectF())
marginsMap.putIfAbsent(type, RectF())
}
return ComplicationSlotBounds(boundsMap, marginsMap)
}
/**
* The [parser] should be inside a node with any number of ComplicationSlotBounds child
* nodes. No other child nodes are expected.
*/
fun inflate(
resources: Resources,
parser: XmlResourceParser,
complicationScaleX: Float,
complicationScaleY: Float
): ComplicationSlotBounds? {
val perComplicationTypeBounds by lazy { HashMap<ComplicationType, RectF>() }
val perComplicationTypeMargins by lazy { HashMap<ComplicationType, RectF>() }
parser.iterate {
when (parser.name) {
NODE_NAME -> {
val rect = if (parser.hasValue("left"))
RectF(
parser.requireAndGet("left", resources, complicationScaleX),
parser.requireAndGet("top", resources, complicationScaleY),
parser.requireAndGet("right", resources, complicationScaleX),
parser.requireAndGet("bottom", resources, complicationScaleY)
)
else if (parser.hasValue("center_x")) {
val halfWidth =
parser.requireAndGet("size_x", resources, complicationScaleX) / 2.0f
val halfHeight =
parser.requireAndGet("size_y", resources, complicationScaleY) / 2.0f
val centerX =
parser.requireAndGet("center_x", resources, complicationScaleX)
val centerY =
parser.requireAndGet("center_y", resources, complicationScaleY)
RectF(
centerX - halfWidth,
centerY - halfHeight,
centerX + halfWidth,
centerY + halfHeight
)
} else {
throw IllegalArgumentException("$NODE_NAME must " +
"either define top, bottom, left, right" +
"or center_x, center_y, size_x, size_y should be specified")
}
val margin = RectF(
parser.get("marginLeft", resources, complicationScaleX) ?: 0f,
parser.get("marginTop", resources, complicationScaleY) ?: 0f,
parser.get("marginRight", resources, complicationScaleX) ?: 0f,
parser.get("marginBottom", resources, complicationScaleY) ?: 0f
)
if (null != parser.getAttributeValue(
NAMESPACE_APP,
"complicationType"
)
) {
val complicationType = ComplicationType.fromWireType(
parser.getAttributeIntValue(
NAMESPACE_APP,
"complicationType",
0
)
)
require(
!perComplicationTypeBounds.contains(complicationType)
) {
"Duplicate $complicationType"
}
perComplicationTypeBounds[complicationType] = rect
perComplicationTypeMargins[complicationType] = margin
} else {
for (complicationType in ComplicationType.values()) {
require(
!perComplicationTypeBounds.contains(
complicationType
)
) {
"Duplicate $complicationType"
}
perComplicationTypeBounds[complicationType] = rect
perComplicationTypeMargins[complicationType] = margin
}
}
}
else -> throw IllegalNodeException(parser)
}
}
return if (perComplicationTypeBounds.isEmpty()) {
null
} else {
createFromPartialMap(perComplicationTypeBounds, perComplicationTypeMargins)
}
}
}
}
internal fun XmlResourceParser.requireAndGet(
id: String,
resources: Resources,
scale: Float
): Float {
val value = get(id, resources, scale)
require(value != null) {
"${ComplicationSlotBounds.NODE_NAME} must define '$id'"
}
return value
}
internal fun XmlResourceParser.get(
id: String,
resources: Resources,
scale: Float
): Float? {
val stringValue = getAttributeValue(NAMESPACE_APP, id) ?: return null
val resId = getAttributeResourceValue(NAMESPACE_APP, id, 0)
if (resId != 0) {
return resources.getDimension(resId) / resources.displayMetrics.widthPixels
}
// There is "dp" -> "dip" conversion while resources compilation.
val dpStr = "dip"
if (stringValue.endsWith(dpStr)) {
val dps = stringValue.substring(0, stringValue.length - dpStr.length).toFloat()
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dps,
resources.displayMetrics
) / resources.displayMetrics.widthPixels
} else {
require(scale > 0) { "scale should be positive" }
return stringValue.toFloat() / scale
}
}
fun XmlResourceParser.hasValue(id: String): Boolean {
return null != getAttributeValue(NAMESPACE_APP, id)
}
internal fun RectF.write(dos: DataOutputStream) {
dos.writeFloat(left)
dos.writeFloat(right)
dos.writeFloat(top)
dos.writeFloat(bottom)
} | apache-2.0 | 51848f566f1dc8349d5f2f83fccf8a71 | 41.444816 | 100 | 0.591962 | 6.005679 | false | false | false | false |
codebutler/odyssey | retrograde-app-shared/src/main/java/com/codebutler/retrograde/lib/ui/SimpleItemPresenter.kt | 1 | 3189 | /*
* SimpleItemPresenter.kt
*
* Copyright (C) 2017 Retrograde Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.retrograde.lib.ui
import android.content.Context
import android.content.res.Resources
import android.view.ContextThemeWrapper
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.leanback.widget.ImageCardView
import androidx.leanback.widget.Presenter
import com.codebutler.retrograde.lib.R
sealed class TextOrResource {
class Text(val value: String) : TextOrResource()
class Resource(@StringRes val value: Int) : TextOrResource()
fun getText(resources: Resources): String = when (this) {
is Text -> value
is Resource -> resources.getString(value)
}
}
open class SimpleItem private constructor (val title: TextOrResource, @DrawableRes val image: Int?) {
constructor(text: String, @DrawableRes image: Int? = 0) : this(TextOrResource.Text(text), image)
constructor(@StringRes resId: Int, @DrawableRes image: Int = 0) : this (TextOrResource.Resource(resId), image)
}
class SimpleItemPresenter(context: Context) : Presenter() {
private val themedContext = ContextThemeWrapper(context, R.style.SimpleImageCardTheme)
private var imageWidth: Int = -1
private var imageHeight: Int = -1
override fun onCreateViewHolder(parent: ViewGroup): ViewHolder {
val cardView = ImageCardView(themedContext)
val res = cardView.resources
imageWidth = res.getDimensionPixelSize(R.dimen.card_width)
imageHeight = res.getDimensionPixelSize(R.dimen.card_height)
cardView.setMainImageScaleType(ImageView.ScaleType.CENTER)
cardView.isFocusable = true
cardView.isFocusableInTouchMode = true
cardView.setMainImageDimensions(imageWidth, imageHeight)
return Presenter.ViewHolder(cardView)
}
override fun onBindViewHolder(viewHolder: ViewHolder, item: Any) {
when (item) {
is SimpleItem -> {
val resources = viewHolder.view.resources
val cardView = viewHolder.view as ImageCardView
cardView.titleText = item.title.getText(resources)
if (item.image != null && item.image != 0) {
cardView.mainImage = resources.getDrawable(item.image)
} else {
cardView.mainImage = null
}
}
}
}
override fun onUnbindViewHolder(viewHolder: ViewHolder?) { }
}
| gpl-3.0 | 2debfe9f66e931ce506c9ac9cfda25ba | 36.964286 | 114 | 0.704923 | 4.628447 | false | false | false | false |
goldmansachs/obevo | obevo-core/src/main/java/com/gs/obevo/impl/graph/GraphEnricherImpl.kt | 1 | 9910 | /**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.impl.graph
import com.gs.obevo.api.appdata.CodeDependencyType
import com.gs.obevo.api.platform.ChangeType
import org.eclipse.collections.api.tuple.Pair
import org.eclipse.collections.impl.tuple.Tuples
import org.jgrapht.Graph
import org.jgrapht.graph.DefaultDirectedGraph
import org.jgrapht.graph.DefaultEdge
import org.slf4j.LoggerFactory
/**
* Created a graph out of the input changes, so that the graph can be shared by other components
*/
class GraphEnricherImpl(private val convertDbObjectName: Function1<String, String>) : GraphEnricher {
override fun <T : SortableDependencyGroup> createDependencyGraph(inputs: Iterable<T>, rollback: Boolean): Graph<T, DefaultEdge> {
val changeIndexes = listOf(
ObjectIndex(),
SchemaObjectIndex(),
ObjectChangeIndex<T>(),
SchemaChangeObjectIndex<T>()
)
changeIndexes.forEach { changeIndex -> inputs.forEach(changeIndex::add) }
val graph = DefaultDirectedGraph<T, DependencyEdge>(DependencyEdge::class.java)
// First - add the core objects to the graph
inputs.forEach { graph.addVertex(it) }
// Now add the declared dependencies to the graph
for (changeGroup in inputs) {
for (change in changeGroup.components) {
if (change.codeDependencies != null) {
for (dependency in change.codeDependencies) {
var dependencyVertex: T? = null
for (changeIndex in changeIndexes) {
dependencyVertex = changeIndex.retrieve(change.changeKey.objectKey.schema, dependency.target)
if (dependencyVertex != null) {
if (LOG.isTraceEnabled) {
LOG.trace("Discovered dependency from {} to {} using index {}",
dependencyVertex,
change.changeKey,
changeIndex)
}
break
}
}
if (dependencyVertex == null) {
LOG.trace("Dependency not found; likely due to not enriching the full graph in source. Should be OK to ignore: {} - {}", dependency, change)
} else {
graph.addEdge(dependencyVertex, changeGroup, DependencyEdge(dependency.codeDependencyType))
}
}
}
}
}
// Add in changes within incremental files to ensure proper order
val groupToComponentPairs = inputs.flatMap { group -> group.components.map { Pair(group, it) } }
val incrementalChangeByObjectMap = groupToComponentPairs.groupBy { pair ->
val tSortMetadata = pair.second
var changeType = tSortMetadata.changeKey.objectKey.changeType.name
if (changeType == ChangeType.TRIGGER_INCREMENTAL_OLD_STR || changeType == ChangeType.FOREIGN_KEY_STR) {
changeType = ChangeType.TABLE_STR
}
changeType + ":" + tSortMetadata.changeKey.objectKey.schema + ":" + convertDbObjectName(tSortMetadata.changeKey.objectKey.objectName)
}
incrementalChangeByObjectMap.values
.map { it.sortedBy { pair -> pair.second.orderWithinObject } }
.forEach { pair ->
pair.map { it.first }.zipWithNext().forEach { (each, nextChange) ->
// if rollback, then go from the next change to the previous
val fromVertex = if (rollback) nextChange else each
val toVertex = if (rollback) each else nextChange
graph.addEdge(fromVertex, toVertex, DependencyEdge(CodeDependencyType.IMPLICIT))
}
}
// validate
GraphUtil.validateNoCycles(graph,
{ vertex, target, edge ->
vertex.components
.map { sortableDependency ->
val name = if (target && edge.edgeType == CodeDependencyType.DISCOVERED)
sortableDependency.changeKey.objectKey.objectName
else sortableDependency.changeKey.objectKey.objectName + "." + sortableDependency.changeKey.changeName
"[$name]"
}
.joinToString(", ")
},
{ dependencyEdge -> dependencyEdge.edgeType.name }
)
return graph as Graph<T, DefaultEdge>
}
override fun <T> createSimpleDependencyGraph(inputs: Iterable<T>, edgesFunction: Function1<T, Iterable<T>>): Graph<T, DefaultEdge> {
val graph = DefaultDirectedGraph<T, DefaultEdge>(DefaultEdge::class.java)
inputs.forEach { graph.addVertex(it) }
inputs.forEach { input ->
val targetVertices = edgesFunction.invoke(input)
for (targetVertex in targetVertices) {
if (graph.containsVertex(targetVertex)) {
graph.addEdge(targetVertex, input)
} else {
LOG.info("Problem?")
}
}
}
return graph
}
private interface ChangeIndex<T> {
fun add(change: T)
fun retrieve(schema: String, dependency: String): T?
}
/**
* Looks for the given dependency/object
*/
private inner class ObjectIndex<T : SortableDependencyGroup> : ChangeIndex<T> {
private val schemaToObjectMap = mutableMapOf<Pair<String, String>, T>()
override fun add(changeGroup: T) {
for (change in changeGroup.components) {
val existingChange = retrieve(change.changeKey.objectKey.schema, convertDbObjectName(change.changeKey.objectKey.objectName))
// TODO getFirst is not ideal here
if (existingChange == null || existingChange.components.first.orderWithinObject < change.orderWithinObject) {
// only keep the latest (why latest vs earliest?)
schemaToObjectMap[Tuples.pair(change.changeKey.objectKey.schema, convertDbObjectName(change.changeKey.objectKey.objectName))] = changeGroup
}
}
}
override fun retrieve(schema: String, dependency: String): T? {
return schemaToObjectMap[Tuples.pair(schema, convertDbObjectName(dependency))]
}
}
private inner class SchemaObjectIndex<T : SortableDependencyGroup> : ChangeIndex<T> {
private val objectMap = mutableMapOf<String, T>()
override fun add(changeGroup: T) {
for (change in changeGroup.components) {
val existingChange = retrieve(change.changeKey.objectKey.schema, convertDbObjectName(change.changeKey.objectKey.objectName))
// TODO getFirst is not ideal here
if (existingChange == null || existingChange.components.first.orderWithinObject < change.orderWithinObject) {
// only keep the latest (why latest vs earliest?)
objectMap[convertDbObjectName(change.changeKey.objectKey.schema + "." + change.changeKey.objectKey.objectName)] = changeGroup
}
}
}
override fun retrieve(schema: String, dependency: String): T? {
return objectMap[convertDbObjectName(dependency)]
}
}
private inner class ObjectChangeIndex<T : SortableDependencyGroup> : ChangeIndex<T> {
private val schemaToObjectMap = mutableMapOf<Pair<String, String>, T>()
override fun add(changeGroup: T) {
for (change in changeGroup.components) {
schemaToObjectMap[Tuples.pair(change.changeKey.objectKey.schema, convertDbObjectName(change.changeKey.objectKey.objectName + "." + change.changeKey.changeName))] = changeGroup
}
}
override fun retrieve(schema: String, dependency: String): T? {
return schemaToObjectMap[Tuples.pair(schema, convertDbObjectName(dependency))]
}
}
private inner class SchemaChangeObjectIndex<T : SortableDependencyGroup> : ChangeIndex<T> {
private val objectMap = mutableMapOf<String, T>()
override fun add(changeGroup: T) {
for (change in changeGroup.components) {
objectMap[convertDbObjectName(change.changeKey.objectKey.schema + "." + change.changeKey.objectKey.objectName + "." + change.changeKey.changeName)] = changeGroup
}
}
override fun retrieve(schema: String, dependency: String): T? {
return objectMap[convertDbObjectName(dependency)]
}
}
/**
* Custom edge type to allow for better error logging for cycles, namely to show the dependency edge type.
*/
private class DependencyEdge internal constructor(internal val edgeType: CodeDependencyType) : DefaultEdge()
companion object {
private val LOG = LoggerFactory.getLogger(GraphEnricherImpl::class.java)
}
}
| apache-2.0 | 47896274f427b22d28c99f86cba7ec37 | 44.668203 | 191 | 0.603027 | 5.322234 | false | false | false | false |
google/ide-perf | src/main/java/com/google/idea/perf/tracer/CallTree.kt | 1 | 2313 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.perf.tracer
/** A call tree, represented recursively. Also see [CallTreeUtil]. */
interface CallTree {
val tracepoint: Tracepoint
val callCount: Long
val wallTime: Long
val maxWallTime: Long
val children: Map<Tracepoint, CallTree>
fun forEachNodeInSubtree(action: (CallTree) -> Unit) {
action(this)
for (child in children.values) {
child.forEachNodeInSubtree(action)
}
}
fun allNodesInSubtree(): Sequence<CallTree> {
val nodes = mutableListOf<CallTree>()
forEachNodeInSubtree { nodes.add(it) }
return nodes.asSequence()
}
fun copy(): CallTree {
val copy = MutableCallTree(Tracepoint.ROOT)
copy.accumulate(this)
return copy
}
}
/** A mutable call tree implementation. */
class MutableCallTree(
override val tracepoint: Tracepoint
): CallTree {
override var callCount: Long = 0L
override var wallTime: Long = 0L
override var maxWallTime: Long = 0L
override val children: MutableMap<Tracepoint, MutableCallTree> = LinkedHashMap()
/** Accumulates the data from another call tree into this one. */
fun accumulate(other: CallTree) {
require(other.tracepoint == tracepoint) {
"Doesn't make sense to sum call tree nodes representing different tracepoints"
}
callCount += other.callCount
wallTime += other.wallTime
maxWallTime = maxOf(maxWallTime, other.maxWallTime)
for ((childTracepoint, otherChild) in other.children) {
val child = children.getOrPut(childTracepoint) { MutableCallTree(childTracepoint) }
child.accumulate(otherChild)
}
}
}
| apache-2.0 | 71955537f4bf4bfc9056e445e5f18fb4 | 31.577465 | 95 | 0.679204 | 4.422562 | false | false | false | false |
Streetwalrus/android_usb_msd | app/src/main/java/streetwalrus/usbmountr/FilePickerPreference.kt | 1 | 2743 | package streetwalrus.usbmountr
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.preference.Preference
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import java.io.File
class FilePickerPreference : Preference, ActivityResultDispatcher.ActivityResultHandler {
val TAG = "FilePickerPreference"
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int)
: super(context, attrs, defStyleAttr)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int)
: super(context, attrs, defStyleAttr, defStyleRes)
private var mActivityResultId = -1
init {
val appContext = context.applicationContext as UsbMountrApplication
mActivityResultId = appContext.mActivityResultDispatcher.registerHandler(this)
}
override fun onCreateView(parent: ViewGroup?): View {
updateSummary()
return super.onCreateView(parent)
}
override fun onPrepareForRemoval() {
super.onPrepareForRemoval()
val appContext = context.applicationContext as UsbMountrApplication
appContext.mActivityResultDispatcher.removeHandler(mActivityResultId)
}
override fun onClick() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "*/*"
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true)
val activity = context as Activity
activity.startActivityForResult(intent, mActivityResultId)
}
override fun onActivityResult(resultCode: Int, resultData: Intent?) {
if (resultCode == Activity.RESULT_OK && resultData != null) {
try {
val path = PathResolver.getPath(context, resultData.data)
Log.d(TAG, "Picked file $path")
persistString(path)
updateSummary()
} catch (e: SecurityException) {
// I'm extremely lazy and don't want to figure permissions out right now
Toast.makeText(context.applicationContext,
context.getString(R.string.file_picker_denied),
Toast.LENGTH_LONG
).show()
}
}
}
private fun updateSummary() {
val value = getPersistedString("")
if (value.equals("")) {
summary = context.getString(R.string.file_picker_nofile)
} else {
summary = File(value).name
}
}
} | mit | f6790cf5bf36013fb14c467f73e18dda | 34.636364 | 91 | 0.666424 | 4.924596 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/folding/MixinFoldingOptionsProvider.kt | 1 | 1543 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.folding
import com.intellij.application.options.editor.CodeFoldingOptionsProvider
import com.intellij.openapi.options.BeanConfigurable
class MixinFoldingOptionsProvider :
BeanConfigurable<MixinFoldingSettings.State>(MixinFoldingSettings.instance.state), CodeFoldingOptionsProvider {
init {
title = "Mixin"
val settings = MixinFoldingSettings.instance
checkBox(
"Target descriptors",
{ settings.state.foldTargetDescriptors },
{ b -> settings.state.foldTargetDescriptors = b }
)
checkBox("Object casts", { settings.state.foldObjectCasts }, { b -> settings.state.foldObjectCasts = b })
checkBox(
"Invoker casts",
{ settings.state.foldInvokerCasts },
{ b -> settings.state.foldInvokerCasts = b }
)
checkBox(
"Invoker method calls",
{ settings.state.foldInvokerMethodCalls },
{ b -> settings.state.foldInvokerMethodCalls = b }
)
checkBox(
"Accessor casts",
{ settings.state.foldAccessorCasts },
{ b -> settings.state.foldAccessorCasts = b }
)
checkBox(
"Accessor method calls",
{ settings.state.foldAccessorMethodCalls },
{ b -> settings.state.foldAccessorMethodCalls = b }
)
}
}
| mit | 6b4160dce59a778f33d363018d09781e | 29.86 | 115 | 0.618924 | 4.747692 | false | false | false | false |
veyndan/reddit-client | app/src/main/java/com/veyndan/paper/reddit/post/media/mutator/ImgflipMutatorFactory.kt | 2 | 889 | package com.veyndan.paper.reddit.post.media.mutator
import com.veyndan.paper.reddit.post.media.model.Image
import com.veyndan.paper.reddit.post.model.Post
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
class ImgflipMutatorFactory : MutatorFactory {
companion object {
private val REGEX = Regex("""^https?://(?:www\.)?imgflip\.com/i/(.*)#.*$""")
}
override fun mutate(post: Post): Maybe<Post> {
val matchResult = REGEX.matchEntire(post.linkUrl)
return Single.just(post)
.filter { matchResult != null }
.map {
val directImageUrl: String = "https://i.imgflip.com/${matchResult!!.groupValues[1]}.jpg"
val image: Image = Image(directImageUrl)
it.copy(it.medias.concatWith(Observable.just(image)))
}
}
}
| mit | 0cf14271c2f180f37d488ef273f0024c | 31.925926 | 108 | 0.624297 | 4.115741 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/stubs/LuaFuncBodyOwnerStub.kt | 2 | 2519 | /*
* 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.stubs
import com.intellij.openapi.util.Computable
import com.intellij.psi.stubs.StubElement
import com.tang.intellij.lua.ext.recursionGuard
import com.tang.intellij.lua.psi.*
import com.tang.intellij.lua.search.SearchContext
import com.tang.intellij.lua.ty.*
/**
* func body owner stub
* Created by TangZX on 2017/2/4.
*/
interface LuaFuncBodyOwnerStub<T : LuaFuncBodyOwner> : StubElement<T> {
val returnDocTy:ITy?
val params: Array<LuaParamInfo>
val tyParams: Array<TyParameter>
val overloads: Array<IFunSignature>
val varargTy: ITy?
private fun walkStub(stub: StubElement<*>, context: SearchContext): ITy? {
val psi = stub.psi
return recursionGuard(stub, Computable {
val ty = when (psi) {
is LuaReturnStat -> {
psi.exprList?.guessTypeAt(context)
}
is LuaDoStat,
is LuaWhileStat,
is LuaIfStat,
is LuaForAStat,
is LuaForBStat,
is LuaRepeatStat -> {
var ret: ITy? = null
for (childrenStub in stub.childrenStubs) {
ret = walkStub(childrenStub, context)
if (ret != null)
break
}
ret
}
else -> null
}
ty
})
}
fun guessReturnTy(context: SearchContext): ITy {
val docTy = returnDocTy
if (docTy != null){
if (docTy is TyTuple && context.index != -1) {
return docTy.list.getOrElse(context.index) { Ty.UNKNOWN }
}
return docTy
}
childrenStubs
.mapNotNull { walkStub(it, context) }
.forEach { return it }
return Ty.VOID
}
} | apache-2.0 | c89b108de668399c21053b25f6128beb | 31.727273 | 78 | 0.58158 | 4.350604 | false | false | false | false |
esofthead/mycollab | mycollab-web/src/main/java/com/mycollab/vaadin/AppUI.kt | 3 | 6722 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.vaadin
import com.google.common.base.MoreObjects
import com.mycollab.common.GenericLinkUtils
import com.mycollab.common.SessionIdGenerator
import com.mycollab.common.i18n.ErrorI18nEnum
import com.mycollab.configuration.ApplicationConfiguration
import com.mycollab.configuration.IDeploymentMode
import com.mycollab.core.utils.StringUtils
import com.mycollab.db.arguments.GroupIdProvider
import com.mycollab.module.billing.SubDomainNotExistException
import com.mycollab.module.user.domain.SimpleBillingAccount
import com.mycollab.module.user.service.BillingAccountService
import com.mycollab.spring.AppContextUtil
import com.mycollab.vaadin.ui.ThemeManager
import com.mycollab.vaadin.ui.UIUtils
import com.vaadin.server.Page
import com.vaadin.server.VaadinRequest
import com.vaadin.server.VaadinServletRequest
import com.vaadin.ui.UI
import org.slf4j.LoggerFactory
import java.util.*
/**
* @author MyCollab Ltd.
* @since 4.3.2
*/
abstract class AppUI : UI() {
/**
* Context of current logged in user
*/
protected var currentContext: UserUIContext? = null
private var initialSubDomain = "1"
var currentFragmentUrl: String? = null
private var _billingAccount: SimpleBillingAccount? = null
private val attributes = mutableMapOf<String, Any?>()
protected fun postSetupApp(request: VaadinRequest) {
initialSubDomain = UIUtils.getSubDomain(request)
val billingService = AppContextUtil.getSpringBean(BillingAccountService::class.java)
LOG.info("Load account info of sub-domain $initialSubDomain from ${(request as VaadinServletRequest).serverName}")
_billingAccount = billingService.getAccountByDomain(initialSubDomain)
if (_billingAccount == null) {
throw SubDomainNotExistException(UserUIContext.getMessage(ErrorI18nEnum.SUB_DOMAIN_IS_NOT_EXISTED, initialSubDomain))
} else {
LOG.info("Billing account info ")
val accountId = _billingAccount!!.id
ThemeManager.loadDesktopTheme(accountId!!)
}
}
fun setAttribute(key: String, value: Any?) {
attributes[key] = value
}
fun getAttribute(key: String): Any? = attributes[key]
val account: SimpleBillingAccount
get() = _billingAccount!!
val loggedInUser: String?
get() = currentContext?.session?.username
override fun close() {
LOG.debug("Application is closed. Clean all resources")
currentContext?.clearSessionVariables()
currentContext = null
super.close()
}
companion object {
private const val serialVersionUID = 1L
private val LOG = LoggerFactory.getLogger(AppUI::class.java)
init {
GroupIdProvider.registerAccountIdProvider(object : GroupIdProvider() {
override val groupId: Int
get() = AppUI.accountId
override val groupRequestedUser: String
get() = UserUIContext.getUsername()
})
SessionIdGenerator.registerSessionIdGenerator(object : SessionIdGenerator() {
override val sessionIdApp: String
get() = UI.getCurrent().toString()
})
}
/**
* @return
*/
@JvmStatic
val siteUrl: String
get() {
val deploymentMode = AppContextUtil.getSpringBean(IDeploymentMode::class.java)
return deploymentMode.getSiteUrl(instance._billingAccount!!.subdomain)
}
@JvmStatic
fun getBillingAccount(): SimpleBillingAccount? = instance._billingAccount
@JvmStatic
val instance: AppUI
get() = UI.getCurrent() as AppUI
@JvmStatic
val subDomain: String
get() = instance._billingAccount!!.subdomain
/**
* Get account id of current user
*
* @return account id of current user. Return 0 if can not get
*/
@JvmStatic
val accountId: Int
get() = try {
instance._billingAccount!!.id
} catch (e: Exception) {
0
}
@JvmStatic
val siteName: String
get() {
val appConfig = AppContextUtil.getSpringBean(ApplicationConfiguration::class.java)
return try {
MoreObjects.firstNonNull(instance._billingAccount!!.sitename, appConfig.siteName)
} catch (e: Exception) {
appConfig.siteName
}
}
@JvmStatic
val defaultCurrency: Currency
get() = instance._billingAccount!!.currencyInstance!!
@JvmStatic
val longDateFormat: String
get() = instance._billingAccount!!.longDateFormatInstance
@JvmStatic
fun showEmailPublicly(): Boolean? = instance._billingAccount!!.displayemailpublicly
@JvmStatic
val shortDateFormat: String
get() = instance._billingAccount!!.shortDateFormatInstance
@JvmStatic
val dateFormat: String
get() = instance._billingAccount!!.dateFormatInstance
@JvmStatic
val dateTimeFormat: String
get() = instance._billingAccount!!.dateTimeFormatInstance
@JvmStatic
val defaultLocale: Locale
get() = instance._billingAccount!!.localeInstance!!
/**
* @param fragment
* @param windowTitle
*/
@JvmStatic
fun addFragment(fragment: String, windowTitle: String) {
if (fragment.startsWith(GenericLinkUtils.URL_PREFIX_PARAM)) {
val newFragment = fragment.substring(1)
Page.getCurrent().setUriFragment(newFragment, false)
} else {
Page.getCurrent().setUriFragment(fragment, false)
}
Page.getCurrent().setTitle("${StringUtils.trim(windowTitle, 150)} [$siteName]")
}
}
}
| agpl-3.0 | c24d37a16a23ce25e8b6f32c396c44a3 | 32.944444 | 129 | 0.646035 | 5.142311 | false | false | false | false |
esofthead/mycollab | mycollab-scheduler/src/main/java/com/mycollab/module/project/schedule/email/service/ProjectMilestoneRelayEmailNotificationActionImpl.kt | 3 | 8955 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.schedule.email.service
import com.hp.gagawa.java.elements.A
import com.hp.gagawa.java.elements.Span
import com.mycollab.common.MonitorTypeConstants
import com.mycollab.common.i18n.GenericI18Enum
import com.mycollab.core.MyCollabException
import com.mycollab.core.utils.StringUtils
import com.mycollab.html.FormatUtils
import com.mycollab.html.LinkUtils
import com.mycollab.module.mail.MailUtils
import com.mycollab.module.project.ProjectLinkGenerator
import com.mycollab.module.project.ProjectTypeConstants
import com.mycollab.module.project.domain.Milestone
import com.mycollab.module.project.domain.ProjectRelayEmailNotification
import com.mycollab.module.project.domain.SimpleMilestone
import com.mycollab.module.project.i18n.MilestoneI18nEnum
import com.mycollab.module.project.i18n.OptionI18nEnum
import com.mycollab.module.project.service.MilestoneService
import com.mycollab.module.user.AccountLinkGenerator
import com.mycollab.module.user.service.UserService
import com.mycollab.schedule.email.ItemFieldMapper
import com.mycollab.schedule.email.MailContext
import com.mycollab.schedule.email.format.DateFieldFormat
import com.mycollab.schedule.email.format.FieldFormat
import com.mycollab.schedule.email.format.I18nFieldFormat
import com.mycollab.schedule.email.project.ProjectMilestoneRelayEmailNotificationAction
import com.mycollab.spring.AppContextUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
class ProjectMilestoneRelayEmailNotificationActionImpl : SendMailToAllMembersAction<SimpleMilestone>(), ProjectMilestoneRelayEmailNotificationAction {
@Autowired private lateinit var milestoneService: MilestoneService
private val mapper = MilestoneFieldNameMapper()
override fun getItemName(): String = StringUtils.trim(bean!!.name, 100)
override fun getProjectName(): String = bean!!.projectName!!
override fun getCreateSubject(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_CREATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getCreateSubjectNotification(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_CREATE_ITEM_SUBJECT, projectLink(), userLink(context), milestoneLink())
override fun getUpdateSubject(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getUpdateSubjectNotification(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, projectLink(), userLink(context), milestoneLink())
override fun getCommentSubject(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getCommentSubjectNotification(context: MailContext<SimpleMilestone>): String = context.getMessage(
MilestoneI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, projectLink(), userLink(context), milestoneLink())
private fun projectLink() = A(ProjectLinkGenerator.generateProjectLink(bean!!.projectid)).appendText(bean!!.projectName).write()
private fun userLink(context: MailContext<SimpleMilestone>) = A(AccountLinkGenerator.generateUserLink(context.user.username)).appendText(context.changeByUserFullName).write()
private fun milestoneLink() = A(ProjectLinkGenerator.generateMilestonePreviewLink(bean!!.projectid, bean!!.id)).appendText(getItemName()).write()
override fun getItemFieldMapper(): ItemFieldMapper = mapper
override fun getBeanInContext(notification: ProjectRelayEmailNotification): SimpleMilestone? =
milestoneService.findById(notification.typeid.toInt(), notification.saccountid)
override fun getType(): String = ProjectTypeConstants.MILESTONE
override fun getTypeId(): String = "${bean!!.id}"
class MilestoneFieldNameMapper : ItemFieldMapper() {
init {
put(Milestone.Field.name, GenericI18Enum.FORM_NAME, true)
put(Milestone.Field.status, I18nFieldFormat(Milestone.Field.status.name, GenericI18Enum.FORM_STATUS,
OptionI18nEnum.MilestoneStatus::class.java))
put(Milestone.Field.assignuser, AssigneeFieldFormat(Milestone.Field.assignuser.name, GenericI18Enum.FORM_ASSIGNEE))
put(Milestone.Field.startdate, DateFieldFormat(Milestone.Field.startdate.name, GenericI18Enum.FORM_START_DATE))
put(Milestone.Field.enddate, DateFieldFormat(Milestone.Field.enddate.name, GenericI18Enum.FORM_END_DATE))
put(Milestone.Field.description, GenericI18Enum.FORM_DESCRIPTION, true)
}
}
class AssigneeFieldFormat(fieldName: String, displayName: Enum<*>) : FieldFormat(fieldName, displayName) {
override fun formatField(context: MailContext<*>): String {
val milestone = context.wrappedBean as SimpleMilestone
return if (milestone.assignuser != null) {
val userAvatarLink = MailUtils.getAvatarLink(milestone.ownerAvatarId, 16)
val img = FormatUtils.newImg("avatar", userAvatarLink)
val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(milestone.saccountid),
milestone.assignuser)
val link = FormatUtils.newA(userLink, milestone.ownerFullName)
FormatUtils.newLink(img, link).write()
} else Span().write()
}
override fun formatField(context: MailContext<*>, value: String): String {
if (StringUtils.isBlank(value)) {
return Span().write()
}
val userService = AppContextUtil.getSpringBean(UserService::class.java)
val user = userService.findUserByUserNameInAccount(value, context.saccountid)
return if (user != null) {
val userAvatarLink = MailUtils.getAvatarLink(user.avatarid, 16)
val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(context.saccountid),
user.username)
val img = FormatUtils.newImg("avatar", userAvatarLink)
val link = FormatUtils.newA(userLink, user.displayName!!)
FormatUtils.newLink(img, link).write()
} else value
}
}
override fun buildExtraTemplateVariables(context: MailContext<SimpleMilestone>) {
val emailNotification = context.emailNotification
val summary = bean!!.name
val summaryLink = ProjectLinkGenerator.generateMilestonePreviewFullLink(siteUrl, bean!!.projectid, bean!!.id)
val avatarId = if (projectMember != null) projectMember!!.memberAvatarId else ""
val userAvatar = LinkUtils.newAvatar(avatarId)
val makeChangeUser = "${userAvatar.write()} ${emailNotification.changeByUserFullName}"
val actionEnum = when (emailNotification.action) {
MonitorTypeConstants.CREATE_ACTION -> MilestoneI18nEnum.MAIL_CREATE_ITEM_HEADING
MonitorTypeConstants.UPDATE_ACTION -> MilestoneI18nEnum.MAIL_UPDATE_ITEM_HEADING
MonitorTypeConstants.ADD_COMMENT_ACTION -> MilestoneI18nEnum.MAIL_COMMENT_ITEM_HEADING
else -> throw MyCollabException("Not support action ${emailNotification.action}")
}
contentGenerator.putVariable("projectName", bean!!.projectName!!)
contentGenerator.putVariable("projectNotificationUrl", ProjectLinkGenerator.generateProjectSettingFullLink(siteUrl, bean!!.projectid))
contentGenerator.putVariable("actionHeading", context.getMessage(actionEnum, makeChangeUser))
contentGenerator.putVariable("name", summary)
contentGenerator.putVariable("summaryLink", summaryLink)
}
} | agpl-3.0 | c4674662fd211de10e29ddc452251271 | 53.272727 | 178 | 0.750838 | 4.917079 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-androidx-collection/src/main/kotlin/org/ccci/gto/android/common/androidx/collection/LongSparseParcelableArray.kt | 2 | 1348 | package org.ccci.gto.android.common.androidx.collection
import android.os.Parcel
import android.os.Parcelable
import androidx.collection.LongSparseArray
import kotlinx.parcelize.Parceler
import kotlinx.parcelize.Parcelize
@Parcelize
class LongSparseParcelableArray<T : Parcelable?> : LongSparseArray<T>(), Parcelable {
internal companion object : Parceler<LongSparseParcelableArray<Parcelable?>> {
override fun LongSparseParcelableArray<Parcelable?>.write(parcel: Parcel, flags: Int) {
val size = size()
val keys = LongArray(size)
val values = arrayOfNulls<Parcelable>(size)
for (i in 0 until size) {
keys[i] = keyAt(i)
values[i] = valueAt(i)
}
parcel.writeInt(size)
parcel.writeLongArray(keys)
parcel.writeParcelableArray(values, 0)
}
override fun create(parcel: Parcel): LongSparseParcelableArray<Parcelable?> {
val size = parcel.readInt()
val keys = LongArray(size).also { parcel.readLongArray(it) }
val values = parcel.readParcelableArray(LongSparseParcelableArray::class.java.classLoader)
return LongSparseParcelableArray<Parcelable?>()
.apply { for (i in 0 until size) put(keys[i], values?.get(i)) }
}
}
}
| mit | e43449441044ecd564560f130df2ce54 | 38.647059 | 102 | 0.651335 | 4.763251 | false | false | false | false |
docker-client/docker-compose-v3 | src/main/kotlin/de/gesellix/docker/compose/types/StackVolume.kt | 1 | 661 | package de.gesellix.docker.compose.types
import com.squareup.moshi.Json
import de.gesellix.docker.compose.adapters.DriverOptsType
import de.gesellix.docker.compose.adapters.ExternalType
import de.gesellix.docker.compose.adapters.LabelsType
data class StackVolume(
var name: String? = "",
var driver: String? = null,
@Json(name = "driver_opts")
@DriverOptsType
var driverOpts: DriverOpts = DriverOpts(),
// StackVolume.external.name is deprecated and replaced by StackVolume.name
@ExternalType
var external: External = External(),
@LabelsType
var labels: Labels = Labels()
)
| mit | ac04265442f202423272d88a680c56c1 | 26.541667 | 83 | 0.69289 | 4.348684 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/wheelchair_access/AddWheelChairAccessToilets.kt | 1 | 1104 | package de.westnordost.streetcomplete.quests.wheelchair_access
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
class AddWheelChairAccessToilets(o: OverpassMapDataDao) : SimpleOverpassQuestType<String>(o) {
override val tagFilters =
" nodes, ways with amenity=toilets and access !~ private|customers and !wheelchair"
override val commitMessage = "Add wheelchair access to toilets"
override val icon = R.drawable.ic_quest_toilets_wheelchair
override fun getTitle(tags: Map<String, String>) =
if (tags.containsKey("name"))
R.string.quest_wheelchairAccess_toilets_name_title
else
R.string.quest_wheelchairAccess_toilets_title
override fun createForm() = AddWheelchairAccessToiletsForm()
override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) {
changes.add("wheelchair", answer)
}
}
| gpl-3.0 | 8097d9efd1021147722ab603e156b0ce | 41.461538 | 94 | 0.765399 | 4.658228 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/nfc/NFCEnterCredentialsActivity.kt | 1 | 1797 | package org.walleth.nfc
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_nfc_enter_credentials.*
import org.ligi.kaxt.setVisibility
import org.ligi.kaxtui.alert
import org.walleth.R
import org.walleth.base_activities.BaseSubActivity
import org.walleth.data.EXTRA_KEY_NFC_CREDENTIALS
class NFCEnterCredentialsActivity : BaseSubActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nfc_enter_credentials)
radio_new_card.setOnCheckedChangeListener { _, _ ->
refresh()
}
fab.setOnClickListener {
when {
input_pin.text?.length != 6 -> alert("The PIN must have 6 digits")
input_puk.text?.length != 12 && isNewCard() -> alert("The PUK must have 12 digits")
input_pairingpwd.text.isNullOrBlank() -> alert("The pairing password cannot be blank")
else -> {
val nfcCredentials = NFCCredentials(
isNewCard = radio_new_card.isChecked,
pin = input_pin.text.toString(),
puk = input_puk.text.toString(),
pairingPassword = input_pairingpwd.text.toString()
)
val resultIntent = Intent().putExtra(EXTRA_KEY_NFC_CREDENTIALS, nfcCredentials)
setResult(Activity.RESULT_OK, resultIntent)
finish()
}
}
}
refresh()
}
private fun refresh() {
puk_input_layout.setVisibility(isNewCard())
}
private fun isNewCard() = radio_new_card.isChecked
}
| gpl-3.0 | a82fd9234d20e05fb6f6dcba6a437a11 | 34.235294 | 102 | 0.599889 | 4.753968 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectBasicMaterialDesign/app/src/main/java/me/liuqingwen/android/projectbasicmaterialdesign/MainActivity.kt | 1 | 5071 | package me.liuqingwen.android.projectbasicmaterialdesign
import android.content.Context
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.layout_activity_main.*
import kotlinx.android.synthetic.main.recycler_list_item.view.*
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jetbrains.anko.toast
class MainActivity : AppCompatActivity()
{
private val dataUrl = "http://liuqingwen.me/data/get-images-json.php?type=json&delay=0"
private val httpClient by lazy { OkHttpClient.Builder().build() }
private val dataObservable by lazy {
Observable.create(ObservableOnSubscribe<Response> {
val request = Request.Builder().get().url(this.dataUrl).build()
try
{
val response = this.httpClient.newCall(request).execute()
it.onNext(response)
it.onComplete()
}
catch(e: Exception)
{
//it.onError(e)
this.onLoadError()
}
})
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_activity_main)
this.init()
this.loadData()
}
private fun onLoadError()
{
Snackbar.make(this.floatingActionButton, "Error Loading.", Snackbar.LENGTH_INDEFINITE).setAction("Reload") { this.loadData() }.show()
}
private fun loadData()
{
this.dataObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
if (it.isSuccessful)
{
val content = it.body()?.string()
val type = object : TypeToken<List<MyItem>>() {}.type
try
{
val items = Gson().fromJson<List<MyItem>>(content, type)
this.displayItems(items)
}
catch(e: Exception)
{
this.onLoadError()
}
}else
{
this.onLoadError()
}
}
}
private fun displayItems(items: List<MyItem>?)
{
if (items == null)
{
this.onLoadError()
return
}
Snackbar.make(this.floatingActionButton, "Is Done!", Snackbar.LENGTH_LONG).setAction("OK") { }.show()
val adapter = MyAdapter(this, items)
this.recyclerView.adapter = adapter
val layoutManager = GridLayoutManager(this, 2)
this.recyclerView.layoutManager = layoutManager
}
private fun init()
{
this.setSupportActionBar(this.toolbar)
this.supportActionBar?.setDisplayHomeAsUpEnabled(true)
this.supportActionBar?.setHomeAsUpIndicator(R.drawable.menu)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean
{
this.menuInflater.inflate(R.menu.menu_toolbar, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean
{
when(item?.itemId)
{
android.R.id.home -> { this.layoutDrawer.openDrawer(Gravity.START) }
R.id.menuVideoCall -> {}
R.id.menuUpload -> {}
R.id.menuGlobe -> {}
R.id.menuPlus -> {}
else -> this.toast("Not implemented yet!")
}
return super.onOptionsItemSelected(item)
}
}
data class MyItem(val url:String, val title:String)
class MyViewHolder(itemView:View):RecyclerView.ViewHolder(itemView)
{
val labelTitle:TextView = itemView.labelTitle
val imageTitle:ImageView = itemView.imageTitle
}
class MyAdapter(val context:Context, val dataList:List<MyItem>):RecyclerView.Adapter<MyViewHolder>()
{
private val inflater by lazy { LayoutInflater.from(this.context) }
override fun onBindViewHolder(holder: MyViewHolder?, position: Int)
{
val item = this.dataList[position]
holder?.labelTitle?.text = item.title
Glide.with(this.context).load(item.url).into(holder?.imageTitle)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder
{
val view = this.inflater.inflate(R.layout.recycler_list_item, parent, false)
val viewHolder = MyViewHolder(view)
return viewHolder
}
override fun getItemCount(): Int
{
return this.dataList.size
}
}
| mit | 480ec4d09f6aebc5b37da051517828df | 30.893082 | 141 | 0.630842 | 4.656566 | false | false | false | false |
K0zka/wikistat | src/main/kotlin/org/dictat/wikistat/wikidata/WikiData.kt | 1 | 2031 | package org.dictat.wikistat.wikidata
import java.util.HashMap
import org.apache.http.client.HttpClient
import org.apache.http.impl.client.AutoRetryHttpClient
import org.apache.http.impl.client.DecompressingHttpClient
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpGet
import java.net.URLEncoder
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.databind.ObjectMapper
import java.util.Collections
import org.apache.http.protocol.HTTP
import org.dictat.wikistat.utils.VersionUtils
class WikiData() {
class PageMissingException() : Exception() {
}
fun langLinks(wikipage: String, lang: String): Map<String, String> {
//TODO: this method is messy, cleanup needed
val ret = HashMap<String, String>();
val defaultHttpClient = DefaultHttpClient()
defaultHttpClient.getParams()!!.setParameter(HTTP.USER_AGENT,"wikistat robot "+ VersionUtils.getVersion() + " http://dictat.org/");
val client: HttpClient = AutoRetryHttpClient(DecompressingHttpClient(defaultHttpClient))
val req = HttpGet("https://"+lang+".wikipedia.org/w/api.php?format=json&action=query&prop=langlinks&lllimit=500&titles="+URLEncoder.encode(wikipage,"UTF-8"));
val response = client.execute(req);
val json = ObjectMapper().readTree(response!!.getEntity()!!.getContent());
val page = json?.get("query")?.get("pages")
if(page == null) {
throw PageMissingException()
}
for(elem in page.elements()) {
val langlinks = elem.get("langlinks")
if(langlinks != null) {
for(sp in langlinks.elements()) {
ret.put(sp.get("lang")?.textValue()!!, sp.get("*")?.textValue()!!);
}
} else {
if(elem.get("missing") != null) {
throw PageMissingException()
}
}
}
return ret;
}
} | apache-2.0 | d0132d1f08c28a7bb6dc02d090f97b72 | 39.64 | 166 | 0.656327 | 4.293869 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/entities/TotalDailyDose.kt | 1 | 1611 | package info.nightscout.androidaps.database.entities
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import info.nightscout.androidaps.database.TABLE_TOTAL_DAILY_DOSES
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.interfaces.DBEntryWithTime
import info.nightscout.androidaps.database.interfaces.TraceableDBEntry
import java.util.*
@Entity(tableName = TABLE_TOTAL_DAILY_DOSES,
foreignKeys = [ForeignKey(
entity = TotalDailyDose::class,
parentColumns = ["id"],
childColumns = ["referenceId"])],
indices = [
Index("id"),
Index("pumpId"),
Index("pumpType"),
Index("pumpSerial"),
Index("isValid"),
Index("referenceId"),
Index("timestamp")
])
data class TotalDailyDose(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
override var version: Int = 0,
override var dateCreated: Long = -1,
override var isValid: Boolean = true,
override var referenceId: Long? = null,
@Embedded
override var interfaceIDs_backing: InterfaceIDs? = InterfaceIDs(),
override var timestamp: Long,
override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(),
var basalAmount: Double = 0.0,
var bolusAmount: Double = 0.0,
var totalAmount: Double = 0.0, // if zero it's calculated as basalAmount + bolusAmount
var carbs: Double = 0.0
) : TraceableDBEntry, DBEntryWithTime {
companion object
} | agpl-3.0 | dcaf8ee730cd012549b712b61e16beb0 | 34.822222 | 90 | 0.71198 | 4.401639 | false | false | false | false |
Heiner1/AndroidAPS | core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/PrefsFormat.kt | 1 | 3084 | package info.nightscout.androidaps.plugins.general.maintenance.formats
import android.content.Context
import android.os.Parcelable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import info.nightscout.androidaps.core.R
import kotlinx.parcelize.Parcelize
import java.io.File
enum class PrefsMetadataKey(val key: String, @DrawableRes val icon: Int, @StringRes val label: Int) {
FILE_FORMAT("format", R.drawable.ic_meta_format, R.string.metadata_label_format),
CREATED_AT("created_at", R.drawable.ic_meta_date, R.string.metadata_label_created_at),
AAPS_VERSION("aaps_version", R.drawable.ic_meta_version, R.string.metadata_label_aaps_version),
AAPS_FLAVOUR("aaps_flavour", R.drawable.ic_meta_flavour, R.string.metadata_label_aaps_flavour),
DEVICE_NAME("device_name", R.drawable.ic_meta_name, R.string.metadata_label_device_name),
DEVICE_MODEL("device_model", R.drawable.ic_meta_model, R.string.metadata_label_device_model),
ENCRYPTION("encryption", R.drawable.ic_meta_encryption, R.string.metadata_label_encryption);
companion object {
private val keyToEnumMap = HashMap<String, PrefsMetadataKey>()
init {
for (value in values()) keyToEnumMap[value.key] = value
}
fun fromKey(key: String): PrefsMetadataKey? =
if (keyToEnumMap.containsKey(key)) {
keyToEnumMap[key]
} else {
null
}
}
fun formatForDisplay(context: Context, value: String): String {
return when (this) {
FILE_FORMAT -> when (value) {
EncryptedPrefsFormat.FORMAT_KEY_ENC -> context.getString(R.string.metadata_format_new)
EncryptedPrefsFormat.FORMAT_KEY_NOENC -> context.getString(R.string.metadata_format_debug)
else -> context.getString(R.string.metadata_format_other)
}
CREATED_AT -> value.replace("T", " ").replace("Z", " (UTC)")
else -> value
}
}
}
@Parcelize
data class PrefMetadata(var value: String, var status: PrefsStatus, var info: String? = null) : Parcelable
typealias PrefMetadataMap = Map<PrefsMetadataKey, PrefMetadata>
data class Prefs(val values: Map<String, String>, var metadata: PrefMetadataMap)
interface PrefsFormat {
fun savePreferences(file: File, prefs: Prefs, masterPassword: String? = null)
fun loadPreferences(file: File, masterPassword: String? = null): Prefs
fun loadMetadata(contents: String? = null): PrefMetadataMap
fun isPreferencesFile(file: File, preloadedContents: String? = null): Boolean
}
enum class PrefsStatus(@DrawableRes val icon: Int) {
OK(R.drawable.ic_meta_ok),
WARN(R.drawable.ic_meta_warning),
ERROR(R.drawable.ic_meta_error),
UNKNOWN(R.drawable.ic_meta_error),
DISABLED(R.drawable.ic_meta_error)
}
class PrefFileNotFoundError(message: String) : Exception(message)
class PrefIOError(message: String) : Exception(message)
class PrefFormatError(message: String) : Exception(message)
| agpl-3.0 | 06fc12a5d2ffeee44a58f7034e949bf6 | 39.051948 | 106 | 0.68904 | 4.005195 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputString.kt | 1 | 1075 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
class InputString(var value: String = "") : Element() {
private val textWatcher: TextWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
value = s.toString()
}
}
override fun addToLayout(root: LinearLayout) {
root.addView(
EditText(root.context).apply {
setText(value)
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
addTextChangedListener(textWatcher)
gravity = Gravity.CENTER_HORIZONTAL
})
}
} | agpl-3.0 | 3ffa94dd8e8c13c8e586442d518e8995 | 36.103448 | 130 | 0.683721 | 4.886364 | false | false | false | false |
k9mail/k-9 | backend/jmap/src/main/java/com/fsck/k9/backend/jmap/CommandMove.kt | 1 | 2141 | package com.fsck.k9.backend.jmap
import rs.ltt.jmap.client.JmapClient
import rs.ltt.jmap.common.method.call.email.SetEmailMethodCall
import rs.ltt.jmap.common.method.response.email.SetEmailMethodResponse
import rs.ltt.jmap.common.util.Patches
import timber.log.Timber
class CommandMove(
private val jmapClient: JmapClient,
private val accountId: String
) {
fun moveMessages(targetFolderServerId: String, messageServerIds: List<String>) {
Timber.v("Moving %d messages to %s", messageServerIds.size, targetFolderServerId)
val mailboxPatch = Patches.set("mailboxIds", mapOf(targetFolderServerId to true))
updateEmails(messageServerIds, mailboxPatch)
}
fun moveMessagesAndMarkAsRead(targetFolderServerId: String, messageServerIds: List<String>) {
Timber.v("Moving %d messages to %s and marking them as read", messageServerIds.size, targetFolderServerId)
val mailboxPatch = Patches.builder()
.set("mailboxIds", mapOf(targetFolderServerId to true))
.set("keywords/\$seen", true)
.build()
updateEmails(messageServerIds, mailboxPatch)
}
fun copyMessages(targetFolderServerId: String, messageServerIds: List<String>) {
Timber.v("Copying %d messages to %s", messageServerIds.size, targetFolderServerId)
val mailboxPatch = Patches.set("mailboxIds/$targetFolderServerId", true)
updateEmails(messageServerIds, mailboxPatch)
}
private fun updateEmails(messageServerIds: List<String>, patch: Map<String, Any>?) {
val session = jmapClient.session.get()
val maxObjectsInSet = session.maxObjectsInSet
messageServerIds.chunked(maxObjectsInSet).forEach { emailIds ->
val updates = emailIds.map { emailId ->
emailId to patch
}.toMap()
val setEmailCall = jmapClient.call(
SetEmailMethodCall.builder()
.accountId(accountId)
.update(updates)
.build()
)
setEmailCall.getMainResponseBlocking<SetEmailMethodResponse>()
}
}
}
| apache-2.0 | f7f59f9430497dfc4c7c3411963447c3 | 37.232143 | 114 | 0.678188 | 4.990676 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentAbEntityImpl.kt | 2 | 8005 | 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.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent
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 ParentAbEntityImpl: ParentAbEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentAbEntity::class.java, ChildAbstractBaseEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
override val children: List<ChildAbstractBaseEntity>
get() = snapshot.extractOneToAbstractManyChildren<ChildAbstractBaseEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ParentAbEntityData?): ModifiableWorkspaceEntityBase<ParentAbEntity>(), ParentAbEntity.Builder {
constructor(): this(ParentAbEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ParentAbEntity 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
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field ParentAbEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field ParentAbEntity#children should be initialized")
}
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ParentAbEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var children: List<ChildAbstractBaseEntity>
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyChildren<ChildAbstractBaseEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildAbstractBaseEntity> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<ChildAbstractBaseEntity> ?: 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 fun getEntityData(): ParentAbEntityData = result ?: super.getEntityData() as ParentAbEntityData
override fun getEntityClass(): Class<ParentAbEntity> = ParentAbEntity::class.java
}
}
class ParentAbEntityData : WorkspaceEntityData<ParentAbEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ParentAbEntity> {
val modifiable = ParentAbEntityImpl.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): ParentAbEntity {
val entity = ParentAbEntityImpl()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ParentAbEntity::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 ParentAbEntityData
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 ParentAbEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
} | apache-2.0 | 68e261b78a07b1dc3b44c9b7ef1be45c | 40.268041 | 240 | 0.621861 | 6.148233 | false | false | false | false |
PolymerLabs/arcs | java/arcs/sdk/js/Utils.kt | 1 | 822 | // ktlint-disable filename
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
@file:Suppress("PackageName", "TopLevelName")
package arcs.sdk
object Utils : UtilsInterface {
override fun log(msg: String): Unit = throw NotImplementedError()
override fun abort(): Unit = throw NotImplementedError()
override fun assert(message: String, cond: Boolean): Unit = throw NotImplementedError()
override fun toUtf8String(bytes: ByteArray): String = throw NotImplementedError()
override fun toUtf8ByteArray(str: String): ByteArray = throw NotImplementedError()
}
| bsd-3-clause | b48b1e50c1bbaf890d81742aff4fe990 | 29.444444 | 96 | 0.746959 | 4.349206 | false | false | false | false |
Maccimo/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/PackageSearchUI.kt | 4 | 8831 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetbrains.packagesearch.intellij.plugin.ui
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBValue
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.components.BrowsableLinkLabel
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScalableUnits
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import org.jetbrains.annotations.Nls
import java.awt.CardLayout
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import java.awt.FlowLayout
import java.awt.Rectangle
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.BorderFactory
import javax.swing.BoxLayout
import javax.swing.Icon
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JMenuItem
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.JTextField
import javax.swing.KeyStroke
import javax.swing.Scrollable
object PackageSearchUI {
private val MAIN_BG_COLOR: Color = JBColor.namedColor("Plugins.background", UIUtil.getListBackground())
internal val GRAY_COLOR: Color = JBColor.namedColor("Label.infoForeground", JBColor(Gray._120, Gray._135))
internal val HeaderBackgroundColor = MAIN_BG_COLOR
internal val SectionHeaderBackgroundColor = JBColor.namedColor("Plugins.SectionHeader.background", 0xF7F7F7, 0x3C3F41)
internal val UsualBackgroundColor = MAIN_BG_COLOR
internal val ListRowHighlightBackground = JBColor.namedColor("PackageSearch.SearchResult.background", 0xF2F5F9, 0x4C5052)
internal val InfoBannerBackground = JBColor.lazy {
EditorColorsManager.getInstance().globalScheme.getColor(EditorColors.NOTIFICATION_BACKGROUND)
?: JBColor(0xE6EEF7, 0x1C3956)
}
internal val MediumHeaderHeight = JBValue.Float(30f)
internal val SmallHeaderHeight = JBValue.Float(24f)
@Suppress("MagicNumber") // Thanks, Swing
internal fun headerPanel(init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
init {
border = JBEmptyBorder(2, 0, 2, 12)
init()
}
override fun getBackground() = HeaderBackgroundColor
}
internal fun cardPanel(cards: List<JPanel> = emptyList(), backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) =
object : JPanel() {
init {
layout = CardLayout()
cards.forEach { add(it) }
init()
}
override fun getBackground() = backgroundColor
}
internal fun borderPanel(backgroundColor: Color = UsualBackgroundColor, init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() {
init {
init()
}
override fun getBackground() = backgroundColor
}
internal fun boxPanel(axis: Int = BoxLayout.Y_AXIS, backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) =
object : JPanel() {
init {
layout = BoxLayout(this, axis)
init()
}
override fun getBackground() = backgroundColor
}
internal fun flowPanel(backgroundColor: Color = UsualBackgroundColor, init: JPanel.() -> Unit) = object : JPanel() {
init {
layout = FlowLayout(FlowLayout.LEFT)
init()
}
override fun getBackground() = backgroundColor
}
fun checkBox(@Nls title: String, init: JCheckBox.() -> Unit = {}) = object : JCheckBox(title) {
init {
init()
}
override fun getBackground() = UsualBackgroundColor
}
fun textField(init: JTextField.() -> Unit): JTextField = JTextField().apply {
init()
}
internal fun menuItem(@Nls title: String, icon: Icon?, handler: () -> Unit): JMenuItem {
if (icon != null) {
return JMenuItem(title, icon).apply { addActionListener { handler() } }
}
return JMenuItem(title).apply { addActionListener { handler() } }
}
fun createLabel(@Nls text: String? = null, init: JLabel.() -> Unit = {}) = JLabel().apply {
font = StartupUiUtil.getLabelFont()
if (text != null) this.text = text
init()
}
internal fun createLabelWithLink(init: BrowsableLinkLabel.() -> Unit = {}) = BrowsableLinkLabel().apply {
font = StartupUiUtil.getLabelFont()
init()
}
internal fun getTextColorPrimary(isSelected: Boolean = false): Color = when {
isSelected -> JBColor.lazy { UIUtil.getListSelectionForeground(true) }
else -> JBColor.lazy { UIUtil.getListForeground() }
}
internal fun getTextColorSecondary(isSelected: Boolean = false): Color = when {
isSelected -> getTextColorPrimary(isSelected)
else -> GRAY_COLOR
}
internal fun setHeight(component: JComponent, @ScalableUnits height: Int, keepWidth: Boolean = false) {
setHeightPreScaled(component, height.scaled(), keepWidth)
}
internal fun setHeightPreScaled(component: JComponent, @ScaledPixels height: Int, keepWidth: Boolean = false) {
component.apply {
preferredSize = Dimension(if (keepWidth) preferredSize.width else 0, height)
minimumSize = Dimension(if (keepWidth) minimumSize.width else 0, height)
maximumSize = Dimension(if (keepWidth) maximumSize.width else Int.MAX_VALUE, height)
}
}
internal fun verticalScrollPane(c: Component) = object : JScrollPane(
VerticalScrollPanelWrapper(c),
VERTICAL_SCROLLBAR_AS_NEEDED,
HORIZONTAL_SCROLLBAR_NEVER
) {
init {
border = BorderFactory.createEmptyBorder()
viewport.background = UsualBackgroundColor
}
}
internal fun overrideKeyStroke(c: JComponent, stroke: String, action: () -> Unit) = overrideKeyStroke(c, stroke, stroke, action)
internal fun overrideKeyStroke(c: JComponent, key: String, stroke: String, action: () -> Unit) {
val inputMap = c.getInputMap(JComponent.WHEN_FOCUSED)
inputMap.put(KeyStroke.getKeyStroke(stroke), key)
c.actionMap.put(
key,
object : AbstractAction() {
override fun actionPerformed(arg: ActionEvent) {
action()
}
}
)
}
private class VerticalScrollPanelWrapper(content: Component) : JPanel(), Scrollable {
init {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
add(content)
}
override fun getPreferredScrollableViewportSize(): Dimension = preferredSize
override fun getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 10
override fun getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 100
override fun getScrollableTracksViewportWidth() = true
override fun getScrollableTracksViewportHeight() = false
override fun getBackground() = UsualBackgroundColor
}
}
internal class ComponentActionWrapper(private val myComponentCreator: () -> JComponent) : DumbAwareAction(), CustomComponentAction {
override fun createCustomComponent(presentation: Presentation, place: String) = myComponentCreator()
override fun actionPerformed(e: AnActionEvent) {
// No-op
}
}
internal fun JComponent.updateAndRepaint() {
invalidate()
repaint()
}
| apache-2.0 | 82733507e94f662c94fa4b27c7d0c763 | 37.395652 | 144 | 0.678632 | 4.879006 | false | false | false | false |
Maccimo/intellij-community | platform/testFramework/src/com/intellij/testFramework/ServiceContainerUtil.kt | 3 | 4871 | // 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:JvmName("ServiceContainerUtil")
package com.intellij.testFramework
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Application
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.extensions.BaseExtensionPointName
import com.intellij.openapi.extensions.DefaultPluginDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.util.messages.ListenerDescriptor
import com.intellij.util.messages.MessageBusOwner
import org.jetbrains.annotations.TestOnly
private val testDescriptor by lazy { DefaultPluginDescriptor("test") }
@TestOnly
fun <T : Any> ComponentManager.registerServiceInstance(serviceInterface: Class<T>, instance: T) {
(this as ComponentManagerImpl).registerServiceInstance(serviceInterface, instance, testDescriptor)
}
/**
* Register a new service or replace an existing service with a specified instance for testing purposes.
* Registration will be rolled back when parentDisposable is disposed. In most of the cases,
* [com.intellij.testFramework.UsefulTestCase.getTestRootDisposable] should be specified.
*/
@TestOnly
fun <T : Any> ComponentManager.registerOrReplaceServiceInstance(serviceInterface: Class<T>, instance: T, parentDisposable: Disposable) {
val previous = this.getService(serviceInterface)
if (previous != null) {
replaceService(serviceInterface, instance, parentDisposable)
} else {
(this as ComponentManagerImpl).registerServiceInstance(serviceInterface, instance, testDescriptor)
if (instance is Disposable) {
Disposer.register(parentDisposable, instance)
} else {
Disposer.register(parentDisposable) {
this.unregisterComponent(serviceInterface)
}
}
}
}
@TestOnly
fun <T : Any> ComponentManager.replaceService(serviceInterface: Class<T>, instance: T, parentDisposable: Disposable) {
(this as ComponentManagerImpl).replaceServiceInstance(serviceInterface, instance, parentDisposable)
}
@TestOnly
fun <T : Any> ComponentManager.registerComponentInstance(componentInterface: Class<T>, instance: T, parentDisposable: Disposable?) {
(this as ComponentManagerImpl).replaceComponentInstance(componentInterface, instance, parentDisposable)
}
@Suppress("DeprecatedCallableAddReplaceWith")
@TestOnly
@Deprecated("Pass parentDisposable")
fun <T : Any> ComponentManager.registerComponentInstance(componentInterface: Class<T>, instance: T) {
(this as ComponentManagerImpl).replaceComponentInstance(componentInterface, instance, null)
}
@TestOnly
@JvmOverloads
fun ComponentManager.registerComponentImplementation(componentInterface: Class<*>, componentImplementation: Class<*>, shouldBeRegistered: Boolean = false) {
(this as ComponentManagerImpl).registerComponentImplementation(componentInterface, componentImplementation, shouldBeRegistered)
}
@TestOnly
fun <T : Any> ComponentManager.registerExtension(name: BaseExtensionPointName<*>, instance: T, parentDisposable: Disposable) {
extensionArea.getExtensionPoint<T>(name.name).registerExtension(instance, parentDisposable)
}
@TestOnly
fun ComponentManager.getServiceImplementationClassNames(prefix: String): List<String> {
val result = ArrayList<String>()
processAllServiceDescriptors(this) { serviceDescriptor ->
val implementation = serviceDescriptor.implementation ?: return@processAllServiceDescriptors
if (implementation.startsWith(prefix)) {
result.add(implementation)
}
}
return result
}
fun processAllServiceDescriptors(componentManager: ComponentManager, consumer: (ServiceDescriptor) -> Unit) {
for (plugin in PluginManagerCore.getLoadedPlugins()) {
val pluginDescriptor = plugin as IdeaPluginDescriptorImpl
val containerDescriptor = when (componentManager) {
is Application -> pluginDescriptor.appContainerDescriptor
is Project -> pluginDescriptor.projectContainerDescriptor
else -> pluginDescriptor.moduleContainerDescriptor
}
containerDescriptor.services.forEach {
if ((componentManager as? ComponentManagerImpl)?.isServiceSuitable(it) != false &&
(it.os == null || componentManager.isSuitableForOs(it.os))) {
consumer(it)
}
}
}
}
fun createSimpleMessageBusOwner(owner: String): MessageBusOwner {
return object : MessageBusOwner {
override fun createListener(descriptor: ListenerDescriptor) = throw UnsupportedOperationException()
override fun isDisposed() = false
override fun toString() = owner
}
} | apache-2.0 | 0f0f9030e3fc59c425348d38616a7343 | 41.736842 | 156 | 0.796346 | 5.154497 | false | true | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertExtensionToFunctionTypeFix.kt | 2 | 2896 | // 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.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isExtensionFunctionType
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
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.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class ConvertExtensionToFunctionTypeFix(element: KtTypeReference, type: KotlinType) : KotlinQuickFixAction<KtTypeReference>(element) {
private val targetTypeStringShort = type.renderType(IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS)
private val targetTypeStringLong = type.renderType(IdeDescriptorRenderers.SOURCE_CODE)
override fun getText() = KotlinBundle.message("convert.supertype.to.0", targetTypeStringShort)
override fun getFamilyName() = KotlinBundle.message("convert.extension.function.type.to.regular.function.type")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val replaced = element.replaced(KtPsiFactory(project).createType(targetTypeStringLong))
ShortenReferences.DEFAULT.process(replaced)
}
private fun KotlinType.renderType(renderer: DescriptorRenderer) = buildString {
append('(')
arguments.dropLast(1).joinTo(this@buildString, ", ") { renderer.renderType(it.type) }
append(") -> ")
append(renderer.renderType([email protected]()))
}
companion object Factory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val casted = Errors.SUPERTYPE_IS_EXTENSION_FUNCTION_TYPE.cast(diagnostic)
val element = casted.psiElement
val type = element.analyze(BodyResolveMode.PARTIAL).get(BindingContext.TYPE, element) ?: return emptyList()
if (!type.isExtensionFunctionType) return emptyList()
return listOf(ConvertExtensionToFunctionTypeFix(element, type))
}
}
}
| apache-2.0 | 7cdaa13583a86524987a0674233baf5f | 49.807018 | 158 | 0.783494 | 4.755337 | false | false | false | false |
lcmatrix/betting-game | src/test/kotlin/de/bettinggame/application/TeamTests.kt | 1 | 4207 | package de.bettinggame.application
import de.bettinggame.domain.*
import org.junit.Before
import org.junit.runner.RunWith
import org.mockito.BDDMockito.given
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import java.time.OffsetDateTime
import java.util.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@RunWith(MockitoJUnitRunner::class)
class TeamServiceTest {
@Mock
lateinit var teamRepository: TeamRepository
@Mock
lateinit var gameRepository: GameRepository
lateinit var teamService: TeamService
val teamOneId = "1"
val teamTwoId = "2"
val teamThreeId = "3"
val teamGermany = Team(teamOneId, Multilingual("Deutschland", "Germany"), "DE", Group.F)
val teamFrance = Team(teamTwoId, Multilingual("Frankreich", "France"), "FR", Group.H)
val teamMexico = Team(teamThreeId, Multilingual("Mexiko", "Mexico"), "MX", Group.F)
@Before
fun setUp() {
val games = createGamesForTeams()
given(teamRepository.findAllByGroupCharNotNull()).willReturn(listOf(teamGermany, teamFrance, teamMexico))
given(gameRepository.findByTeamInPreliminaryLevel(teamGermany)).willReturn(games)
given(gameRepository.findByTeamInPreliminaryLevel(teamMexico)).willReturn(games)
teamService = TeamService(teamRepository, gameRepository)
}
@Test
fun testGetAllGroupsWithTeams() {
val allGroupsWithTeams = teamService.getAllGroupsWithTeams()
assertEquals(2, allGroupsWithTeams.size, "2 groups expected")
val iterator = allGroupsWithTeams.iterator()
val groupF = iterator.next()
assertEquals(Group.F.name, groupF.groupChar)
assertEquals(2, groupF.teams.size)
assertEquals(teamGermany.teamKey, groupF.teams[0].teamKey)
val germany = groupF.teams[0]
assertEquals(4, germany.points)
assertEquals(4, germany.goals)
assertEquals(1, germany.goalsAgainst)
val mexico = groupF.teams[1]
assertEquals(1, mexico.points)
assertEquals(1, mexico.goals)
assertEquals(4, mexico.goalsAgainst)
assertEquals(teamMexico.teamKey, groupF.teams[1].teamKey)
val groupH = iterator.next()
assertEquals(Group.H.name, groupH.groupChar)
assertEquals(1, groupH.teams.size)
assertEquals(teamFrance.teamKey, groupH.teams[0].teamKey)
}
@Test
fun testTeamToCompare() {
// compare points
val team1 = TeamTo("team1", "t1", 3, 5, 2)
val team2 = TeamTo("team2", "t2", 4, 6, 1)
assertTrue { team1.compareTo(team2) > 0 }
// compare goal difference
val team3 = TeamTo("team3", "t3", 3, 5, 2)
val team4 = TeamTo("team4", "t4", 3, 6, 1)
assertTrue { team3.compareTo(team4) > 0 }
// compare scored goals
val team5 = TeamTo("team5", "t5", 3, 7, 2)
val team6 = TeamTo("team6", "t6", 3, 6, 3)
assertTrue { team5.compareTo(team6) < 0 }
val team7 = TeamTo("team7", "t7", 3, 6, 3)
val team8 = TeamTo("team8", "t8", 3, 6, 3)
assertTrue { team7.compareTo(team8) == 0 }
}
private fun createGamesForTeams(): List<Game> {
return listOf(
Game(
UUID.randomUUID().toString(),
OffsetDateTime.now(),
createLocation(),
TournamentLevel.PRELIMINARY,
teamGermany,
teamMexico,
3,
0
),
Game(
UUID.randomUUID().toString(),
OffsetDateTime.now(),
createLocation(),
TournamentLevel.PRELIMINARY,
teamMexico,
teamGermany,
1,
1
),
)
}
private fun createLocation(): Location {
return Location(UUID.randomUUID().toString(), "x", Multilingual("location", "location"), Multilingual("Stadt", "city"),
Multilingual("land", "country"))
}
}
| apache-2.0 | 2efa12b8ddd1e900a16274e1dbda5b9b | 33.768595 | 127 | 0.598526 | 4.319302 | false | true | false | false |
blindpirate/gradle | subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/NamedDomainObjectContainerExtensionsTest.kt | 3 | 9350 | package org.gradle.kotlin.dsl
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.NamedDomainObjectProvider
import org.gradle.api.PolymorphicDomainObjectContainer
import org.gradle.api.Task
import org.gradle.api.tasks.Delete
import org.gradle.api.tasks.Exec
import org.gradle.api.tasks.TaskContainer
import org.gradle.kotlin.dsl.support.uncheckedCast
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.sameInstance
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class NamedDomainObjectContainerExtensionsTest {
data class DomainObject(var foo: String? = null, var bar: Boolean? = null)
@Test
fun `can use monomorphic container api`() {
val alice = DomainObject()
val bob = DomainObject()
val john = DomainObject()
val marty = mockDomainObjectProviderFor(DomainObject())
val doc = mockDomainObjectProviderFor(DomainObject())
val container = mock<NamedDomainObjectContainer<DomainObject>> {
on { getByName("alice") } doReturn alice
on { create("bob") } doReturn bob
on { maybeCreate("john") } doReturn john
on { named("marty") } doReturn marty
on { register("doc") } doReturn doc
on { getByName(eq("alice"), any<Action<DomainObject>>()) } doReturn alice
on { create(eq("bob"), any<Action<DomainObject>>()) } doReturn bob
}
// regular syntax
container.getByName("alice") {
foo = "alice-foo"
}
container.create("bob") {
foo = "bob-foo"
}
container.maybeCreate("john")
container.named("marty")
container.register("doc")
// invoke syntax
container {
getByName("alice") {
foo = "alice-foo"
}
create("bob") {
foo = "bob-foo"
}
maybeCreate("john")
named("marty")
register("doc")
}
}
@Test
fun `can use polymorphic container api`() {
val alice = DomainObjectBase.Foo()
val bob = DomainObjectBase.Bar()
val default = DomainObjectBase.Default()
val marty = DomainObjectBase.Foo()
val martyProvider = mockDomainObjectProviderFor(marty)
val doc = DomainObjectBase.Bar()
val docProvider = mockDomainObjectProviderFor<DomainObjectBase>(doc)
val docProviderAsBarProvider = uncheckedCast<NamedDomainObjectProvider<DomainObjectBase.Bar>>(docProvider)
val container = mock<PolymorphicDomainObjectContainer<DomainObjectBase>> {
on { getByName("alice") } doReturn alice
on { maybeCreate("alice", DomainObjectBase.Foo::class.java) } doReturn alice
on { create(eq("bob"), eq(DomainObjectBase.Bar::class.java), any<Action<DomainObjectBase.Bar>>()) } doReturn bob
on { create("john") } doReturn default
on { create("john", DomainObjectBase.Default::class.java) } doReturn default
onNamedWithAction("marty", DomainObjectBase.Foo::class, martyProvider)
on { register(eq("doc"), eq(DomainObjectBase.Bar::class.java)) } doReturn docProviderAsBarProvider
onRegisterWithAction("doc", DomainObjectBase.Bar::class, docProviderAsBarProvider)
}
// regular syntax
container.getByName<DomainObjectBase.Foo>("alice") {
foo = "alice-foo-2"
}
container.maybeCreate<DomainObjectBase.Foo>("alice")
container.create<DomainObjectBase.Bar>("bob") {
bar = true
}
container.create("john")
container.named("marty", DomainObjectBase.Foo::class) {
foo = "marty-foo"
}
container.named<DomainObjectBase.Foo>("marty") {
foo = "marty-foo-2"
}
container.register<DomainObjectBase.Bar>("doc") {
bar = true
}
// invoke syntax
container {
getByName<DomainObjectBase.Foo>("alice") {
foo = "alice-foo-2"
}
maybeCreate<DomainObjectBase.Foo>("alice")
create<DomainObjectBase.Bar>("bob") {
bar = true
}
create("john")
named("marty", DomainObjectBase.Foo::class) {
foo = "marty-foo"
}
named<DomainObjectBase.Foo>("marty") {
foo = "marty-foo-2"
}
register<DomainObjectBase.Bar>("doc") {
bar = true
}
}
}
@Test
fun `can configure monomorphic container`() {
val alice = DomainObject()
val aliceProvider = mockDomainObjectProviderFor(alice)
val bob = DomainObject()
val bobProvider = mockDomainObjectProviderFor(bob)
val container = mock<NamedDomainObjectContainer<DomainObject>> {
on { named("alice") } doReturn aliceProvider
on { named("bob") } doReturn bobProvider
}
container {
"alice" {
foo = "alice-foo"
}
"alice" {
// will configure the same object as the previous block
bar = true
}
"bob" {
foo = "bob-foo"
bar = false
}
}
assertThat(
alice,
equalTo(DomainObject("alice-foo", true))
)
assertThat(
bob,
equalTo(DomainObject("bob-foo", false))
)
}
sealed class DomainObjectBase {
data class Foo(var foo: String? = null) : DomainObjectBase()
data class Bar(var bar: Boolean? = null) : DomainObjectBase()
data class Default(val isDefault: Boolean = true) : DomainObjectBase()
}
@Test
fun `can configure polymorphic container`() {
val alice = DomainObjectBase.Foo()
val aliceProvider = mockDomainObjectProviderFor(alice)
val bob = DomainObjectBase.Bar()
val bobProvider = mockDomainObjectProviderFor(bob)
val default: DomainObjectBase = DomainObjectBase.Default()
val defaultProvider = mockDomainObjectProviderFor(default)
val container = mock<PolymorphicDomainObjectContainer<DomainObjectBase>> {
onNamedWithAction("alice", DomainObjectBase.Foo::class, aliceProvider)
on { named(eq("bob"), eq(DomainObjectBase.Bar::class.java)) } doReturn bobProvider
on { named(eq("jim")) } doReturn defaultProvider
on { named(eq("steve")) } doReturn defaultProvider
}
container {
val a = "alice"(DomainObjectBase.Foo::class) {
foo = "foo"
}
val b = "bob"(type = DomainObjectBase.Bar::class)
val j = "jim" {}
val s = "steve"() // can invoke without a block, but must invoke
assertThat(a.get(), sameInstance(alice))
assertThat(b.get(), sameInstance(bob))
assertThat(j.get(), sameInstance(default))
assertThat(s.get(), sameInstance(default))
}
assertThat(
alice,
equalTo(DomainObjectBase.Foo("foo"))
)
assertThat(
bob,
equalTo(DomainObjectBase.Bar())
)
}
@Test
fun `can create and configure tasks`() {
val clean = mock<Delete>()
val cleanProvider = mockTaskProviderFor(clean)
val tasks = mock<TaskContainer> {
on { create(eq("clean"), eq(Delete::class.java), any<Action<Delete>>()) } doReturn clean
on { getByName("clean") } doReturn clean
onNamedWithAction("clean", Delete::class, cleanProvider)
}
tasks {
create<Delete>("clean") {
delete("some")
}
getByName<Delete>("clean") {
delete("stuff")
}
"clean"(type = Delete::class) {
delete("things")
}
}
tasks.getByName<Delete>("clean") {
delete("build")
}
inOrder(clean) {
verify(clean).delete("stuff")
verify(clean).delete("things")
verify(clean).delete("build")
}
}
@Test
fun `can create element within configuration block via delegated property`() {
val tasks = mock<TaskContainer> {
on { create("hello") } doReturn mock<Task>()
}
tasks {
@Suppress("unused_variable")
val hello by creating
}
verify(tasks).create("hello")
}
@Test
fun `can get element of specific type within configuration block via delegated property`() {
val task = mock<Exec>()
val tasks = mock<TaskContainer> {
on { getByName("hello") } doReturn task
}
@Suppress("unused_variable")
tasks {
val hello by getting(Exec::class)
}
verify(tasks).getByName("hello")
}
}
| apache-2.0 | 1b4610bf4d7790c2053f97add4817ab2 | 31.241379 | 124 | 0.576257 | 5.065005 | false | false | false | false |
blindpirate/gradle | build-logic/basics/src/main/kotlin/gradlebuild/basics/classanalysis/AnalyzeAndShade.kt | 1 | 6281 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 gradlebuild.basics.classanalysis
import org.gradle.api.attributes.Attribute
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.commons.ClassRemapper
import org.objectweb.asm.commons.Remapper
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.net.URI
import java.nio.file.FileSystems
import java.nio.file.FileVisitResult
import java.nio.file.FileVisitor
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import java.util.zip.ZipEntry
private
val ignoredPackagePatterns = PackagePatterns(setOf("java"))
object Attributes {
val artifactType = Attribute.of("artifactType", String::class.java)
val minified = Attribute.of("minified", Boolean::class.javaObjectType)
}
class JarAnalyzer(
private val shadowPackage: String,
private val keepPackages: Set<String>,
private val unshadedPackages: Set<String>,
private val ignorePackages: Set<String>
) {
fun analyze(jarFile: File, classesDir: File, manifestFile: File, buildReceipt: File): ClassGraph {
val classGraph = classGraph()
val jarUri = URI.create("jar:${jarFile.toPath().toUri()}")
FileSystems.newFileSystem(jarUri, emptyMap<String, Any>()).use { jarFileSystem ->
jarFileSystem.rootDirectories.forEach {
visitClassDirectory(it, classGraph, classesDir, manifestFile.toPath(), buildReceipt.toPath())
}
}
return classGraph
}
private
fun classGraph() =
ClassGraph(
PackagePatterns(keepPackages),
PackagePatterns(unshadedPackages),
PackagePatterns(ignorePackages),
shadowPackage
)
private
fun visitClassDirectory(dir: Path, classes: ClassGraph, classesDir: File, manifest: Path, buildReceipt: Path) {
Files.walkFileTree(
dir,
object : FileVisitor<Path> {
private
var seenManifest: Boolean = false
override fun preVisitDirectory(dir: Path?, attrs: BasicFileAttributes?) =
FileVisitResult.CONTINUE
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
when {
file.isClassFilePath() -> {
visitClassFile(file)
}
file.isBuildReceipt() -> {
Files.copy(file, buildReceipt)
}
file.isUnseenManifestFilePath() -> {
seenManifest = true
Files.copy(file, manifest)
}
}
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path?, exc: IOException?) =
FileVisitResult.TERMINATE
override fun postVisitDirectory(dir: Path?, exc: IOException?) =
FileVisitResult.CONTINUE
private
fun Path.isClassFilePath() =
toString().endsWith(".class")
private
fun Path.isBuildReceipt() =
toString() == "/org/gradle/build-receipt.properties"
private
fun Path.isUnseenManifestFilePath() =
toString() == "/${JarFile.MANIFEST_NAME}" && !seenManifest
private
fun visitClassFile(file: Path) {
try {
val reader = ClassReader(Files.newInputStream(file))
val details = classes[reader.className]
details.visited = true
val classWriter = ClassWriter(0)
reader.accept(
ClassRemapper(
classWriter,
object : Remapper() {
override fun map(name: String): String {
if (ignoredPackagePatterns.matches(name)) {
return name
}
val dependencyDetails = classes[name]
if (dependencyDetails !== details) {
details.dependencies.add(dependencyDetails)
}
return dependencyDetails.outputClassName
}
}
),
ClassReader.EXPAND_FRAMES
)
classesDir.resolve(details.outputClassFilename).apply {
parentFile.mkdirs()
writeBytes(classWriter.toByteArray())
}
} catch (exception: Exception) {
throw ClassAnalysisException("Could not transform class from ${file.toFile()}", exception)
}
}
}
)
}
}
fun JarOutputStream.addJarEntry(entryName: String, sourceFile: File) {
putNextEntry(ZipEntry(entryName))
BufferedInputStream(FileInputStream(sourceFile)).use { inputStream -> inputStream.copyTo(this) }
closeEntry()
}
| apache-2.0 | 78ddb7fe9e32f73e0b35a1b76a37d9e2 | 36.386905 | 115 | 0.551505 | 5.746569 | false | false | false | false |
nearbydelta/KoreanAnalyzer | core/src/main/kotlin/kr/bydelta/koala/types.kt | 1 | 26070 | @file:JvmName("Util")
package kr.bydelta.koala
/**
* 세종 품사표기 표준안을 Enum Class로 담았습니다.
*
* @since 1.x
*/
enum class POS {
/** ([NOUNS]: 체언) ''일반명사'': 일반 개념을 표시하는 명사. **/
NNG,
/** ([NOUNS]: 체언) ''고유명사'' : 낱낱의 특정한 사물이나 사람을 다른 것들과 구별하여 부르기 위하여 고유의 기호를 붙인 이름. **/
NNP,
/** ([NOUNS]: 체언) ''일반 의존명사'' : 의미가 형식적이어서 다른 말 아래에 기대어 쓰이는 명사.
*
* ‘것1’, ‘따름1’, ‘뿐1’, ‘데1’ 따위가 있다.
* */
NNB,
/** ([NOUNS]: 체언) ''단위성 의존명사'' : 수효나 분량 따위의 단위를 나타내는 의존 명사.
*
* ‘쌀 한 말, 쇠고기 한 근, 굴비 한 두름, 북어 한 쾌, 고무신 한 켤레, 광목 한 필’에서 ‘말3’, ‘근3’, ‘두름1’, ‘쾌1’, ‘켤레2’, ‘필2’
* */
NNM,
/** ([NOUNS]: 체언) ''수사'' : 사물의 수량이나 순서를 나타내는 품사. 양수사와 서수사가 있다. **/
NR,
/** ([NOUNS]: 체언) ''대명사'' : 사람이나 사물의 이름을 대신 나타내는 말. 또는 그런 말들을 지칭하는 품사 **/
NP,
/** ([PREDICATES]: 용언) ''동사'' : 사물의 동작이나 작용을 나타내는 품사. **/
VV,
/** ([PREDICATES]: 용언) ''형용사'' : 사물의 성질이나 상태를 나타내는 품사. **/
VA,
/** ([PREDICATES]: 용언) ''보조용언'' : 본용언과 연결되어 그것의 뜻을 보충하는 역할을 하는 용언. 보조 동사, 보조 형용사가 있다.
*
* ‘ 가지고 싶다’의 ‘싶다’, ‘먹어 보다’의 ‘보다1’ 따위이다.
* */
VX,
/** ([PREDICATES]: 용언) ''긍정지정사(이다)'': 무엇이 무엇이라고 지정하는 단어. (이다) **/
VCP,
/** ([PREDICATES]: 용언) ''부정지정사(아니다)'': 무엇이 무엇이 아니라고 지정하는 단어. (아니다) **/
VCN,
/** ([MODIFIERS]: 수식언) ''관형사'' : 체언 앞에 놓여서, 그 체언의 내용을 자세히 꾸며 주는 품사. **/
MM,
/** ([MODIFIERS]: 수식언) ''부사'' : 용언 또는 다른 말 앞에 놓여 그 뜻을 분명하게 하는 품사. **/
MAG,
/** ([MODIFIERS]: 수식언) ''접속부사'' : 앞의 체언이나 문장의 뜻을 뒤의 체언이나 문장에 이어 주면서 뒤의 말을 꾸며 주는 부사.
*
* ‘ 그러나’, ‘그런데’, ‘그리고’, ‘하지만’ 따위가 있다.
* */
MAJ,
/** (독립언) ''감탄사'' : 말하는 이의 본능적인 놀람이나 느낌, 부름, 응답 따위를 나타내는 말의 부류이다. **/
IC,
/** ([POSTPOSITIONS]: 관계언) ''주격 조사'' : 문장 안에서, 체언이 서술어의 주어임을 표시하는 격 조사.
*
* ‘이/가’, ‘께서’, ‘에서2’ 따위가 있다.
* */
JKS,
/** ([POSTPOSITIONS]: 관계언) ''보격 조사'' : 문장 안에서, 체언이 보어임을 표시하는 격 조사.
*
* ‘철수는 위대한 학자가 되었다.’에서의 ‘가11’, ‘그는 보통 인물이 아니다.’에서의 ‘이27’ 따위이다.
* */
JKC,
/** ([POSTPOSITIONS]: 관계언) ''관형격 조사'' : 문장 안에서, 앞에 오는 체언이 뒤에 오는 체언의 관형어임을 보이는 조사. **/
JKG,
/** ([POSTPOSITIONS]: 관계언) ''목적격 조사'' : 문장 안에서, 체언이 서술어의 목적어임을 표시하는 격 조사. ‘을/를’이 있다. **/
JKO,
/** ([POSTPOSITIONS]: 관계언) ''부사격 조사'' : 문장 안에서, 체언이 부사어임을 보이는 조사.
*
* ‘ 에4’, ‘에서2’, ‘(으)로’, ‘와/과’, ‘보다4’ 따위가 있다. **/
JKB,
/** ([POSTPOSITIONS]: 관계언) ''호격 조사'' :
* 문장 안에서, 체언이 부름의 자리에 놓이게 하여 독립어가 되게 하는 조사.
*
* ‘영숙아’의 ‘아9’, ‘철수야’의 ‘야12’ 따위가 있다. **/
JKV,
/** ([POSTPOSITIONS]: 관계언) ''인용격 조사'': 앞의 말이 인용됨을 나타내는 조사. **/
JKQ,
/** ([POSTPOSITIONS]: 관계언) ''접속 조사'' : 둘 이상의 단어나 구 따위를 같은 자격으로 이어 주는 구실을 하는 조사.
*
* ‘와4’, ‘과12’, ‘하고5’, ‘(이)나’, ‘(이)랑’ 따위가 있다. **/
JC,
/** ([POSTPOSITIONS]: 관계언) ''보조사'' : 체언, 부사, 활용 어미 따위에 붙어서 어떤 특별한 의미를 더해 주는 조사.
*
* ‘은5’, ‘는1’, ‘도15’, ‘만14’, ‘까지3’, ‘마저’, ‘조차8’, ‘부터’ 따위가 있다.
* */
JX,
/** ([ENDINGS]: 어미) ''선어말 어미'' : 어말 어미 앞에 나타나는 어미.
*
* * ‘-시-23’, ‘-옵-1’ 따위와 같이 높임법에 관한 것과
* * ‘-았-’, ‘-는-2’, ‘-더-2’, ‘-겠-’ 따위와 같이 시상(時相)에 관한 것이 있다.
* */
EP,
/** ([ENDINGS]: 어미) ''종결 어미'' : 한 문장을 종결되게 하는 어말 어미.
*
* * 동사에는 평서형ㆍ감탄형ㆍ의문형ㆍ명령형ㆍ청유형이 있고,
* * 형용사에는 평서형ㆍ감탄형ㆍ의문형이 있다.
* */
EF,
/** ([ENDINGS]: 어미) ''연결 어미'' 어간에 붙어 다음 말에 연결하는 구실을 하는 어미.
*
* ‘-게10’, ‘-고25’, ‘-(으)며’, ‘-(으)면’, ‘-(으)니’, ‘-아/어’, ‘-지23’ 따위가 있다.
* */
EC,
/** ([ENDINGS]: 어미) ''명사형 전성어미'': 용언의 어간에 붙어 명사의 기능을 수행하게 하는 어미. **/
ETN,
/** ([ENDINGS]: 어미) ''관형형 전성어미'': 용언의 어간에 붙어 관형사의 기능을 수행하게 하는 어미. **/
ETM,
/** ([AFFIXES]: 접사) ''체언 접두사'' : 파생어를 만드는 접사로, 어근이나 단어의 앞에 붙어 새로운 단어가 되게 하는 말. **/
XPN,
/** ([AFFIXES]: 접사) ''용언 접두사'' : 파생어를 만드는 접사로, 어근이나 단어의 앞에 붙어 새로운 단어가 되게 하는 말. **/
XPV,
/** ([AFFIXES]: 접사) ''명사 파생 접미사'':
* 파생어를 만드는 접사로, 어근이나 단어의 뒤에 붙어 새로운 명사가 되게 하는 말.
* */
XSN,
/** ([AFFIXES]: 접사) ''동사 파생 접미사'':
* 파생어를 만드는 접사로, 어근이나 단어의 뒤에 붙어 새로운 동사가 되게 하는 말.
* */
XSV,
/** ([AFFIXES]: 접사) ''형용사 파생 접미사'':
* 파생어를 만드는 접사로, 어근이나 단어의 뒤에 붙어 새로운 형용사가 되게 하는 말.
* */
XSA,
/** ([AFFIXES]: 접사) ''부사 파생 접미사'':
* 파생어를 만드는 접사로, 어근이나 단어의 뒤에 붙어 새로운 부사가 되게 하는 말.
* */
XSM,
/** ([AFFIXES]: 접사) ''기타 접미사'':
* 파생어를 만드는 접사로, 어근이나 단어의 뒤에 붙어 새로운 단어가 되게 하는 말.
* */
XSO,
/** ''어근'' :
* 단어를 분석할 때, 실질적 의미를 나타내는 중심이 되는 부분.
*
* ‘덮개’의 ‘덮-’, ‘어른스럽다’의 ‘어른1’ 따위이다.
* */
XR,
/** ([SYMBOLS]: 기호) 종결기호: 마침/물음/느낌표 **/
SF,
/** ([SYMBOLS]: 기호) 연결기호: 쉼표/가운뎃점/빗금 **/
SP,
/** ([SYMBOLS]: 기호) 묶음기호: 괄호/묶음표/따옴표 **/
SS,
/** ([SYMBOLS]: 기호) 생략기호: 줄임표 **/
SE,
/** ([SYMBOLS]: 기호) 붙임기호: 물결표/줄임표/빠짐표 **/
SO,
/** ([SYMBOLS]: 기호) 기타기호 **/
SW,
/** 명사 추정 범주 **/
NF,
/** 동사 추정 범주 **/
NV,
/** 분석 불능 범주 **/
NA,
/** 외국어 **/
SL,
/** 한자 **/
SH,
/** 숫자 **/
SN,
/** 임시기호(내부처리용) **/
TEMP;
/**
* Static variables
*/
companion object {
/** 전체 **/
@JvmStatic
val ALL = values().toSet()
/** 체언 **/
@JvmStatic
val NOUNS = setOf(NNG, NNP, NNB, NNM, NR, NP)
/** 용언 **/
@JvmStatic
val PREDICATES = setOf(VV, VA, VX, VCP, VCN)
/** 수식언 **/
@JvmStatic
val MODIFIERS = setOf(MM, MAG, MAJ)
/** 관계언(조사) **/
@JvmStatic
val POSTPOSITIONS = setOf(JKS, JKC, JKG, JKO, JKB, JKV, JKQ, JC, JX)
/** 어미 **/
@JvmStatic
val ENDINGS = setOf(EP, EF, EC, ETN, ETM)
/** 접사 **/
@JvmStatic
val AFFIXES = setOf(XPN, XPV, XSN, XSV, XSM, XSA, XSO)
/** 접미사 **/
@JvmStatic
val SUFFIXES = setOf(XSN, XSV, XSM, XSA, XSO)
/** 기호 **/
@JvmStatic
val SYMBOLS = setOf(SF, SP, SS, SE, SW, SO)
/** 미확인 단어 **/
@JvmStatic
val UNKNOWNS = setOf(NF, NV, NA)
}
/**
* 이 값이 체언([NOUNS])인지 확인합니다.
*
* @since 1.x
* @return 체언인 경우 True
*/
fun isNoun(): Boolean = this in NOUNS
/**
* 이 값이 용언([PREDICATES])인지 확인합니다.
*
* @since 1.x
* @return 용언인 경우 True
*/
fun isPredicate(): Boolean = this in PREDICATES
/**
* 이 값이 수식언([MODIFIERS])인지 확인합니다.
*
* @since 1.x
* @return 수식언인 경우 True
*/
fun isModifier(): Boolean = this in MODIFIERS
/**
* 이 값이 관계언(조사; [POSTPOSITIONS])인지 확인합니다.
*
* @since 1.x
* @return 관계언인 경우 True
*/
fun isPostPosition(): Boolean = this in POSTPOSITIONS
/**
* 이 값이 어미([ENDINGS])인지 확인합니다.
*
* @since 1.x
* @return 어미인 경우 True
*/
fun isEnding(): Boolean = this in ENDINGS
/**
* 이 값이 접사([AFFIXES])인지 확인합니다.
*
* @since 1.x
* @return 접사인 경우 True
*/
fun isAffix(): Boolean = this in AFFIXES
/**
* 이 값이 접미사([SUFFIXES])인지 확인합니다.
*
* @since 1.x
* @return 접미사인 경우 True
*/
fun isSuffix(): Boolean = this in SUFFIXES
/**
* 이 값이 기호([SYMBOLS])인지 확인합니다.
*
* @since 1.x
* @return 기호인 경우 True
*/
fun isSymbol(): Boolean = this in SYMBOLS
/**
* 이 값이 미확인 단어([UNKNOWNS])인지 확인합니다.
*
* @since 1.x
* @return 미확인 단어인 경우 True
*/
fun isUnknown(): Boolean = this in UNKNOWNS
/**
* 이 값이 주어진 [tag]로 시작하는지 확인합니다.
*
* @since 2.0.0
* @return 그러한 경우 True
*/
fun startsWith(tag: CharSequence): Boolean {
val xtag = tag.toString().toUpperCase()
return if (xtag == "N") name.startsWith(xtag) && !isUnknown() else name.startsWith(xtag)
}
}
/**
* 전체 형태소의 개수
*/
internal inline val POS_SIZE get() = POS.values().size
/**
* (Extension) 이 String 값에 주어진 [tag]가 포함되는지 확인합니다.
*
* ## 사용법
* ### Kotlin
* ```kotlin
* POS.NN in "N"
* \\ 또는
* "N".contains(POS.NN)
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* POS.NN in "N"
* \\ 또는
* "N".contains(POS.NN)
* ```
*
* ### Java
* ```java
* Util.contains("N", POS.NN)
* ```
*
* @since 2.0.0
* @param[tag] 하위 분류인지 확인할 형태소 품사표기 값
* @return 하위 분류에 해당한다면 true
*/
operator fun CharSequence.contains(tag: POS): Boolean = tag.startsWith(this)
/*************************************************************/
/**
* 세종 구문구조 표지자를 Enum class로 담았습니다.
*
* @since 2.0.0
*/
enum class PhraseTag {
/**
* 구문구조 표지자: 문장
*/
S,
/**
* 구문구조 표지자: 체언 구
*
* 문장에서 주어 따위의 기능을 하는 명사, 대명사, 수사 또는 이 역할을 하는 구
*/
NP,
/**
* 구문구조 표지자: 용언 구
*
* 문장에서 서술어의 기능을 하는 동사, 형용사 또는 이 역할을 하는 구
*/
VP,
/**
* 구문구조 표지자: 긍정지정사구
*
* 무엇이 무엇이라고 지정하는 단어(이다) 또는 이 역할을 하는 구
*/
VNP,
/**
* 구문구조 표지자: 부사구
*
* 용언구 또는 다른 말 앞에 놓여 그 뜻을 분명하게 하는 단어 또는 이 역할을 하는 구
*/
AP,
/**
* 구문구조 표지자: 관형사구
*
* 체언구 앞에 놓여서, 그 체언구의 내용을 자세히 꾸며 주는 단어 또는 이 역할을 하는 구
*/
DP,
/**
* 구문구조 표지자: 감탄사구
*
* 말하는 이의 본능적인 놀람이나 느낌, 부름, 응답 따위를 나타내는 단어 또는 이 역할을 하는 구
*/
IP,
/**
* 구문구조 표지자: 의사(Pseudo) 구
*
* 인용부호와 괄호를 제외한 나머지 부호나, 조사, 어미가 단독으로 어절을 이룰 때 (즉, 구를 보통 이루지 않는 것이 구를 이루는 경우)
*/
X,
/**
* 구문구조 표지자: 왼쪽 인용부호
*
* 열림 인용부호
*/
L,
/**
* 구문구조 표지자: 오른쪽 인용부호
*
* 닫힘 인용부호
*/
R,
/**
* 구문구조 표지자: 인용절
*
* 인용 부호 내부에 있는 인용된 절. 세종 표지에서는 Q, U, W, Y, Z가 사용되나 KoalaNLP에서는 하나로 통일함.
*/
Q
}
/**
* (Extension) 주어진 목록에 주어진 구문구조 표지 [tag]가 포함되는지 확인합니다.
*
* ## 사용법
* ### Kotlin
* ```kotlin
* PhraseTag.NP in listOf("S", "NP")
* \\ 또는
* listOf("S", "NP").contains(PhraseTag.NP)
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* PhraseTag.NP in Seq("S", "NP")
* \\ 또는
* Seq("S", "NP").contains(PhraseTag.NP)
* ```
*
* ### Java
* ```java
* List<String> list = new LinkedList()
* list.add("S")
* list.add("NP")
* Util.contains(list, PhraseTag.NP)
* ```
*
* @since 2.0.0
* @param[tag] 속하는지 확인할 구문구조 표지 값
* @return 목록 중 하나라도 일치한다면 true
*/
operator fun Iterable<String>.contains(tag: PhraseTag): Boolean = this.any { it == tag.name }
/********************************************************/
/**
* 의존구문구조 기능표지자를 담은 Enum class입니다.
* (ETRI 표준안)
*
* [참고](http://aiopen.etri.re.kr/data/1.%20%EC%9D%98%EC%A1%B4%20%EA%B5%AC%EB%AC%B8%EB%B6%84%EC%84%9D%EC%9D%84%20%EC%9C%84%ED%95%9C%20%ED%95%9C%EA%B5%AD%EC%96%B4%20%EC%9D%98%EC%A1%B4%EA%B4%80%EA%B3%84%20%EA%B0%80%EC%9D%B4%EB%93%9C%EB%9D%BC%EC%9D%B8%20%EB%B0%8F%20%EC%97%91%EC%86%8C%EB%B8%8C%EB%A0%88%EC%9D%B8%20%EC%96%B8%EC%96%B4%EB%B6%84%EC%84%9D%20%EB%A7%90%EB%AD%89%EC%B9%98.pdf)
*
* @since 1.x
*/
enum class DependencyTag {
/** ''주어'': 술어가 나타내는 동작이나 상태의 주체가 되는 말
*
* 주격 체언구(NP_SBJ), 명사 전성 용언구(VP_SBJ), 명사절(S_SBJ) */
SBJ,
/** ''목적어'': 타동사가 쓰인 문장에서 동작의 대상이 되는 말
*
* 목적격 체언구(NP_OBJ), 명사 전성 용언구(VP_OBJ), 명사절(S_OBJ) */
OBJ,
/** ''보어'': 주어와 서술어만으로는 뜻이 완전하지 못한 문장에서, 그 불완전한 곳을 보충하여 뜻을 완전하게 하는 수식어.
*
* 보격 체언구(NP_CMP), 명사 전성 용언구(VP_CMP), 인용절(S_CMP) */
CMP,
/** 체언 수식어(관형격). 관형격 체언구(NP_MOD), 관형형 용언구(VP_MOD), 관형절(S_MOD) */
MOD,
/** 용언 수식어(부사격). 부사격 체언구(NP_AJT), 부사격 용언구(VP_AJT) 문말어미+부사격 조사(S_AJT) */
AJT,
/** ''접속어'': 단어와 단어, 구절과 구절, 문장과 문장을 이어 주는 구실을 하는 문장 성분.
*
* 접속격 체언(NP_CNJ) */
CNJ,
/** 삽입어구 */
PRN,
/** 정의되지 않음 */
UNDEF,
/** ROOT 지시자 */
ROOT
}
/**
* (Extension) 주어진 목록에 주어진 의존구문 표지 [tag]가 포함되는지 확인.
*
* ## 사용법
* ### Kotlin
* ```kotlin
* DependencyTag.SBJ in listOf("SBJ", "MOD")
* \\ 또는
* listOf("SBJ", "MOD").contains(DependencyTag.SBJ)
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* DependencyTag.SBJ in Seq("SBJ", "MOD")
* \\ 또는
* Seq("SBJ", "MOD").contains(DependencyTag.SBJ)
* ```
*
* ### Java
* ```java
* List<String> list = new LinkedList()
* list.add("SBJ")
* list.add("MOD")
* Util.contains(list, DependencyTag.SBJ)
* ```
*
* @since 2.0.0
* @param[tag] 속하는지 확인할 의존구조 표지 값
* @return 목록 중 하나라도 일치한다면 true
*/
operator fun Iterable<String>.contains(tag: DependencyTag): Boolean = this.any { it == tag.name }
/************************************************************/
/**
* 의미역(Semantic Role) 분석 표지를 담은 Enum class입니다.
* (ETRI 표준안)
*
* @since 2.0.0
*/
enum class RoleType {
/**
* (필수격) **행동주, 경험자.** 술어로 기술된 행동을 하거나 경험한 대상.
*
* 예: {"진흥왕은" 화랑도를 개편했다.}에서 _<진흥왕은>_, {"쑨원은" 삼민주의를 내세웠다.}에서 _<쑨원은>_
*/
ARG0,
/**
* (필수격) **피동작주, 대상.** 술어로 기술된 행동을 당한 대상 (주로 목적격, 피동작 대상). '이동'에 관한 행동에 의해서 위치의 변화가 되거나, '생성/소멸' 사건의 결과로 존재가 변화하는 대상.
*
* 예: {진흥왕은 "화랑도를" 개편했다.}에서 _<화랑도를>_, {"범인은" 사거리에서 발견되었다.}에서 _<범인은>_, {밤거리에는 "인적이" 드물다.}에서 _<인적이>_.
*/
ARG1,
/**
* (필수격) **시작점, 수혜자, 결과.** 술어로 기술된 행동의 시작점, 행동으로 인해 수혜를 받는 대상, 행동을 기술하기 위해 필요한 장소.
*
* 예: {영희가 "철수에게서" 그 선물을 받았다.}에서 _<철수에게서>_.
*/
ARG2,
/**
* (필수격) **착점.** 술어로 기술된 행동의 도착점.
*
* 예: {연이가 "동창회에" 참석했다.}에서 _<동창회에>_. {근이가 "학교에" 갔다.}에서 _<학교에>_.
*/
ARG3,
/**
* (부가격) **장소.** 술어로 기술된 행동이 발생하는 공간. 주로 술어가 '이동'이 아닌 상태를 나타내고, '~에(서)' 조사와 함께 쓰이는 경우.
*
* 예: {친구들이 "서울에" 많이 산다.}에서 _<서울에>_.
*/
ARGM_LOC,
/**
* (부가격) **방향.** 술어가 '이동' 상태를 나타낼 때, '~(으)로' 조사와 함께 쓰이는 경우.
*
* 예: {달이 "서쪽으로" 기울었다.}에서 _<서쪽으로>_. */
ARGM_DIR,
/**
* (부가격) **조건.** 술어의 행동이 발생되는 조건이나 인물, 사물 따위의 자격을 나타내는 경우. 주로 '~중에', '~가운데에', '~보다', '~에 대해'
*
* 예: {"과세 대상 금액이 많을수록" 높은 세율을 적용한다.}에서 _<많을수록>_. */
ARGM_CND,
/**
* (부가격) **방법.** 술어의 행동을 수행하는 방법. 또는 술어가 특정 언어에 의한 것을 나타낼 때, 그 언어. (구체적인 사물이 등장하는 경우는 [ARGM_INS] 참고)
*
* 예: {그는 "큰 소리로" 떠들었다.}에서 _<소리로>_. */
ARGM_MNR,
/**
* (부가격) **시간.** 술어의 행동이 발생한 시간 등과 같이 술어와 관련된 시간. 명확한 날짜, 시기, 시대를 지칭하는 경우.
*
* 단, 기간의 범위를 나타내는 경우, 즉 ~에서 ~까지의 경우는 시점([ARG2])과 착점([ARG3])으로 분석함.
*
* 예: {진달래는 "이른 봄에" 핀다.}에서 _<봄에>_. */
ARGM_TMP,
/**
* (부가격) **범위.** 크기 또는 높이 등의 수치나 정도를 논하는 경우. '가장', '최고', '매우', '더욱' 등을 나타내는 경우.
*
* 예: {그 악기는 "4개의" 현을 가진다.}에서 _<4개의>_. */
ARGM_EXT,
/**
* (부가격) **보조서술.** 대상과 같은 의미이거나 대상의 상태를 나타내면서 술어를 수식하는 것. 주로 '~로서'. 또는 '최초로'와 같이 술어의 정해진 순서를 나타내는 경우.
*
* 예: {석회암 지대에서 "깔대기 모양으로" 파인 웅덩이가 생겼다.}에서 _<모양으로>_. */
ARGM_PRD,
/**
* (부가격) **목적.** 술어의 주체가 가진 목표. 또는 행위의 의도. 주로 '~를 위해'. 발생 이유([ARGM_CAU])와 유사함에 주의.
*
* 예: {주나라의 백이와 숙제는 "절개를 지키고자" 수양산에 거처했다.}에서 _<지키고자>_. */
ARGM_PRP,
/**
* (부가격) **발생 이유.** 술어가 발생한 이유. '~때문에'를 대신할 수 있는 조사가 붙은 경우. 목적([ARGM_PRP])과 혼동되나, 목적은 아닌 것.
*
* 예: {지난 밤 "강풍으로" 가로수가 넘어졌다.}에서 _<강풍으로>_. */
ARGM_CAU,
/**
* (부가격) **담화 연결.** 문장 접속 부사. (그러나, 그리고, 즉 등.)
*
* 예: {"하지만" 여기서 동, 서는 중국과 유럽을 뜻한다.}에서 _<하지만>_. */
ARGM_DIS,
/**
* (부가격) **부사적 어구.** ('마치', '물론', '역시' 등)
*
* 예: {산의 능선이 "마치" 닭벼슬을 쓴 용의 형상을 닮았다.}에서 _<마치>_. */
ARGM_ADV,
/**
* (부가격) **부정.** 술어에 부정의 의미를 더하는 경우.
*
* 예: {산은 불에 타지 "않았다."}에서 _<않았다.>_. */
ARGM_NEG,
/**
* (부가격) **도구.** 술어의 행동을 할 때 사용되는 도구. 방법([ARGM_MNR])보다 구체적인 사물이 등장할 때.
*
* 예: {"하얀 천으로" 상자를 덮었다.}에서 _<천으로>_. */
ARGM_INS
}
/**
* (Extension) 주어진 목록에 주어진 의미역 표지 [tag]가 포함되는지 확인합니다.
*
* ## 사용법
* ### Kotlin
* ```kotlin
* RoleType.ARG0 in listOf("ARG0", "ARGM_LOC")
* \\ 또는
* listOf("ARG0", "ARGM_LOC").contains(RoleType.ARG0)
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* RoleType.ARG0 in Seq("ARG0", "ARGM_LOC")
* \\ 또는
* Seq("ARG0", "ARGM_LOC").contains(RoleType.ARG0)
* ```
*
* ### Java
* ```java
* List<String> list = new LinkedList()
* list.add("ARG0")
* list.add("ARGM_LOC")
* Util.contains(list, RoleType.ARG0)
* ```
*
* @since 2.0.0
* @param[tag] 속하는지 확인할 의미역 표지 값
* @return 목록 중 하나라도 일치한다면 true
*/
operator fun Iterable<String>.contains(tag: RoleType): Boolean = this.any { it == tag.name }
/************************************************************/
/**
* 대분류 개체명(Named Entity) 유형을 담은 Enum class입니다.
* (ETRI 표준안)
*
* @since 2.0.0
*/
enum class CoarseEntityType {
/**
* 사람의 이름
*/
PS,
/**
* 장소의 이름
*/
LC,
/**
* 단체의 이름
*/
OG,
/**
* 작품/물품의 이름
*/
AF,
/**
* 기간/날짜의 이름
*/
DT,
/**
* 시간/간격의 이름
*/
TI,
/**
* 문명/문화활동에 사용되는 명칭
*/
CV,
/**
* 동물의 이름
*/
AM,
/**
* 식물의 이름
*/
PT,
/**
* 수량의 값, 서수 또는 이름
*/
QT,
/**
* 학문분야 또는 학파, 예술사조 등의 이름
*/
FD,
/**
* 이론, 법칙, 원리 등의 이름
*/
TR,
/**
* 사회적 활동, 운동, 사건 등의 이름
*/
EV,
/**
* 화학적 구성물의 이름
*/
MT,
/**
* 용어
*/
TM
}
/**
* (Extension) 주어진 목록에 주어진 개체명 유형 [tag]가 포함되는지 확인합니다.
*
* ## 사용법
* ### Kotlin
* ```kotlin
* CoarseEntityType.PL in listOf("PS", "PL")
* \\ 또는
* listOf("PS", "PL").contains(CoarseEntityType.PL)
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support/)
* ```scala
* import kr.bydelta.koala.Implicits._
* CoarseEntityType.PL in Seq("PS", "PL")
* \\ 또는
* Seq("PS", "PL").contains(CoarseEntityType.PL)
* ```
*
* ### Java
* ```java
* List<String> list = new LinkedList()
* list.add("PS")
* list.add("PL")
* Util.contains(list, CoarseEntityType.PL)
* ```
*
* @since 2.0.0
* @param[tag] 속하는지 확인할 개체명 표지 값
* @return 목록 중 하나라도 일치한다면 true
*/
operator fun Iterable<String>.contains(tag: CoarseEntityType): Boolean = this.any { it == tag.name }
| gpl-3.0 | 2a32fdb5f597eec972d13533a991c71c | 22.037711 | 381 | 0.475277 | 2.28299 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/reader/discover/interests/ReaderInterestsViewModel.kt | 1 | 14857 | package org.wordpress.android.ui.reader.discover.interests
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker
import org.wordpress.android.models.ReaderTag
import org.wordpress.android.models.ReaderTagList
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsFragment.EntryPoint
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.DoneButtonUiState.DoneButtonDisabledUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.DoneButtonUiState.DoneButtonEnabledUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.DoneButtonUiState.DoneButtonHiddenUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.UiState.ContentUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.UiState.ErrorUiState.ConnectionErrorUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.UiState.ErrorUiState.RequestFailedErrorUiState
import org.wordpress.android.ui.reader.discover.interests.ReaderInterestsViewModel.UiState.InitialLoadingUiState
import org.wordpress.android.ui.reader.repository.ReaderRepositoryCommunication
import org.wordpress.android.ui.reader.repository.ReaderTagRepository
import org.wordpress.android.ui.reader.tracker.ReaderTracker
import org.wordpress.android.ui.reader.viewmodels.ReaderViewModel
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.viewmodel.Event
import javax.inject.Inject
class ReaderInterestsViewModel @Inject constructor(
private val readerTagRepository: ReaderTagRepository,
private val readerTracker: ReaderTracker
) : ViewModel() {
private var isStarted = false
private lateinit var currentLanguage: String
private var parentViewModel: ReaderViewModel? = null
private var entryPoint = EntryPoint.DISCOVER
private var userTags = ReaderTagList()
private val _uiState: MutableLiveData<UiState> = MutableLiveData()
val uiState: LiveData<UiState> = _uiState
private val _snackbarEvents = MediatorLiveData<Event<SnackbarMessageHolder>>()
val snackbarEvents: LiveData<Event<SnackbarMessageHolder>> = _snackbarEvents
private val _closeReaderInterests = MutableLiveData<Event<Unit>>()
val closeReaderInterests: LiveData<Event<Unit>> = _closeReaderInterests
private var userTagsFetchedSuccessfully = false
fun start(
currentLanguage: String,
parentViewModel: ReaderViewModel?,
entryPoint: EntryPoint
) {
if (isStarted && this.currentLanguage == currentLanguage) {
return
}
isStarted = true
this.currentLanguage = currentLanguage
this.parentViewModel = parentViewModel
this.entryPoint = entryPoint
parentViewModel?.dismissQuickStartSnackbarIfNeeded()
loadUserTags()
}
private fun loadUserTags() {
updateUiState(InitialLoadingUiState)
viewModelScope.launch {
when (val result = readerTagRepository.getUserTags()) {
is ReaderRepositoryCommunication.SuccessWithData<*> -> {
userTagsFetchedSuccessfully = true
userTags = result.data as ReaderTagList
when (entryPoint) {
EntryPoint.DISCOVER -> checkAndLoadInterests(userTags)
EntryPoint.SETTINGS -> loadInterests(userTags)
}
}
is ReaderRepositoryCommunication.Error -> {
if (result is ReaderRepositoryCommunication.Error.NetworkUnavailable) {
updateUiState(ConnectionErrorUiState)
} else if (result is ReaderRepositoryCommunication.Error.RemoteRequestFailure) {
updateUiState(RequestFailedErrorUiState)
}
}
ReaderRepositoryCommunication.Started -> Unit // Do nothing
ReaderRepositoryCommunication.Success -> Unit // Do nothing
}
}
}
private fun checkAndLoadInterests(userTags: ReaderTagList) {
if (userTags.isEmpty()) {
loadInterests(userTags)
} else {
parentViewModel?.onCloseReaderInterests()
}
}
private fun loadInterests(userTags: ReaderTagList) {
updateUiState(InitialLoadingUiState)
viewModelScope.launch {
val newUiState: UiState? = when (val result = readerTagRepository.getInterests()) {
is ReaderRepositoryCommunication.SuccessWithData<*> -> {
readerTracker.track(AnalyticsTracker.Stat.SELECT_INTERESTS_SHOWN)
val tags = (result.data as ReaderTagList).filter { checkAndExcludeTag(userTags, it) }
val distinctTags = ReaderTagList().apply { addAll(tags.distinctBy { it.tagSlug }) }
when (entryPoint) {
EntryPoint.DISCOVER -> ContentUiState(
interestsUiState = transformToInterestsUiState(distinctTags),
interests = distinctTags,
doneButtonUiState = DoneButtonDisabledUiState(),
titleVisible = true
)
EntryPoint.SETTINGS -> ContentUiState(
interestsUiState = transformToInterestsUiState(distinctTags),
interests = distinctTags,
doneButtonUiState = DoneButtonDisabledUiState(R.string.reader_btn_done),
titleVisible = false
)
}
}
is ReaderRepositoryCommunication.Error.NetworkUnavailable -> {
ConnectionErrorUiState
}
is ReaderRepositoryCommunication.Error.RemoteRequestFailure -> {
RequestFailedErrorUiState
}
else -> {
null
}
}
newUiState?.let {
updateUiState(it)
}
}
}
private fun checkAndExcludeTag(userTags: ReaderTagList, tag: ReaderTag): Boolean {
var contain = false
userTags.forEach { excludedTag ->
if (excludedTag.tagSlug.equals(tag.tagSlug)) {
contain = true
return@forEach
}
}
return !contain
}
fun onInterestAtIndexToggled(index: Int, isChecked: Boolean) {
uiState.value?.let {
val currentUiState = uiState.value as ContentUiState
val updatedInterestsUiState = getUpdatedInterestsUiState(index, isChecked)
updateUiState(
currentUiState.copy(
interestsUiState = updatedInterestsUiState,
doneButtonUiState = currentUiState.getDoneButtonState(
entryPoint = entryPoint,
isInterestChecked = isChecked
)
)
)
parentViewModel?.completeQuickStartFollowSiteTaskIfNeeded()
}
}
fun onDoneButtonClick() {
val contentUiState = uiState.value as ContentUiState
updateUiState(
contentUiState.copy(
progressBarVisible = true,
doneButtonUiState = DoneButtonDisabledUiState(R.string.reader_btn_done)
)
)
trackInterests(contentUiState.getSelectedInterests())
viewModelScope.launch {
readerTagRepository.clearTagLastUpdated(ReaderTag.createDiscoverPostCardsTag())
when (val result = readerTagRepository.saveInterests(contentUiState.getSelectedInterests())) {
is ReaderRepositoryCommunication.Success -> {
when (entryPoint) {
EntryPoint.DISCOVER -> parentViewModel?.onCloseReaderInterests()
EntryPoint.SETTINGS -> _closeReaderInterests.value = Event(Unit)
}
}
is ReaderRepositoryCommunication.Error -> {
if (result is ReaderRepositoryCommunication.Error.NetworkUnavailable) {
_snackbarEvents.postValue(
Event(SnackbarMessageHolder(UiStringRes(R.string.no_network_message)))
)
} else if (result is ReaderRepositoryCommunication.Error.RemoteRequestFailure) {
_snackbarEvents.postValue(
Event(SnackbarMessageHolder(UiStringRes(R.string.reader_error_request_failed_title)))
)
}
updateUiState(
contentUiState.copy(
progressBarVisible = false,
doneButtonUiState = DoneButtonEnabledUiState(R.string.reader_btn_done)
)
)
}
is ReaderRepositoryCommunication.Started -> Unit // Do nothing
is ReaderRepositoryCommunication.SuccessWithData<*> -> Unit // Do nothing
}
}
}
fun onRetryButtonClick() {
if (!userTagsFetchedSuccessfully) {
loadUserTags()
} else {
loadInterests(userTags)
}
}
private fun transformToInterestsUiState(interests: ReaderTagList) =
interests.map { interest ->
TagUiState(interest.tagTitle, interest.tagSlug)
}
private fun getUpdatedInterestsUiState(index: Int, isChecked: Boolean): List<TagUiState> {
val currentUiState = uiState.value as ContentUiState
val newInterestsUiState = currentUiState.interestsUiState.toMutableList()
newInterestsUiState[index] = currentUiState.interestsUiState[index].copy(isChecked = isChecked)
return newInterestsUiState
}
private fun updateUiState(uiState: UiState) {
_uiState.value = uiState
}
private fun trackInterests(tags: List<ReaderTag>) {
tags.forEach {
val source = when (entryPoint) {
EntryPoint.DISCOVER -> ReaderTracker.SOURCE_DISCOVER
EntryPoint.SETTINGS -> ReaderTracker.SOURCE_SETTINGS
}
readerTracker.trackTag(
AnalyticsTracker.Stat.READER_TAG_FOLLOWED,
it.tagSlug,
source
)
}
readerTracker.trackTagQuantity(AnalyticsTracker.Stat.SELECT_INTERESTS_PICKED, tags.size)
}
fun onBackButtonClick() {
when (entryPoint) {
EntryPoint.DISCOVER -> parentViewModel?.onCloseReaderInterests()
EntryPoint.SETTINGS -> _closeReaderInterests.value = Event(Unit)
}
}
sealed class UiState(
open val doneButtonUiState: DoneButtonUiState = DoneButtonHiddenUiState,
open val progressBarVisible: Boolean = false,
open val titleVisible: Boolean = false,
val errorLayoutVisible: Boolean = false
) {
object InitialLoadingUiState : UiState(
progressBarVisible = true
)
data class ContentUiState(
val interestsUiState: List<TagUiState>,
val interests: ReaderTagList,
override val progressBarVisible: Boolean = false,
override val doneButtonUiState: DoneButtonUiState,
override val titleVisible: Boolean
) : UiState(
progressBarVisible = false,
titleVisible = titleVisible,
errorLayoutVisible = false
)
sealed class ErrorUiState constructor(
val titleRes: Int
) : UiState(
progressBarVisible = false,
errorLayoutVisible = true
) {
object ConnectionErrorUiState : ErrorUiState(R.string.no_network_message)
object RequestFailedErrorUiState : ErrorUiState(R.string.reader_error_request_failed_title)
}
private fun getCheckedInterestsUiState(): List<TagUiState> {
return if (this is ContentUiState) {
interestsUiState.filter { it.isChecked }
} else {
emptyList()
}
}
fun getSelectedInterests(): List<ReaderTag> {
return if (this is ContentUiState) {
interests.filter {
getCheckedInterestsUiState().map { checkedInterestUiState ->
checkedInterestUiState.slug
}.contains(it.tagSlug)
}
} else {
emptyList()
}
}
fun getDoneButtonState(
entryPoint: EntryPoint,
isInterestChecked: Boolean = false
): DoneButtonUiState {
return if (this is ContentUiState) {
val disableDoneButton = interests.isEmpty() ||
(getCheckedInterestsUiState().size == 1 && !isInterestChecked)
if (disableDoneButton) {
when (entryPoint) {
EntryPoint.DISCOVER -> DoneButtonDisabledUiState()
EntryPoint.SETTINGS -> DoneButtonDisabledUiState(R.string.reader_btn_done)
}
} else {
DoneButtonEnabledUiState()
}
} else {
DoneButtonHiddenUiState
}
}
}
sealed class DoneButtonUiState(
@StringRes open val titleRes: Int = R.string.reader_btn_done,
val enabled: Boolean = false,
val visible: Boolean = true
) {
data class DoneButtonEnabledUiState(
@StringRes override val titleRes: Int = R.string.reader_btn_done
) : DoneButtonUiState(
enabled = true
)
data class DoneButtonDisabledUiState(
@StringRes override val titleRes: Int = R.string.reader_btn_select_few_interests
) : DoneButtonUiState(
enabled = false
)
object DoneButtonHiddenUiState : DoneButtonUiState(
visible = false
)
}
}
| gpl-2.0 | 8fd0b2caeecec016ccb27b535990e63e | 40.5 | 129 | 0.608804 | 6.268776 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/photopicker/MediaPickerLauncher.kt | 1 | 12836 | package org.wordpress.android.ui.photopicker
import android.app.Activity
import android.content.Intent
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.RequestCodes
import org.wordpress.android.ui.media.MediaBrowserType
import org.wordpress.android.ui.media.MediaBrowserType.FEATURED_IMAGE_PICKER
import org.wordpress.android.ui.media.MediaBrowserType.WP_STORIES_MEDIA_PICKER
import org.wordpress.android.ui.mediapicker.MediaPickerActivity
import org.wordpress.android.ui.mediapicker.MediaPickerSetup
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.CameraSetup.ENABLED
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.CameraSetup.HIDDEN
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.CameraSetup.STORIES
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.DataSource.DEVICE
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.DataSource.GIF_LIBRARY
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.DataSource.STOCK_LIBRARY
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.DataSource.WP_LIBRARY
import org.wordpress.android.ui.mediapicker.MediaType
import org.wordpress.android.ui.mediapicker.MediaType.AUDIO
import org.wordpress.android.ui.mediapicker.MediaType.DOCUMENT
import org.wordpress.android.ui.mediapicker.MediaType.IMAGE
import org.wordpress.android.ui.mediapicker.MediaType.VIDEO
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import javax.inject.Inject
class MediaPickerLauncher @Inject constructor(
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper
) {
fun showFeaturedImagePicker(
activity: Activity,
site: SiteModel?,
localPostId: Int
) {
val availableDataSources = if (site != null && site.isUsingWpComRestApi) {
setOf(WP_LIBRARY, STOCK_LIBRARY, GIF_LIBRARY)
} else {
setOf(WP_LIBRARY, GIF_LIBRARY)
}
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = DEVICE,
availableDataSources = availableDataSources,
canMultiselect = false,
requiresStoragePermissions = true,
allowedTypes = setOf(IMAGE),
cameraSetup = ENABLED,
systemPickerEnabled = true,
editingEnabled = true,
queueResults = true,
defaultSearchView = false,
title = R.string.photo_picker_title
)
val intent = MediaPickerActivity.buildIntent(
activity,
mediaPickerSetup,
site,
localPostId
)
activity.startActivityForResult(intent, RequestCodes.PHOTO_PICKER)
}
fun showSiteIconPicker(
activity: Activity,
site: SiteModel?
) {
val intent = buildSitePickerIntent(activity, site)
activity.startActivityForResult(intent, RequestCodes.PHOTO_PICKER)
}
@Suppress("DEPRECATION")
fun showSiteIconPicker(
fragment: Fragment,
site: SiteModel?
) {
val intent = buildSitePickerIntent(fragment.requireActivity(), site)
fragment.startActivityForResult(intent, RequestCodes.SITE_ICON_PICKER)
}
private fun buildSitePickerIntent(
activity: Activity,
site: SiteModel?
): Intent {
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = DEVICE,
availableDataSources = setOf(WP_LIBRARY),
canMultiselect = false,
requiresStoragePermissions = true,
allowedTypes = setOf(IMAGE),
cameraSetup = ENABLED,
systemPickerEnabled = true,
editingEnabled = true,
queueResults = false,
defaultSearchView = false,
title = R.string.photo_picker_title
)
val intent = MediaPickerActivity.buildIntent(
activity,
mediaPickerSetup,
site,
null
)
return intent
}
fun showPhotoPickerForResult(
activity: Activity,
browserType: MediaBrowserType,
site: SiteModel?,
localPostId: Int?
) {
val intent = MediaPickerActivity.buildIntent(
activity,
buildLocalMediaPickerSetup(browserType),
site,
localPostId
)
activity.startActivityForResult(intent, RequestCodes.PHOTO_PICKER)
}
fun showStoriesPhotoPickerForResultAndTrack(activity: Activity, site: SiteModel?) {
analyticsTrackerWrapper.track(Stat.MEDIA_PICKER_OPEN_FOR_STORIES)
showStoriesPhotoPickerForResult(activity, site)
}
@Suppress("DEPRECATION")
fun showStoriesPhotoPickerForResult(
activity: Activity,
site: SiteModel?
) {
ActivityLauncher.showPhotoPickerForResult(activity, WP_STORIES_MEDIA_PICKER, site, null)
}
@Suppress("DEPRECATION")
fun showGravatarPicker(fragment: Fragment) {
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = DEVICE,
availableDataSources = setOf(),
canMultiselect = false,
requiresStoragePermissions = true,
allowedTypes = setOf(IMAGE),
cameraSetup = ENABLED,
systemPickerEnabled = true,
editingEnabled = true,
queueResults = false,
defaultSearchView = false,
title = R.string.photo_picker_title
)
val intent = MediaPickerActivity.buildIntent(
fragment.requireContext(),
mediaPickerSetup
)
fragment.startActivityForResult(intent, RequestCodes.PHOTO_PICKER)
}
fun showFilePicker(activity: Activity, canMultiselect: Boolean = true, site: SiteModel) {
showFilePicker(
activity,
site,
canMultiselect,
mutableSetOf(IMAGE, VIDEO, AUDIO, DOCUMENT),
RequestCodes.FILE_LIBRARY,
R.string.photo_picker_choose_file
)
}
fun showAudioFilePicker(activity: Activity, canMultiselect: Boolean = false, site: SiteModel) {
showFilePicker(
activity,
site,
canMultiselect,
mutableSetOf(AUDIO),
RequestCodes.AUDIO_LIBRARY,
R.string.photo_picker_choose_audio
)
}
private fun showFilePicker(
activity: Activity,
site: SiteModel,
canMultiselect: Boolean = false,
allowedTypes: Set<MediaType>,
requestCode: Int,
@StringRes title: Int
) {
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = DEVICE,
availableDataSources = setOf(),
canMultiselect = canMultiselect,
requiresStoragePermissions = true,
allowedTypes = allowedTypes,
cameraSetup = HIDDEN,
systemPickerEnabled = true,
editingEnabled = true,
queueResults = false,
defaultSearchView = false,
title = title
)
val intent = MediaPickerActivity.buildIntent(
activity,
mediaPickerSetup,
site
)
activity.startActivityForResult(
intent,
requestCode
)
}
fun viewWPMediaLibraryPickerForResult(activity: Activity, site: SiteModel, browserType: MediaBrowserType) {
val intent = MediaPickerActivity.buildIntent(
activity,
buildWPMediaLibraryPickerSetup(browserType),
site
)
val requestCode: Int = if (browserType.canMultiselect()) {
RequestCodes.MULTI_SELECT_MEDIA_PICKER
} else {
RequestCodes.SINGLE_SELECT_MEDIA_PICKER
}
activity.startActivityForResult(intent, requestCode)
}
fun showStockMediaPickerForResult(
activity: Activity,
site: SiteModel,
requestCode: Int,
allowMultipleSelection: Boolean
) {
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = STOCK_LIBRARY,
availableDataSources = setOf(),
canMultiselect = allowMultipleSelection,
requiresStoragePermissions = false,
allowedTypes = setOf(IMAGE),
cameraSetup = HIDDEN,
systemPickerEnabled = false,
editingEnabled = false,
queueResults = false,
defaultSearchView = true,
title = R.string.photo_picker_stock_media
)
val intent = MediaPickerActivity.buildIntent(
activity,
mediaPickerSetup,
site
)
activity.startActivityForResult(intent, requestCode)
}
fun showGifPickerForResult(
activity: Activity,
site: SiteModel,
allowMultipleSelection: Boolean
) {
val requestCode = if (allowMultipleSelection) {
RequestCodes.GIF_PICKER_MULTI_SELECT
} else {
RequestCodes.GIF_PICKER_SINGLE_SELECT
}
val mediaPickerSetup = MediaPickerSetup(
primaryDataSource = GIF_LIBRARY,
availableDataSources = setOf(),
canMultiselect = allowMultipleSelection,
requiresStoragePermissions = false,
allowedTypes = setOf(IMAGE),
cameraSetup = HIDDEN,
systemPickerEnabled = false,
editingEnabled = false,
queueResults = false,
defaultSearchView = true,
title = R.string.photo_picker_gif
)
val intent = MediaPickerActivity.buildIntent(
activity,
mediaPickerSetup,
site
)
activity.startActivityForResult(intent, requestCode)
}
private fun buildLocalMediaPickerSetup(browserType: MediaBrowserType): MediaPickerSetup {
val allowedTypes = mutableSetOf<MediaType>()
if (browserType.isImagePicker) {
allowedTypes.add(IMAGE)
}
if (browserType.isVideoPicker) {
allowedTypes.add(VIDEO)
}
val title = if (browserType.isImagePicker && browserType.isVideoPicker) {
R.string.photo_picker_photo_or_video_title
} else if (browserType.isVideoPicker) {
R.string.photo_picker_video_title
} else {
R.string.photo_picker_title
}
return MediaPickerSetup(
primaryDataSource = DEVICE,
availableDataSources = if (browserType.isWPStoriesPicker) setOf(WP_LIBRARY) else setOf(),
canMultiselect = browserType.canMultiselect(),
requiresStoragePermissions = true,
allowedTypes = allowedTypes,
cameraSetup = if (browserType.isWPStoriesPicker) STORIES else HIDDEN,
systemPickerEnabled = true,
editingEnabled = browserType.isImagePicker,
queueResults = browserType == FEATURED_IMAGE_PICKER,
defaultSearchView = false,
title = title
)
}
private fun buildWPMediaLibraryPickerSetup(browserType: MediaBrowserType): MediaPickerSetup {
val allowedTypes = mutableSetOf<MediaType>()
if (browserType.isImagePicker) {
allowedTypes.add(IMAGE)
}
if (browserType.isVideoPicker) {
allowedTypes.add(VIDEO)
}
if (browserType.isAudioPicker) {
allowedTypes.add(AUDIO)
}
if (browserType.isDocumentPicker) {
allowedTypes.add(DOCUMENT)
}
return MediaPickerSetup(
primaryDataSource = WP_LIBRARY,
availableDataSources = setOf(),
canMultiselect = browserType.canMultiselect(),
requiresStoragePermissions = false,
allowedTypes = allowedTypes,
cameraSetup = if (browserType.isWPStoriesPicker) STORIES else HIDDEN,
systemPickerEnabled = false,
editingEnabled = false,
queueResults = false,
defaultSearchView = false,
title = R.string.wp_media_title
)
}
}
| gpl-2.0 | 8003bd9b7e39027e998c767c1ef778c7 | 35.885057 | 111 | 0.612886 | 5.901609 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/entity/app/profile/UserHolder.kt | 1 | 7985 | package forpdateam.ru.forpda.entity.app.profile
import android.content.SharedPreferences
import com.jakewharton.rxrelay2.BehaviorRelay
import forpdateam.ru.forpda.common.Html
import forpdateam.ru.forpda.entity.EntityWrapper
import forpdateam.ru.forpda.entity.remote.profile.ProfileModel
import forpdateam.ru.forpda.extensions.nullString
import forpdateam.ru.forpda.model.data.remote.api.ApiUtils
import io.reactivex.Observable
import org.json.JSONArray
import org.json.JSONObject
class UserHolder(
private val sharedPreferences: SharedPreferences
) : IUserHolder {
private val currentUserRelay = BehaviorRelay.createDefault(EntityWrapper(user))
override var user: ProfileModel?
get() {
return sharedPreferences
.getString("current_user", null)
?.let {
val jsonProfile = JSONObject(it)
ProfileModel().apply {
id = jsonProfile.getInt("id")
sign = ApiUtils.coloredFromHtml(jsonProfile.nullString("sign"))
about = ApiUtils.spannedFromHtml(jsonProfile.nullString("about"))
avatar = jsonProfile.nullString("avatar")
nick = jsonProfile.nullString("nick")
status = jsonProfile.nullString("status")
group = jsonProfile.nullString("group")
note = jsonProfile.nullString("note")
jsonProfile.getJSONArray("contacts")?.also {
for (i in 0 until it.length()) {
val jsonContact = it.getJSONObject(i)
contacts.add(ProfileModel.Contact().apply {
type = ProfileModel.ContactType.valueOf(jsonContact.getString("type"))
url = jsonContact.nullString("url")
title = jsonContact.nullString("title")
})
}
}
jsonProfile.getJSONArray("info")?.also {
for (i in 0 until it.length()) {
val jsonInfo = it.getJSONObject(i)
info.add(ProfileModel.Info().apply {
type = ProfileModel.InfoType.valueOf(jsonInfo.getString("type"))
value = jsonInfo.nullString("value")
})
}
}
jsonProfile.getJSONArray("stats")?.also {
for (i in 0 until it.length()) {
val jsonStat = it.getJSONObject(i)
stats.add(ProfileModel.Stat().apply {
type = ProfileModel.StatType.valueOf(jsonStat.getString("type"))
url = jsonStat.nullString("url")
value = jsonStat.nullString("value")
})
}
}
jsonProfile.getJSONArray("devices")?.also {
for (i in 0 until it.length()) {
val jsonDevice = it.getJSONObject(i)
devices.add(ProfileModel.Device().apply {
url = jsonDevice.nullString("url")
name = jsonDevice.nullString("name")
accessory = jsonDevice.nullString("accessory")
})
}
}
jsonProfile.getJSONArray("warnings")?.also {
for (i in 0 until it.length()) {
val jsonContact = it.getJSONObject(i)
warnings.add(ProfileModel.Warning().apply {
type = ProfileModel.WarningType.valueOf(jsonContact.getString("type"))
date = jsonContact.nullString("date")
title = jsonContact.nullString("title")
content = ApiUtils.spannedFromHtml(jsonContact.nullString("content"))
})
}
}
}
}
}
set(value) {
currentUserRelay.accept(EntityWrapper(value))
val result = value?.let { profile ->
JSONObject().apply {
put("id", profile.id)
put("sign", profile.sign?.let { Html.toHtml(it) })
put("about", profile.about?.let { Html.toHtml(it) })
put("avatar", profile.avatar)
put("nick", profile.nick)
put("status", profile.status)
put("group", profile.group)
put("note", profile.note)
put("contacts", JSONArray().apply {
profile.contacts.forEach { contact ->
put(JSONObject().apply {
put("type", contact.type.toString())
put("url", contact.url)
put("title", contact.title)
})
}
})
put("info", JSONArray().apply {
profile.info.forEach { info ->
put(JSONObject().apply {
put("type", info.type.toString())
put("value", info.value)
})
}
})
put("stats", JSONArray().apply {
profile.stats.forEach { stat ->
put(JSONObject().apply {
put("type", stat.type.toString())
put("url", stat.url)
put("value", stat.value)
})
}
})
put("devices", JSONArray().apply {
profile.devices.forEach { device ->
put(JSONObject().apply {
put("url", device.url)
put("name", device.name)
put("accessory", device.accessory)
})
}
})
put("warnings", JSONArray().apply {
profile.warnings.forEach { warning ->
put(JSONObject().apply {
put("type", warning.type)
put("date", warning.date)
put("title", warning.title)
put("content", warning.content?.let { Html.toHtml(it) })
})
}
})
}
}
if (result == null) {
sharedPreferences.edit().remove("current_user").apply()
} else {
sharedPreferences.edit().putString("current_user", result.toString()).apply()
}
}
override fun observeCurrentUser(): Observable<EntityWrapper<ProfileModel?>> = currentUserRelay
}
| gpl-3.0 | 1e0f392b319089458583b910a7d122d2 | 47.393939 | 110 | 0.402379 | 6.670844 | false | false | false | false |
android/play-billing-samples | ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/data/network/SubRemoteDataSource.kt | 1 | 3505 | /*
* Copyright 2018 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.subscriptions.data.network
import com.example.subscriptions.data.SubscriptionStatus
import com.example.subscriptions.data.network.firebase.ServerFunctions
import kotlinx.coroutines.flow.StateFlow
/**
* Execute network requests on the network thread.
* Fetch data from a remote server object.
*/
class SubRemoteDataSource private constructor(
private val serverFunctions: ServerFunctions
) {
/**
* True when there are pending network requests.
*/
val loading: StateFlow<Boolean>
get() = serverFunctions.loading
/**
* Live Data with the basic content.
*/
val basicContent = serverFunctions.basicContent
/**
* Live Data with the premium content.
*/
val premiumContent = serverFunctions.premiumContent
/**
* GET basic content.
*/
suspend fun updateBasicContent() = serverFunctions.updateBasicContent()
/**
* GET premium content.
*/
suspend fun updatePremiumContent() = serverFunctions.updatePremiumContent()
/**
* GET request for subscription status.
*/
suspend fun fetchSubscriptionStatus() = serverFunctions.fetchSubscriptionStatus()
/**
* POST request to register subscription.
*/
suspend fun registerSubscription(
product: String,
purchaseToken: String
): List<SubscriptionStatus> {
return serverFunctions.registerSubscription(
product = product,
purchaseToken = purchaseToken
)
}
/**
* POST request to transfer a subscription that is owned by someone else.
*/
suspend fun postTransferSubscriptionSync(product: String, purchaseToken: String) {
serverFunctions.transferSubscription(product = product, purchaseToken = purchaseToken)
}
/**
* POST request to register an Instance ID.
*/
suspend fun postRegisterInstanceId(instanceId: String) {
serverFunctions.registerInstanceId(instanceId)
}
/**
* POST request to unregister an Instance ID.
*/
suspend fun postUnregisterInstanceId(instanceId: String) {
serverFunctions.unregisterInstanceId(instanceId)
}
/**
* POST request to acknowledge a subscription.
*/
suspend fun postAcknowledgeSubscription(
product: String,
purchaseToken: String
): List<SubscriptionStatus> {
return serverFunctions.acknowledgeSubscription(
product = product,
purchaseToken = purchaseToken
)
}
companion object {
@Volatile
private var INSTANCE: SubRemoteDataSource? = null
fun getInstance(
callableFunctions: ServerFunctions
): SubRemoteDataSource =
INSTANCE ?: synchronized(this) {
INSTANCE ?: SubRemoteDataSource(callableFunctions).also { INSTANCE = it }
}
}
}
| apache-2.0 | b36ba02df4ad1e33eb793c124955bd22 | 28.208333 | 94 | 0.676462 | 5.247006 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinBreadcrumbsInfoProvider.kt | 5 | 20069 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.psi.ElementDescriptionUtil
import com.intellij.psi.PsiElement
import com.intellij.refactoring.util.RefactoringDescriptionLocation
import com.intellij.ui.breadcrumbs.BreadcrumbsProvider
import com.intellij.usageView.UsageViewShortNameLocation
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.unwrapIfLabeled
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getCallNameExpression
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentsInParentheses
import kotlin.reflect.KClass
class KotlinBreadcrumbsInfoProvider : BreadcrumbsProvider {
override fun isShownByDefault(): Boolean = !UISettings.getInstance().showMembersInNavigationBar
private abstract class ElementHandler<TElement : KtElement>(val type: KClass<TElement>) {
abstract fun elementInfo(element: TElement): String
abstract fun elementTooltip(element: TElement): String
open fun accepts(element: TElement): Boolean = true
}
private object LambdaHandler : ElementHandler<KtFunctionLiteral>(KtFunctionLiteral::class) {
override fun elementInfo(element: KtFunctionLiteral): String {
val lambdaExpression = element.parent as KtLambdaExpression
val unwrapped = lambdaExpression.unwrapIfLabeled()
val label = lambdaExpression.labelText()
val lambdaText = "$label{$ellipsis}"
when (val parent = unwrapped.parent) {
is KtLambdaArgument -> {
val callExpression = parent.parent as? KtCallExpression
val callName = callExpression?.getCallNameExpression()?.getReferencedName()
if (callName != null) {
val receiverText = callExpression.getQualifiedExpressionForSelector()?.let {
it.receiverExpression.text.orEllipsis(TextKind.INFO) + it.operationSign.value
} ?: ""
return buildString {
append(receiverText)
append(callName)
if (callExpression.valueArgumentList != null) {
appendCallArguments(callExpression)
} else {
if (label.isNotEmpty()) append(" ")
}
append(lambdaText)
}
}
}
is KtProperty -> {
val name = parent.nameAsName
if (unwrapped == parent.initializer && name != null) {
val valOrVar = if (parent.isVar) "var" else "val"
return "$valOrVar ${name.render()} = $lambdaText"
}
}
}
return lambdaText
}
private fun StringBuilder.appendCallArguments(callExpression: KtCallExpression) {
var argumentText = "($ellipsis)"
val arguments = callExpression.getValueArgumentsInParentheses()
when (arguments.size) {
0 -> argumentText = "()"
1 -> {
val argument = arguments.single()
val argumentExpression = argument.getArgumentExpression()
if (!argument.isNamed() && argument.getSpreadElement() == null && argumentExpression != null) {
argumentText = "(" + argumentExpression.shortText(TextKind.INFO) + ")"
}
}
}
append(argumentText)
append(" ")
}
//TODO
override fun elementTooltip(element: KtFunctionLiteral): String {
return ElementDescriptionUtil.getElementDescription(element, RefactoringDescriptionLocation.WITH_PARENT)
}
}
private object AnonymousObjectHandler : ElementHandler<KtObjectDeclaration>(KtObjectDeclaration::class) {
override fun accepts(element: KtObjectDeclaration) = element.isObjectLiteral()
override fun elementInfo(element: KtObjectDeclaration) = element.buildText(TextKind.INFO)
override fun elementTooltip(element: KtObjectDeclaration) = element.buildText(TextKind.TOOLTIP)
private fun KtObjectDeclaration.buildText(kind: TextKind): String {
return buildString {
append("object")
val superTypeEntries = superTypeListEntries
if (superTypeEntries.isNotEmpty()) {
append(" : ")
if (kind == TextKind.INFO) {
val entry = superTypeEntries.first()
entry.typeReference?.text?.truncateStart(kind)?.let { append(it) }
if (superTypeEntries.size > 1) {
if (!endsWith(ellipsis)) {
append(",$ellipsis")
}
}
} else {
append(superTypeEntries.joinToString(separator = ", ") { it.typeReference?.text ?: "" }.truncateEnd(kind))
}
}
}
}
}
private object AnonymousFunctionHandler : ElementHandler<KtNamedFunction>(KtNamedFunction::class) {
override fun accepts(element: KtNamedFunction) = element.name == null
override fun elementInfo(element: KtNamedFunction) = element.buildText(TextKind.INFO)
override fun elementTooltip(element: KtNamedFunction) = element.buildText(TextKind.TOOLTIP)
private fun KtNamedFunction.buildText(kind: TextKind): String {
return "fun(" +
valueParameters.joinToString(separator = ", ") { if (kind == TextKind.INFO) it.name ?: "" else it.text }.truncateEnd(
kind
) +
")"
}
}
private object PropertyAccessorHandler : ElementHandler<KtPropertyAccessor>(KtPropertyAccessor::class) {
override fun elementInfo(element: KtPropertyAccessor): String {
return DeclarationHandler.elementInfo(element.property) + "." + (if (element.isGetter) "get" else "set")
}
override fun elementTooltip(element: KtPropertyAccessor): String {
return DeclarationHandler.elementTooltip(element)
}
}
private object DeclarationHandler : ElementHandler<KtDeclaration>(KtDeclaration::class) {
override fun accepts(element: KtDeclaration): Boolean {
if (element is KtProperty) {
return element.parent is KtFile || element.parent is KtClassBody // do not show local variables
}
return true
}
override fun elementInfo(element: KtDeclaration): String {
when {
element is KtProperty -> {
return (if (element.isVar) "var " else "val ") + element.nameAsName?.render()
}
element is KtObjectDeclaration && element.isCompanion() -> {
return buildString {
append("companion object")
element.nameIdentifier?.let { append(" "); append(it.text) }
}
}
else -> {
val description = ElementDescriptionUtil.getElementDescription(element, UsageViewShortNameLocation.INSTANCE)
val suffix = if (element is KtFunction) "()" else null
return if (suffix != null) description + suffix else description
}
}
}
override fun elementTooltip(element: KtDeclaration): String = try {
ElementDescriptionUtil.getElementDescription(element, RefactoringDescriptionLocation.WITH_PARENT)
} catch (e: IndexNotReadyException) {
KotlinBundle.message("breadcrumbs.tooltip.indexing")
}
}
private abstract class ConstructWithExpressionHandler<TElement : KtElement>(
private val constructName: String,
type: KClass<TElement>
) : ElementHandler<TElement>(type) {
protected abstract fun extractExpression(element: TElement): KtExpression?
protected abstract fun labelOwner(element: TElement): KtExpression?
override fun elementInfo(element: TElement) = element.buildText(TextKind.INFO)
override fun elementTooltip(element: TElement) = element.buildText(TextKind.TOOLTIP)
protected fun TElement.buildText(kind: TextKind): String {
return buildString {
append(labelOwner(this@buildText)?.labelText() ?: "")
append(constructName)
val expression = extractExpression(this@buildText)
if (expression != null) {
append(" (")
append(expression.shortText(kind))
append(")")
}
}
}
}
private object IfThenHandler : ConstructWithExpressionHandler<KtContainerNode>("if", KtContainerNode::class) {
override fun accepts(element: KtContainerNode): Boolean {
return element.node.elementType == KtNodeTypes.THEN
}
override fun extractExpression(element: KtContainerNode): KtExpression? {
return (element.parent as KtIfExpression).condition
}
override fun labelOwner(element: KtContainerNode): KtExpression? = null
override fun elementInfo(element: KtContainerNode): String {
return elseIfPrefix(element) + super.elementInfo(element)
}
override fun elementTooltip(element: KtContainerNode): String {
return elseIfPrefix(element) + super.elementTooltip(element)
}
private fun elseIfPrefix(then: KtContainerNode): String {
return if ((then.parent as KtIfExpression).isElseIf()) "if $ellipsis else " else ""
}
}
private object ElseHandler : ElementHandler<KtContainerNode>(KtContainerNode::class) {
override fun accepts(element: KtContainerNode): Boolean {
return element.node.elementType == KtNodeTypes.ELSE
&& (element.parent as KtIfExpression).`else` !is KtIfExpression // filter out "else if"
}
override fun elementInfo(element: KtContainerNode): String {
val ifExpression = element.parent as KtIfExpression
val then = ifExpression.thenNode
val ifInfo = if (ifExpression.isElseIf() || then == null) "if" else IfThenHandler.elementInfo(then)
return "$ifInfo $ellipsis else"
}
override fun elementTooltip(element: KtContainerNode): String {
val ifExpression = element.parent as KtIfExpression
val thenNode = ifExpression.thenNode ?: return "else"
return "else (of '" + IfThenHandler.elementTooltip(thenNode) + "')" //TODO
}
private val KtIfExpression.thenNode: KtContainerNode?
get() = children.firstOrNull { it.node.elementType == KtNodeTypes.THEN } as KtContainerNode?
}
private object TryHandler : ElementHandler<KtBlockExpression>(KtBlockExpression::class) {
override fun accepts(element: KtBlockExpression) = element.parent is KtTryExpression
override fun elementInfo(element: KtBlockExpression) = "try"
override fun elementTooltip(element: KtBlockExpression): String {
return buildString {
val tryExpression = element.parent as KtTryExpression
append("try {$ellipsis}")
for (catchClause in tryExpression.catchClauses) {
append("\ncatch(")
append(catchClause.catchParameter?.typeReference?.text ?: "")
append(") {$ellipsis}")
}
if (tryExpression.finallyBlock != null) {
append("\nfinally {$ellipsis}")
}
}
}
}
private object CatchHandler : ElementHandler<KtCatchClause>(KtCatchClause::class) {
override fun elementInfo(element: KtCatchClause): String {
val text = element.catchParameter?.typeReference?.text ?: ""
return "catch ($text)"
}
override fun elementTooltip(element: KtCatchClause): String {
return elementInfo(element)
}
}
private object FinallyHandler : ElementHandler<KtFinallySection>(KtFinallySection::class) {
override fun elementInfo(element: KtFinallySection) = "finally"
override fun elementTooltip(element: KtFinallySection) = "finally"
}
private object WhileHandler : ConstructWithExpressionHandler<KtContainerNode>("while", KtContainerNode::class) {
override fun accepts(element: KtContainerNode) = element.bodyOwner() is KtWhileExpression
override fun extractExpression(element: KtContainerNode) = (element.bodyOwner() as KtWhileExpression).condition
override fun labelOwner(element: KtContainerNode) = element.bodyOwner()
}
private object DoWhileHandler : ConstructWithExpressionHandler<KtContainerNode>("do $ellipsis while", KtContainerNode::class) {
override fun accepts(element: KtContainerNode) = element.bodyOwner() is KtDoWhileExpression
override fun extractExpression(element: KtContainerNode) = (element.bodyOwner() as KtDoWhileExpression).condition
override fun labelOwner(element: KtContainerNode) = element.bodyOwner()
}
private object WhenHandler : ConstructWithExpressionHandler<KtWhenExpression>("when", KtWhenExpression::class) {
override fun extractExpression(element: KtWhenExpression) = element.subjectExpression
override fun labelOwner(element: KtWhenExpression): KtExpression? = null
}
private object WhenEntryHandler : ElementHandler<KtExpression>(KtExpression::class) {
override fun accepts(element: KtExpression) = element.parent is KtWhenEntry
override fun elementInfo(element: KtExpression) = element.buildText(TextKind.INFO)
override fun elementTooltip(element: KtExpression) = element.buildText(TextKind.TOOLTIP)
private fun KtExpression.buildText(kind: TextKind): String {
with(parent as KtWhenEntry) {
if (isElse) {
return "else ->"
} else {
val condition = conditions.firstOrNull() ?: return "->"
val firstConditionText = condition.buildText(kind)
return if (conditions.size == 1) {
"$firstConditionText ->"
} else {
//TODO: show all conditions for tooltip
(if (firstConditionText.endsWith(ellipsis)) firstConditionText else "$firstConditionText,$ellipsis") + " ->"
}
}
}
}
private fun KtWhenCondition.buildText(kind: TextKind): String {
return when (this) {
is KtWhenConditionIsPattern -> {
(if (isNegated) "!is" else "is") + " " + (typeReference?.text?.truncateEnd(kind) ?: "")
}
is KtWhenConditionInRange -> {
(if (isNegated) "!in" else "in") + " " + (rangeExpression?.text?.truncateEnd(kind) ?: "")
}
is KtWhenConditionWithExpression -> {
expression?.text?.truncateStart(kind) ?: ""
}
else -> error("Unknown when entry condition type: ${this}")
}
}
}
private object ForHandler : ElementHandler<KtContainerNode>(KtContainerNode::class) {
override fun accepts(element: KtContainerNode) = element.bodyOwner() is KtForExpression
override fun elementInfo(element: KtContainerNode) = element.buildText(TextKind.INFO)
override fun elementTooltip(element: KtContainerNode) = element.buildText(TextKind.TOOLTIP)
private fun KtContainerNode.buildText(kind: TextKind): String {
with(bodyOwner() as KtForExpression) {
val parameterText = loopParameter?.nameAsName?.render() ?: destructuringDeclaration?.text ?: return "for"
val collectionText = loopRange?.text ?: ""
val text = ("$parameterText in $collectionText").truncateEnd(kind)
return labelText() + "for($text)"
}
}
}
@Suppress("UNCHECKED_CAST")
private fun handler(e: PsiElement): ElementHandler<in KtElement>? {
if (e !is KtElement) return null
val handler = Holder.handlers.firstOrNull { it.type.java.isInstance(e) && (it as ElementHandler<in KtElement>).accepts(e) }
return handler as ElementHandler<in KtElement>?
}
override fun getLanguages() = arrayOf(KotlinLanguage.INSTANCE)
override fun acceptElement(e: PsiElement) = !DumbService.isDumb(e.project) && handler(e) != null
override fun getElementInfo(e: PsiElement): String {
if (DumbService.isDumb(e.project)) return ""
return handler(e)!!.elementInfo(e as KtElement)
}
override fun getElementTooltip(e: PsiElement): String {
if (DumbService.isDumb(e.project)) return ""
return handler(e)!!.elementTooltip(e as KtElement)
}
override fun getParent(e: PsiElement): PsiElement? {
val node = e.node ?: return null
return when (node.elementType) {
KtNodeTypes.PROPERTY_ACCESSOR ->
e.parent.parent
else ->
e.parent
}
}
private object Holder {
val handlers: List<ElementHandler<*>> = listOf<ElementHandler<*>>(
LambdaHandler,
AnonymousObjectHandler,
AnonymousFunctionHandler,
PropertyAccessorHandler,
DeclarationHandler,
IfThenHandler,
ElseHandler,
TryHandler,
CatchHandler,
FinallyHandler,
WhileHandler,
DoWhileHandler,
WhenHandler,
WhenEntryHandler,
ForHandler
)
}
}
internal enum class TextKind(val maxTextLength: Int) {
INFO(16), TOOLTIP(100)
}
internal fun KtExpression.shortText(kind: TextKind): String {
return if (this is KtNameReferenceExpression) text else text.truncateEnd(kind)
}
//TODO: line breaks
internal fun String.orEllipsis(kind: TextKind): String {
return if (length <= kind.maxTextLength) this else ellipsis
}
internal fun String.truncateEnd(kind: TextKind): String {
val maxLength = kind.maxTextLength
return if (length > maxLength) substring(0, maxLength - ellipsis.length) + ellipsis else this
}
internal fun String.truncateStart(kind: TextKind): String {
val maxLength = kind.maxTextLength
return if (length > maxLength) ellipsis + substring(length - maxLength - 1) else this
}
internal const val ellipsis = "${Typography.ellipsis}"
internal fun KtContainerNode.bodyOwner(): KtExpression? {
return if (node.elementType == KtNodeTypes.BODY) parent as KtExpression else null
}
internal fun KtExpression.labelText(): String {
var result = ""
var current = parent
while (current is KtLabeledExpression) {
result = current.getLabelName() + "@ " + result
current = current.parent
}
return result
} | apache-2.0 | ea9645943ee657fa2ed06c4d5e9aae71 | 41.611465 | 137 | 0.620111 | 5.696565 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/browsers/impl/WebBrowserServiceImpl.kt | 5 | 3306 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.browsers.impl
import com.intellij.ide.browsers.*
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.DumbService
import com.intellij.psi.PsiElement
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.Url
import com.intellij.util.Urls
import com.intellij.util.containers.ContainerUtil
import java.util.*
private val URL_PROVIDER_EP = ExtensionPointName<WebBrowserUrlProvider>("com.intellij.webBrowserUrlProvider")
class WebBrowserServiceImpl : WebBrowserService() {
companion object {
fun getProviders(request: OpenInBrowserRequest): Sequence<WebBrowserUrlProvider> {
val dumbService = DumbService.getInstance(request.project)
return URL_PROVIDER_EP.extensionList.asSequence().filter {
(!dumbService.isDumb || DumbService.isDumbAware(it)) && it.canHandleElement(request)
}
}
fun getDebuggableUrls(context: PsiElement?): Collection<Url> {
try {
val request = if (context == null) null else createOpenInBrowserRequest(context)
if (request == null || WebBrowserXmlService.getInstance().isXmlLanguage(request.file.viewProvider.baseLanguage)) {
return emptyList()
}
else {
// it is client responsibility to set token
request.isAppendAccessToken = false
request.reloadMode = ReloadMode.DISABLED
return getProviders(request)
.map { getUrls(it, request) }
.filter(Collection<*>::isNotEmpty).firstOrNull()
?: emptyList()
}
}
catch (ignored: WebBrowserUrlProvider.BrowserException) {
return emptyList()
}
}
@JvmStatic
fun getDebuggableUrl(context: PsiElement?): Url? = ContainerUtil.getFirstItem(getDebuggableUrls(context))
}
override fun getUrlsToOpen(request: OpenInBrowserRequest, preferLocalUrl: Boolean): Collection<Url> {
val isHtmlOrXml = WebBrowserXmlService.getInstance().isHtmlOrXmlFile(request.file)
if (!preferLocalUrl || !isHtmlOrXml) {
val dumbService = DumbService.getInstance(request.project)
for (urlProvider in URL_PROVIDER_EP.extensionList) {
if ((!dumbService.isDumb || DumbService.isDumbAware(urlProvider)) && urlProvider.canHandleElement(request)) {
val urls = getUrls(urlProvider, request)
if (!urls.isEmpty()) {
return urls
}
}
}
if (!isHtmlOrXml && !request.isForceFileUrlIfNoUrlProvider) {
return emptyList()
}
}
val file = if (!request.file.viewProvider.isPhysical) null else request.virtualFile
return if (file is LightVirtualFile || file == null) emptyList() else listOf(Urls.newFromVirtualFile(file))
}
}
private fun getUrls(provider: WebBrowserUrlProvider?, request: OpenInBrowserRequest): Collection<Url> {
if (provider != null) {
request.result?.let { return it }
try {
return provider.getUrls(request)
}
catch (e: WebBrowserUrlProvider.BrowserException) {
if (!WebBrowserXmlService.getInstance().isHtmlFile(request.file)) {
throw e
}
}
}
return emptyList()
} | apache-2.0 | 4a42ae0e5f77fd4d92f9549af8c1353a | 37.011494 | 122 | 0.696007 | 4.669492 | false | false | false | false |
GunoH/intellij-community | plugins/performanceTesting/src/com/jetbrains/performancePlugin/commands/RecoveryActionCommand.kt | 1 | 1996 | package com.jetbrains.performancePlugin.commands
import com.intellij.ide.actions.cache.ProjectRecoveryScope
import com.intellij.ide.actions.cache.RecoveryAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.ui.playback.PlaybackContext
import com.intellij.openapi.ui.playback.commands.AbstractCommand
import com.intellij.util.indexing.RefreshIndexableFilesAction
import com.intellij.util.indexing.ReindexAction
import com.intellij.util.indexing.RescanIndexesAction
import com.jetbrains.performancePlugin.utils.ActionCallbackProfilerStopper
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.toPromise
private val LOG = Logger.getInstance(RecoveryActionCommand::class.java)
class RecoveryActionCommand(text: String, line: Int) : AbstractCommand(text, line) {
companion object {
const val PREFIX = CMD_PREFIX + "recovery"
private val ALLOWED_ACTIONS = listOf("REFRESH", "RESCAN", "REINDEX")
}
override fun _execute(context: PlaybackContext): Promise<Any?> {
val actionCallback = ActionCallbackProfilerStopper()
val args = text.split(" ".toRegex(), 2).toTypedArray()
val project = context.project
val recoveryAction: RecoveryAction = when (args[1]) {
"REFRESH" -> RefreshIndexableFilesAction()
"RESCAN" -> RescanIndexesAction()
"REINDEX" -> ReindexAction()
else -> error("The argument ${args[1]} to the command is incorrect. Allowed actions: $ALLOWED_ACTIONS")
}
recoveryAction.perform(ProjectRecoveryScope(project)).handle { res, err ->
if (err != null) {
LOG.error(err)
return@handle
}
if (res.problems.isNotEmpty()) {
LOG.error("${recoveryAction.actionKey} found and fixed ${res.problems.size} problems, samples: " +
res.problems.take(10).joinToString(", ") { it.message })
}
LOG.info("Command $PREFIX ${args[1]} finished")
actionCallback.setDone()
}
return actionCallback.toPromise()
}
}
| apache-2.0 | 3a769a677e943be61f06edf7a89b583e | 38.92 | 109 | 0.731463 | 4.228814 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.kt | 1 | 31001 | // 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.keymap.impl
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.configurationStore.SerializableScheme
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.PluginManagerConfigurable
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.keymap.ex.KeymapManagerEx
import com.intellij.openapi.options.ExternalizableSchemeAdapter
import com.intellij.openapi.options.SchemeState
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.KeyStrokeAdapter
import com.intellij.util.ArrayUtilRt
import com.intellij.util.SmartList
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.mapSmart
import com.intellij.util.containers.nullize
import org.jdom.Element
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import javax.swing.KeyStroke
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private const val KEY_MAP = "keymap"
private const val KEYBOARD_SHORTCUT = "keyboard-shortcut"
private const val KEYBOARD_GESTURE_SHORTCUT = "keyboard-gesture-shortcut"
private const val KEYBOARD_GESTURE_KEY = "keystroke"
private const val KEYBOARD_GESTURE_MODIFIER = "modifier"
private const val KEYSTROKE_ATTRIBUTE = "keystroke"
private const val FIRST_KEYSTROKE_ATTRIBUTE = "first-keystroke"
private const val SECOND_KEYSTROKE_ATTRIBUTE = "second-keystroke"
private const val ACTION = "action"
private const val VERSION_ATTRIBUTE = "version"
private const val PARENT_ATTRIBUTE = "parent"
private const val NAME_ATTRIBUTE = "name"
private const val ID_ATTRIBUTE = "id"
private const val MOUSE_SHORTCUT = "mouse-shortcut"
fun KeymapImpl(name: String, dataHolder: SchemeDataHolder<KeymapImpl>): KeymapImpl {
val result = KeymapImpl(dataHolder)
result.name = name
result.schemeState = SchemeState.UNCHANGED
return result
}
open class KeymapImpl @JvmOverloads constructor(private var dataHolder: SchemeDataHolder<KeymapImpl>? = null)
: ExternalizableSchemeAdapter(), Keymap, SerializableScheme {
@Volatile
private var parent: KeymapImpl? = null
private var unknownParentName: String? = null
open var canModify: Boolean = true
@JvmField
internal var schemeState: SchemeState? = null
override fun getSchemeState(): SchemeState? = schemeState
private val actionIdToShortcuts = ConcurrentHashMap<String, List<Shortcut>>()
get() {
val dataHolder = dataHolder
if (dataHolder != null) {
this.dataHolder = null
readExternal(dataHolder.read())
}
return field
}
private val keymapManager by lazy { KeymapManagerEx.getInstanceEx()!! }
/**
* @return IDs of the action which are specified in the keymap. It doesn't return IDs of action from parent keymap.
*/
val ownActionIds: Array<String>
get() = actionIdToShortcuts.keys.toTypedArray()
private fun <T> cachedShortcuts(mapper: (Shortcut) -> T?): ReadWriteProperty<Any?, Map<T, MutableList<String>>> =
object : ReadWriteProperty<Any?, Map<T, MutableList<String>>> {
private var cache: Map<T, MutableList<String>>? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): Map<T, MutableList<String>> =
cache ?: mapShortcuts(mapper).also { cache = it }
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Map<T, MutableList<String>>) {
cache = null
}
private fun mapShortcuts(mapper: (Shortcut) -> T?): Map<T, MutableList<String>> {
fun addActionToShortcutMap(actionId: String, map: MutableMap<T, MutableList<String>>) {
for (shortcut in getOwnOrBoundShortcuts(actionId)) {
mapper(shortcut)?.let {
val ids = map.getOrPut(it) { SmartList() }
if (!ids.contains(actionId)) {
ids.add(actionId)
}
}
}
}
val map = HashMap<T, MutableList<String>>()
actionIdToShortcuts.keys.forEach { addActionToShortcutMap(it, map) }
keymapManager.boundActions.forEach { addActionToShortcutMap(it, map) }
return map
}
}
// Accesses to these caches are non-synchronized, so must be performed
// from EDT only (where all the modifications are currently done)
private var keystrokeToActionIds: Map<KeyStroke, MutableList<String>> by cachedShortcuts { (it as? KeyboardShortcut)?.firstKeyStroke }
private var mouseShortcutToActionIds: Map<MouseShortcut, MutableList<String>> by cachedShortcuts { it as? MouseShortcut }
private var gestureToActionIds: Map<KeyboardModifierGestureShortcut, MutableList<String>> by cachedShortcuts { it as? KeyboardModifierGestureShortcut }
override fun getPresentableName(): String = name
override fun deriveKeymap(newName: String): KeymapImpl =
if (canModify()) {
val newKeymap = copy()
newKeymap.name = newName
newKeymap
}
else {
val newKeymap = KeymapImpl()
newKeymap.parent = this
newKeymap.name = newName
newKeymap
}
fun copy(): KeymapImpl =
dataHolder?.let { KeymapImpl(name, it) }
?: copyTo(KeymapImpl())
fun copyTo(otherKeymap: KeymapImpl): KeymapImpl {
otherKeymap.cleanShortcutsCache()
otherKeymap.actionIdToShortcuts.clear()
otherKeymap.actionIdToShortcuts.putAll(actionIdToShortcuts)
// after actionIdToShortcuts (on first access we lazily read itself)
otherKeymap.parent = parent
otherKeymap.name = name
otherKeymap.canModify = canModify()
return otherKeymap
}
override fun getParent(): KeymapImpl? = parent
final override fun canModify(): Boolean = canModify
override fun addShortcut(actionId: String, shortcut: Shortcut) {
addShortcut(actionId, shortcut, false)
}
fun addShortcut(actionId: String, shortcut: Shortcut, fromSettings: Boolean) {
actionIdToShortcuts.compute(actionId) { id, list ->
var result: List<Shortcut>? = list
if (result == null) {
val boundShortcuts = keymapManager.getActionBinding(id)?.let { actionIdToShortcuts[it] }
result = boundShortcuts ?: parent?.getShortcutList(id)?.map { convertShortcut(it) } ?: emptyList()
}
if (!result.contains(shortcut)) {
result = result + shortcut
}
if (result.areShortcutsEqualToParent(id)) null else result
}
cleanShortcutsCache()
fireShortcutChanged(actionId, fromSettings)
}
private fun cleanShortcutsCache() {
keystrokeToActionIds = emptyMap()
mouseShortcutToActionIds = emptyMap()
gestureToActionIds = emptyMap()
schemeState = SchemeState.POSSIBLY_CHANGED
}
override fun removeAllActionShortcuts(actionId: String) {
for (shortcut in getShortcuts(actionId)) {
removeShortcut(actionId, shortcut)
}
}
override fun removeShortcut(actionId: String, toDelete: Shortcut) {
removeShortcut(actionId, toDelete, false)
}
fun removeShortcut(actionId: String, toDelete: Shortcut, fromSettings: Boolean) {
val fromBinding = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
actionIdToShortcuts.compute(actionId) { id, list ->
when {
list == null -> {
val inherited = fromBinding ?: parent?.getShortcutList(id)?.mapSmart { convertShortcut(it) }.nullize()
if (inherited == null || !inherited.contains(toDelete)) null
else inherited - toDelete
}
!list.contains(toDelete) -> list
parent == null -> if (list.size == 1) null else ContainerUtil.newUnmodifiableList(list - toDelete)
else -> {
val result = list - toDelete
if (result.areShortcutsEqualToParent(id)) null else ContainerUtil.newUnmodifiableList(result)
}
}
}
cleanShortcutsCache()
fireShortcutChanged(actionId, fromSettings)
}
private fun List<Shortcut>.areShortcutsEqualToParent(actionId: String) =
parent.let { parent -> parent != null && areShortcutsEqual(this, parent.getShortcutList(actionId).mapSmart { convertShortcut(it) }) }
private fun getOwnOrBoundShortcuts(actionId: String): List<Shortcut> {
actionIdToShortcuts[actionId]?.let {
return it
}
val result = SmartList<Shortcut>()
keymapManager.getActionBinding(actionId)?.let {
result.addAll(getOwnOrBoundShortcuts(it))
}
return result
}
private fun getActionIds(shortcut: KeyboardModifierGestureShortcut): List<String> {
// first, get keystrokes from our own map
val list = SmartList<String>()
for ((key, value) in gestureToActionIds) {
if (shortcut.startsWith(key)) {
list.addAll(value)
}
}
if (parent != null) {
val ids = parent!!.getActionIds(shortcut)
if (ids.isNotEmpty()) {
for (id in ids) {
// add actions from the parent keymap only if they are absent in this keymap
if (!actionIdToShortcuts.containsKey(id)) {
list.add(id)
}
}
}
}
sortInRegistrationOrder(list)
return list
}
override fun getActionIds(firstKeyStroke: KeyStroke): Array<String> {
return ArrayUtilRt.toStringArray(getActionIds(firstKeyStroke, { it.keystrokeToActionIds }, KeymapImpl::convertKeyStroke))
}
override fun getActionIds(firstKeyStroke: KeyStroke, secondKeyStroke: KeyStroke?): Array<String> {
val ids = getActionIds(firstKeyStroke)
var actualBindings: MutableList<String>? = null
for (id in ids) {
val shortcuts = getShortcuts(id)
for (shortcut in shortcuts) {
if (shortcut !is KeyboardShortcut) {
continue
}
if (firstKeyStroke == shortcut.firstKeyStroke && secondKeyStroke == shortcut.secondKeyStroke) {
if (actualBindings == null) {
actualBindings = SmartList()
}
actualBindings.add(id)
break
}
}
}
return ArrayUtilRt.toStringArray(actualBindings)
}
override fun getActionIds(shortcut: Shortcut): Array<String> {
return when (shortcut) {
is KeyboardShortcut -> {
val first = shortcut.firstKeyStroke
val second = shortcut.secondKeyStroke
if (second == null) getActionIds(first) else getActionIds(first, second)
}
is MouseShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut))
is KeyboardModifierGestureShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut))
else -> ArrayUtilRt.EMPTY_STRING_ARRAY
}
}
override fun hasActionId(actionId: String, shortcut: MouseShortcut): Boolean {
var convertedShortcut = shortcut
var keymap = this
do {
val list = keymap.mouseShortcutToActionIds[convertedShortcut]
if (list != null && list.contains(actionId)) {
return true
}
val parent = keymap.parent ?: return false
convertedShortcut = keymap.convertMouseShortcut(shortcut)
keymap = parent
}
while (true)
}
override fun getActionIds(shortcut: MouseShortcut): List<String> {
return getActionIds(shortcut, { it.mouseShortcutToActionIds }, KeymapImpl::convertMouseShortcut)
}
@RequiresEdt
private fun <T> getActionIds(shortcut: T,
shortcutToActionIds: (keymap: KeymapImpl) -> Map<T, MutableList<String>>,
convertShortcut: (keymap: KeymapImpl, shortcut: T) -> T): List<String> {
// first, get keystrokes from our own map
var list = shortcutToActionIds(this)[shortcut]
val parentIds = parent?.getActionIds(convertShortcut(this, shortcut), shortcutToActionIds, convertShortcut) ?: emptyList()
var isOriginalListInstance = list != null
for (id in parentIds) {
// add actions from the parent keymap only if they are absent in this keymap
// do not add parent bind actions, if bind-on action is overwritten in the child
if (actionIdToShortcuts.containsKey(id)) continue
val key = keymapManager.getActionBinding(id)
if (key != null && actionIdToShortcuts.containsKey(key)) continue
if (list == null) {
list = SmartList()
}
else if (isOriginalListInstance) {
list = SmartList(list)
isOriginalListInstance = false
}
if (!list.contains(id)) {
list.add(id)
}
}
sortInRegistrationOrder(list ?: return emptyList())
return list
}
fun isActionBound(actionId: String): Boolean = keymapManager.boundActions.contains(actionId)
override fun getShortcuts(actionId: String?): Array<Shortcut> =
getShortcutList(actionId).let { if (it.isEmpty()) Shortcut.EMPTY_ARRAY else it.toTypedArray() }
private fun getShortcutList(actionId: String?): List<Shortcut> {
if (actionId == null) {
return emptyList()
}
// it is critical to use convertShortcut - otherwise MacOSDefaultKeymap doesn't convert shortcuts
// todo why not convert on add? why we don't need to convert our own shortcuts?
return actionIdToShortcuts[actionId]
?: keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
?: parent?.getShortcutList(actionId)?.mapSmart { convertShortcut(it) }
?: emptyList()
}
fun getOwnShortcuts(actionId: String): Array<Shortcut> {
val own = actionIdToShortcuts[actionId] ?: return Shortcut.EMPTY_ARRAY
return if (own.isEmpty()) Shortcut.EMPTY_ARRAY else own.toTypedArray()
}
fun hasShortcutDefined(actionId: String): Boolean =
actionIdToShortcuts[actionId] != null || parent?.hasShortcutDefined(actionId) == true
// you must clear `actionIdToShortcuts` before calling
protected open fun readExternal(keymapElement: Element) {
if (KEY_MAP != keymapElement.name) {
throw InvalidDataException("unknown element: $keymapElement")
}
name = keymapElement.getAttributeValue(NAME_ATTRIBUTE)!!
unknownParentName = null
keymapElement.getAttributeValue(PARENT_ATTRIBUTE)?.let { parentSchemeName ->
var parentScheme = findParentScheme(parentSchemeName)
if (parentScheme == null && parentSchemeName == "Default for Mac OS X") {
// https://youtrack.jetbrains.com/issue/RUBY-17767#comment=27-1374197
parentScheme = findParentScheme("Mac OS X")
}
if (parentScheme == null) {
logger<KeymapImpl>().warn("Cannot find parent scheme $parentSchemeName for scheme $name")
unknownParentName = parentSchemeName
notifyAboutMissingKeymap(parentSchemeName, IdeBundle.message("notification.content.cannot.find.parent.keymap", parentSchemeName, name), true)
}
else {
parent = parentScheme as KeymapImpl
canModify = true
}
}
val actionIds = HashSet<String>()
val skipInserts = SystemInfo.isMac && (ApplicationManager.getApplication() == null || !ApplicationManager.getApplication().isUnitTestMode)
for (actionElement in keymapElement.children) {
if (actionElement.name != ACTION) {
throw InvalidDataException("unknown element: $actionElement; Keymap's name=$name")
}
val id = actionElement.getAttributeValue(ID_ATTRIBUTE) ?: throw InvalidDataException("Attribute 'id' cannot be null; Keymap's name=$name")
actionIds.add(id)
val shortcuts = SmartList<Shortcut>()
for (shortcutElement in actionElement.children) {
if (KEYBOARD_SHORTCUT == shortcutElement.name) {
// Parse first keystroke
val firstKeyStrokeStr = shortcutElement.getAttributeValue(FIRST_KEYSTROKE_ATTRIBUTE)
?: throw InvalidDataException("Attribute '$FIRST_KEYSTROKE_ATTRIBUTE' cannot be null; Action's id=$id; Keymap's name=$name")
if (skipInserts && firstKeyStrokeStr.contains("INSERT")) {
continue
}
val firstKeyStroke = KeyStrokeAdapter.getKeyStroke(firstKeyStrokeStr) ?: continue
// Parse second keystroke
var secondKeyStroke: KeyStroke? = null
val secondKeyStrokeStr = shortcutElement.getAttributeValue(SECOND_KEYSTROKE_ATTRIBUTE)
if (secondKeyStrokeStr != null) {
secondKeyStroke = KeyStrokeAdapter.getKeyStroke(secondKeyStrokeStr) ?: continue
}
shortcuts.add(KeyboardShortcut(firstKeyStroke, secondKeyStroke))
}
else if (KEYBOARD_GESTURE_SHORTCUT == shortcutElement.name) {
val strokeText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_KEY) ?: throw InvalidDataException(
"Attribute '$KEYBOARD_GESTURE_KEY' cannot be null; Action's id=$id; Keymap's name=$name")
val stroke = KeyStrokeAdapter.getKeyStroke(strokeText) ?: continue
val modifierText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_MODIFIER)
var modifier: KeyboardGestureAction.ModifierType? = null
if (KeyboardGestureAction.ModifierType.dblClick.toString().equals(modifierText, ignoreCase = true)) {
modifier = KeyboardGestureAction.ModifierType.dblClick
}
else if (KeyboardGestureAction.ModifierType.hold.toString().equals(modifierText, ignoreCase = true)) {
modifier = KeyboardGestureAction.ModifierType.hold
}
if (modifier == null) {
throw InvalidDataException("Wrong modifier=$modifierText action id=$id keymap=$name")
}
shortcuts.add(KeyboardModifierGestureShortcut.newInstance(modifier, stroke))
}
else if (MOUSE_SHORTCUT == shortcutElement.name) {
val keystrokeString = shortcutElement.getAttributeValue(KEYSTROKE_ATTRIBUTE)
?: throw InvalidDataException("Attribute 'keystroke' cannot be null; Action's id=$id; Keymap's name=$name")
try {
shortcuts.add(KeymapUtil.parseMouseShortcut(keystrokeString))
}
catch (e: InvalidDataException) {
throw InvalidDataException("Wrong mouse-shortcut: '$keystrokeString'; Action's id=$id; Keymap's name=$name")
}
}
else {
throw InvalidDataException("unknown element: $shortcutElement; Keymap's name=$name")
}
}
// creating the list even when there are no shortcuts (empty element means that an action overrides a parent one to clear shortcuts)
actionIdToShortcuts[id] = Collections.unmodifiableList(shortcuts)
}
ActionsCollectorImpl.onActionsLoadedFromKeymapXml(this, actionIds)
cleanShortcutsCache()
}
protected open fun findParentScheme(parentSchemeName: String): Keymap? = keymapManager.schemeManager.findSchemeByName(parentSchemeName)
override fun writeScheme(): Element {
dataHolder?.let {
return it.read()
}
val keymapElement = Element(KEY_MAP)
keymapElement.setAttribute(VERSION_ATTRIBUTE, "1")
keymapElement.setAttribute(NAME_ATTRIBUTE, name)
(parent?.name ?: unknownParentName)?.let {
keymapElement.setAttribute(PARENT_ATTRIBUTE, it)
}
writeOwnActionIds(keymapElement)
schemeState = SchemeState.UNCHANGED
return keymapElement
}
private fun writeOwnActionIds(keymapElement: Element) {
val ownActionIds = ownActionIds
Arrays.sort(ownActionIds)
for (actionId in ownActionIds) {
val shortcuts = actionIdToShortcuts[actionId] ?: continue
val actionElement = Element(ACTION)
actionElement.setAttribute(ID_ATTRIBUTE, actionId)
for (shortcut in shortcuts) {
when (shortcut) {
is KeyboardShortcut -> {
val element = Element(KEYBOARD_SHORTCUT)
element.setAttribute(FIRST_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(shortcut.firstKeyStroke))
shortcut.secondKeyStroke?.let {
element.setAttribute(SECOND_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(it))
}
actionElement.addContent(element)
}
is MouseShortcut -> {
val element = Element(MOUSE_SHORTCUT)
element.setAttribute(KEYSTROKE_ATTRIBUTE, KeymapUtil.getMouseShortcutString(shortcut))
actionElement.addContent(element)
}
is KeyboardModifierGestureShortcut -> {
val element = Element(KEYBOARD_GESTURE_SHORTCUT)
element.setAttribute(KEYBOARD_GESTURE_SHORTCUT, KeyStrokeAdapter.toString(shortcut.stroke))
element.setAttribute(KEYBOARD_GESTURE_MODIFIER, shortcut.type.name)
actionElement.addContent(element)
}
else -> throw IllegalStateException("unknown shortcut class: $shortcut")
}
}
keymapElement.addContent(actionElement)
}
}
fun clearOwnActionsIds() {
actionIdToShortcuts.clear()
cleanShortcutsCache()
}
fun hasOwnActionId(actionId: String): Boolean = actionIdToShortcuts.containsKey(actionId)
fun clearOwnActionsId(actionId: String) {
actionIdToShortcuts.remove(actionId)
cleanShortcutsCache()
}
override fun getActionIds(): Array<String> = ArrayUtilRt.toStringArray(actionIdList)
override fun getActionIdList(): Set<String> {
val ids = LinkedHashSet<String>()
ids.addAll(actionIdToShortcuts.keys)
var parent = parent
while (parent != null) {
ids.addAll(parent.actionIdToShortcuts.keys)
parent = parent.parent
}
return ids
}
override fun getConflicts(actionId: String, keyboardShortcut: KeyboardShortcut): Map<String, MutableList<KeyboardShortcut>> {
val result = HashMap<String, MutableList<KeyboardShortcut>>()
for (id in getActionIds(keyboardShortcut.firstKeyStroke)) {
if (id == actionId || (actionId.startsWith("Editor") && id == "$${actionId.substring(6)}")) {
continue
}
val useShortcutOf = keymapManager.getActionBinding(id)
if (useShortcutOf != null && useShortcutOf == actionId) {
continue
}
for (shortcut1 in getShortcutList(id)) {
if (shortcut1 !is KeyboardShortcut || shortcut1.firstKeyStroke != keyboardShortcut.firstKeyStroke) {
continue
}
if (keyboardShortcut.secondKeyStroke != null && shortcut1.secondKeyStroke != null && keyboardShortcut.secondKeyStroke != shortcut1.secondKeyStroke) {
continue
}
result.getOrPut(id) { SmartList() }.add(shortcut1)
}
}
return result
}
protected open fun convertKeyStroke(keyStroke: KeyStroke): KeyStroke = keyStroke
protected open fun convertMouseShortcut(shortcut: MouseShortcut): MouseShortcut = shortcut
protected open fun convertShortcut(shortcut: Shortcut): Shortcut = shortcut
private fun fireShortcutChanged(actionId: String, fromSettings: Boolean) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).shortcutChanged(this, actionId, fromSettings)
}
override fun toString(): String = presentableName
override fun equals(other: Any?): Boolean {
if (other !is KeymapImpl) return false
if (other === this) return true
if (name != other.name) return false
if (canModify != other.canModify) return false
if (parent != other.parent) return false
if (actionIdToShortcuts != other.actionIdToShortcuts) return false
return true
}
override fun hashCode(): Int = name.hashCode()
}
private fun sortInRegistrationOrder(ids: MutableList<String>) {
ids.sortWith(ActionManagerEx.getInstanceEx().registrationOrderComparator)
}
// compare two lists in any order
private fun areShortcutsEqual(shortcuts1: List<Shortcut>, shortcuts2: List<Shortcut>): Boolean {
if (shortcuts1.size != shortcuts2.size) {
return false
}
for (shortcut in shortcuts1) {
if (!shortcuts2.contains(shortcut)) {
return false
}
}
return true
}
@Suppress("SpellCheckingInspection") private const val macOSKeymap = "com.intellij.plugins.macoskeymap"
@Suppress("SpellCheckingInspection") private const val gnomeKeymap = "com.intellij.plugins.gnomekeymap"
@Suppress("SpellCheckingInspection") private const val kdeKeymap = "com.intellij.plugins.kdekeymap"
@Suppress("SpellCheckingInspection") private const val xwinKeymap = "com.intellij.plugins.xwinkeymap"
@Suppress("SpellCheckingInspection") private const val eclipseKeymap = "com.intellij.plugins.eclipsekeymap"
@Suppress("SpellCheckingInspection") private const val emacsKeymap = "com.intellij.plugins.emacskeymap"
@Suppress("SpellCheckingInspection") private const val netbeansKeymap = "com.intellij.plugins.netbeanskeymap"
@Suppress("SpellCheckingInspection") private const val qtcreatorKeymap = "com.intellij.plugins.qtcreatorkeymap"
@Suppress("SpellCheckingInspection") private const val resharperKeymap = "com.intellij.plugins.resharperkeymap"
@Suppress("SpellCheckingInspection") private const val sublimeKeymap = "com.intellij.plugins.sublimetextkeymap"
@Suppress("SpellCheckingInspection") private const val visualStudioKeymap = "com.intellij.plugins.visualstudiokeymap"
private const val visualStudio2022Keymap = "com.intellij.plugins.visualstudio2022keymap"
@Suppress("SpellCheckingInspection") private const val xcodeKeymap = "com.intellij.plugins.xcodekeymap"
@Suppress("SpellCheckingInspection") private const val visualAssistKeymap = "com.intellij.plugins.visualassistkeymap"
@Suppress("SpellCheckingInspection") private const val riderKeymap = "com.intellij.plugins.riderkeymap"
@Suppress("SpellCheckingInspection") private const val vsCodeKeymap = "com.intellij.plugins.vscodekeymap"
@Suppress("SpellCheckingInspection") private const val vsForMacKeymap = "com.intellij.plugins.vsformackeymap"
internal fun notifyAboutMissingKeymap(keymapName: String, @NlsContexts.NotificationContent message: String, isParent: Boolean) {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(project: Project) {
connection.disconnect()
ApplicationManager.getApplication().invokeLater(
{
// TODO remove when PluginAdvertiser implements that
val pluginId = when (keymapName) {
"Mac OS X",
"Mac OS X 10.5+" -> macOSKeymap
"Default for GNOME" -> gnomeKeymap
"Default for KDE" -> kdeKeymap
"Default for XWin" -> xwinKeymap
"Eclipse",
"Eclipse (Mac OS X)" -> eclipseKeymap
"Emacs" -> emacsKeymap
"NetBeans 6.5" -> netbeansKeymap
"QtCreator",
"QtCreator OSX" -> qtcreatorKeymap
"ReSharper",
"ReSharper OSX" -> resharperKeymap
"Sublime Text",
"Sublime Text (Mac OS X)" -> sublimeKeymap
"Visual Studio",
"Visual Studio OSX" -> visualStudioKeymap
"Visual Studio 2022" -> visualStudio2022Keymap
"Visual Assist",
"Visual Assist OSX" -> visualAssistKeymap
"Xcode" -> xcodeKeymap
"Visual Studio for Mac" -> vsForMacKeymap
"Rider",
"Rider OSX"-> riderKeymap
"VSCode",
"VSCode OSX"-> vsCodeKeymap
else -> null
}
val action: AnAction = when (pluginId) {
null -> object : NotificationAction(IdeBundle.message("action.text.search.for.keymap", keymapName)) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
//TODO enableSearch("$keymapName /tag:Keymap")?.run()
ShowSettingsUtil.getInstance().showSettingsDialog(e.project, PluginManagerConfigurable::class.java)
}
}
else -> object : NotificationAction(IdeBundle.message("action.text.install.keymap", keymapName)) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
val connect = ApplicationManager.getApplication().messageBus.connect()
connect.subscribe(KeymapManagerListener.TOPIC, object: KeymapManagerListener {
override fun keymapAdded(keymap: Keymap) {
ApplicationManager.getApplication().invokeLater {
if (keymap.name == keymapName) {
connect.disconnect()
val successMessage = if (isParent) IdeBundle.message("notification.content.keymap.successfully.installed", keymapName)
else {
KeymapManagerEx.getInstanceEx().activeKeymap = keymap
IdeBundle.message("notification.content.keymap.successfully.activated", keymapName)
}
Notification("KeymapInstalled", successMessage,
NotificationType.INFORMATION).notify(e.project)
}
}
}
})
val plugins = mutableSetOf(PluginId.getId(pluginId))
when (pluginId) {
gnomeKeymap, kdeKeymap -> plugins += PluginId.getId(xwinKeymap)
resharperKeymap -> plugins += PluginId.getId(visualStudioKeymap)
visualAssistKeymap -> plugins += PluginId.getId(visualStudioKeymap)
visualStudio2022Keymap -> plugins += PluginId.getId(visualStudioKeymap)
xcodeKeymap, vsForMacKeymap -> plugins += PluginId.getId(macOSKeymap)
}
installAndEnable(project, plugins) { }
notification.expire()
}
}
}
Notification("KeymapMissing", IdeBundle.message("notification.group.missing.keymap"),
message, NotificationType.ERROR)
.addAction(action)
.notify(project)
},
ModalityState.NON_MODAL)
}
})
}
| apache-2.0 | 2ebef6f2e139577797538a61912cad35 | 40.668011 | 158 | 0.690687 | 5.23754 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/util/test-generator-api/test/org/jetbrains/kotlin/testGenerator/generator/TestGenerator.kt | 3 | 5371 | // 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.testGenerator.generator
import com.intellij.testFramework.TestDataPath
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.base.test.KotlinRoot
import org.jetbrains.kotlin.test.*
import org.jetbrains.kotlin.testGenerator.model.*
import org.junit.runner.RunWith
import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.kotlin.idea.base.test.TestRoot
import java.io.File
import java.nio.file.Files
import java.util.*
object TestGenerator {
fun write(workspace: TWorkspace, isUpToDateCheck: Boolean = false) {
for (group in workspace.groups) {
for (suite in group.suites) {
write(suite, group, isUpToDateCheck)
}
}
}
private fun write(suite: TSuite, group: TGroup, isUpToDateCheck: Boolean) {
val packageName = suite.generatedClassName.substringBeforeLast('.')
val rootModelName = suite.generatedClassName.substringAfterLast('.')
val content = buildCode {
appendCopyrightComment()
newLine()
appendLine("package $packageName;")
newLine()
appendImports(getImports(suite, group))
appendGeneratedComment()
appendAnnotation(TAnnotation<SuppressWarnings>("all"))
appendAnnotation(TAnnotation<TestRoot>(group.modulePath))
appendAnnotation(TAnnotation<TestDataPath>("\$CONTENT_ROOT"))
val singleModel = suite.models.singleOrNull()
if (singleModel != null) {
append(SuiteElement.create(group, suite, singleModel, rootModelName, isNested = false))
} else {
appendAnnotation(TAnnotation<RunWith>(JUnit3RunnerWithInners::class.java))
appendBlock("public abstract class $rootModelName extends ${suite.abstractTestClass.simpleName}") {
val children = suite.models
.map { SuiteElement.create(group, suite, it, it.testClassName, isNested = true) }
appendList(children, separator = "\n\n")
}
}
newLine()
}
val filePath = suite.generatedClassName.replace('.', '/') + ".java"
val file = File(group.testSourcesRoot, filePath)
write(file, postProcessContent(content), isUpToDateCheck)
}
private fun write(file: File, content: String, isUpToDateCheck: Boolean) {
val oldContent = file.takeIf { it.isFile }?.readText() ?: ""
if (normalizeContent(content) != normalizeContent(oldContent)) {
if (isUpToDateCheck) error("'${file.name}' is not up to date\nUse 'Generate Kotlin Tests' run configuration")
Files.createDirectories(file.toPath().parent)
file.writeText(content)
val path = file.toRelativeStringSystemIndependent(KotlinRoot.DIR)
println("Updated $path")
}
}
private fun normalizeContent(content: String): String = content.replace(Regex("\\R"), "\n")
private fun getImports(suite: TSuite, group: TGroup): List<String> {
val imports = mutableListOf<String>()
imports += TestDataPath::class.java.canonicalName
imports += JUnit3RunnerWithInners::class.java.canonicalName
if (suite.models.any { it.passTestDataPath }) {
imports += KotlinTestUtils::class.java.canonicalName
}
imports += TestMetadata::class.java.canonicalName
imports += TestRoot::class.java.canonicalName
imports += RunWith::class.java.canonicalName
imports.addAll(suite.imports)
if (suite.models.any { it.targetBackend != TargetBackend.ANY }) {
imports += TargetBackend::class.java.canonicalName
}
val superPackageName = suite.abstractTestClass.`package`.name
val selfPackageName = suite.generatedClassName.substringBeforeLast('.')
if (superPackageName != selfPackageName) {
imports += suite.abstractTestClass.kotlin.java.canonicalName
}
if (group.isCompilerTestData) {
imports += "static ${TestKotlinArtifacts::class.java.canonicalName}.${TestKotlinArtifacts::compilerTestData.name}"
}
return imports
}
private fun postProcessContent(text: String): String {
return text.lineSequence()
.map { it.trimEnd() }
.joinToString(System.getProperty("line.separator"))
}
private fun Code.appendImports(imports: List<String>) {
if (imports.isNotEmpty()) {
imports.forEach { appendLine("import $it;") }
newLine()
}
}
private fun Code.appendCopyrightComment() {
val year = GregorianCalendar()[Calendar.YEAR]
appendLine("// Copyright 2000-$year JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.")
}
private fun Code.appendGeneratedComment() {
appendDocComment("""
This class is generated by {@link org.jetbrains.kotlin.testGenerator.generator.TestGenerator}.
DO NOT MODIFY MANUALLY.
""".trimIndent())
}
} | apache-2.0 | f60da97c1ff8ae056dea8b2c3738b39d | 39.390977 | 143 | 0.654068 | 5.081362 | false | true | false | false |
ktorio/ktor | ktor-shared/ktor-serialization/ktor-serialization-jackson/jvm/test/ServerJacksonBlockingTest.kt | 1 | 2638 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.jackson.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import kotlinx.coroutines.*
import java.io.*
import java.lang.reflect.*
import java.util.concurrent.*
import kotlin.coroutines.*
import kotlin.test.*
@Suppress("DEPRECATION")
class ServerJacksonBlockingTest {
private val dispatcher = UnsafeDispatcher()
private val environment = createTestEnvironment {
parentCoroutineContext = dispatcher
}
@AfterTest
fun cleanup() {
dispatcher.close()
}
@Test
fun testReceive(): Unit = withApplication(environment) {
application.intercept(ApplicationCallPipeline.Setup) {
withContext(dispatcher) {
proceed()
}
}
application.install(ContentNegotiation) {
jackson()
}
application.routing {
post("/") {
assertEquals(K(77), call.receive())
call.respondText("OK")
}
}
runBlocking {
assertEquals(
"OK",
client.post("/") {
setBody("{\"i\": 77}")
contentType(ContentType.Application.Json)
}.body()
)
}
}
data class K(var i: Int)
private class UnsafeDispatcher : CoroutineDispatcher(), Closeable {
private val dispatcher = Executors.newCachedThreadPool().asCoroutineDispatcher()
override fun dispatch(context: CoroutineContext, block: Runnable) {
dispatcher.dispatch(context + dispatcher) {
markParkingProhibited()
block.run()
}
}
override fun close() {
dispatcher.close()
}
private val prohibitParkingFunction: Method? by lazy {
try {
Class.forName("io.ktor.utils.io.jvm.javaio.PollersKt")
.getMethod("prohibitParking")
} catch (cause: Throwable) {
null
}
}
private fun markParkingProhibited() {
try {
prohibitParkingFunction?.invoke(null)
} catch (cause: Throwable) {
}
}
}
}
| apache-2.0 | eb4b9f7a2907d440e382d3ea34879793 | 26.768421 | 118 | 0.580364 | 4.867159 | false | true | false | false |
evanchooly/kobalt | src/test/kotlin/com/beust/kobalt/maven/DependencyTest.kt | 1 | 1432 | package com.beust.kobalt.maven
import com.beust.kobalt.TestModule
import com.beust.kobalt.misc.KobaltExecutors
import com.beust.kobalt.misc.Versions
import org.testng.Assert
import org.testng.annotations.*
import java.util.concurrent.ExecutorService
import javax.inject.Inject
import kotlin.properties.Delegates
@Guice(modules = arrayOf(TestModule::class))
class DependencyTest @Inject constructor(val executors: KobaltExecutors) {
@DataProvider
fun dpVersions(): Array<Array<out Any>> {
return arrayOf(
arrayOf("0.1", "0.1.1"),
arrayOf("0.1", "1.4"),
arrayOf("6.9.4", "6.9.5"),
arrayOf("1.7", "1.38"),
arrayOf("1.70", "1.380"),
arrayOf("3.8.1", "4.5"),
arrayOf("18.0-rc1", "19.0"),
arrayOf("3.0.5.RELEASE", "3.0.6")
)
}
private var executor: ExecutorService by Delegates.notNull()
@BeforeClass
public fun bc() {
executor = executors.newExecutor("DependencyTest", 5)
}
@AfterClass
public fun ac() {
executor.shutdown()
}
@Test(dataProvider = "dpVersions")
public fun versionSorting(k: String, v: String) {
val dep1 = Versions.toLongVersion(k)
val dep2 = Versions.toLongVersion(v)
Assert.assertTrue(dep1.compareTo(dep2) < 0)
Assert.assertTrue(dep2.compareTo(dep1) > 0)
}
}
| apache-2.0 | 408c33f7748514b9f4d18834244ef02c | 28.22449 | 74 | 0.607542 | 3.75853 | false | true | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/setting/search/SettingsSearchController.kt | 2 | 5347 | package eu.kanade.tachiyomi.ui.setting.search
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 androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import dev.chrisbanes.insetter.applyInsetter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.databinding.SettingsSearchControllerBinding
import eu.kanade.tachiyomi.ui.base.controller.NucleusController
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.setting.SettingsController
/**
* This controller shows and manages the different search result in settings search.
* [SettingsSearchAdapter.OnTitleClickListener] called when preference is clicked in settings search
*/
class SettingsSearchController :
NucleusController<SettingsSearchControllerBinding, SettingsSearchPresenter>(),
SettingsSearchAdapter.OnTitleClickListener {
/**
* Adapter containing search results grouped by lang.
*/
private var adapter: SettingsSearchAdapter? = null
private lateinit var searchView: SearchView
init {
setHasOptionsMenu(true)
}
override fun createBinding(inflater: LayoutInflater) = SettingsSearchControllerBinding.inflate(inflater)
override fun getTitle(): String? {
return presenter.query
}
/**
* Create the [SettingsSearchPresenter] used in controller.
*
* @return instance of [SettingsSearchPresenter]
*/
override fun createPresenter(): SettingsSearchPresenter {
return SettingsSearchPresenter()
}
/**
* Adds items to the options menu.
*
* @param menu menu containing options.
* @param inflater used to load the menu xml.
*/
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.settings_main, menu)
binding.recycler.applyInsetter {
type(navigationBars = true) {
padding()
}
}
// Initialize search menu
val searchItem = menu.findItem(R.id.action_search)
searchView = searchItem.actionView as SearchView
searchView.maxWidth = Int.MAX_VALUE
searchView.queryHint = applicationContext?.getString(R.string.action_search_settings)
searchItem.expandActionView()
setItems(getResultSet())
searchItem.setOnActionExpandListener(
object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
return true
}
override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
router.popCurrentController()
return false
}
}
)
searchView.setOnQueryTextListener(
object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
setItems(getResultSet(query))
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
setItems(getResultSet(newText))
return false
}
}
)
searchView.setQuery(presenter.preferences.lastSearchQuerySearchSettings().get(), true)
}
override fun onViewCreated(view: View) {
super.onViewCreated(view)
adapter = SettingsSearchAdapter(this)
binding.recycler.layoutManager = LinearLayoutManager(view.context)
binding.recycler.adapter = adapter
// load all search results
SettingsSearchHelper.initPreferenceSearchResultCollection(presenter.preferences.context)
}
override fun onDestroyView(view: View) {
adapter = null
super.onDestroyView(view)
}
override fun onSaveViewState(view: View, outState: Bundle) {
super.onSaveViewState(view, outState)
adapter?.onSaveInstanceState(outState)
}
override fun onRestoreViewState(view: View, savedViewState: Bundle) {
super.onRestoreViewState(view, savedViewState)
adapter?.onRestoreInstanceState(savedViewState)
}
/**
* returns a list of `SettingsSearchItem` to be shown as search results
* Future update: should we add a minimum length to the query before displaying results? Consider other languages.
*/
fun getResultSet(query: String? = null): List<SettingsSearchItem> {
if (!query.isNullOrBlank()) {
return SettingsSearchHelper.getFilteredResults(query)
.map { SettingsSearchItem(it, null) }
}
return mutableListOf()
}
/**
* Add search result to adapter.
*
* @param searchResult result of search.
*/
fun setItems(searchResult: List<SettingsSearchItem>) {
adapter?.updateDataSet(searchResult)
}
/**
* Opens a catalogue with the given search.
*/
override fun onTitleClick(ctrl: SettingsController) {
searchView.query.let {
presenter.preferences.lastSearchQuerySearchSettings().set(it.toString())
}
router.pushController(ctrl.withFadeTransaction())
}
}
| apache-2.0 | ed64598722064c5aa8421a56afbdea51 | 31.803681 | 118 | 0.669908 | 5.428426 | false | false | false | false |
oldergod/android-architecture | app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/Task.kt | 1 | 545 | package com.example.android.architecture.blueprints.todoapp.data
import com.example.android.architecture.blueprints.todoapp.util.isNotNullNorEmpty
import java.util.UUID
data class Task(
val id: String = UUID.randomUUID().toString(),
val title: String?,
val description: String?,
val completed: Boolean = false
) {
val titleForList =
if (title.isNotNullNorEmpty()) {
title
} else {
description
}
val active = !completed
val empty = title.isNullOrEmpty() && description.isNullOrEmpty()
} | apache-2.0 | ae3afc6a3268cd7951133dacf9842781 | 23.818182 | 81 | 0.695413 | 4.430894 | false | false | false | false |
tommykw/iweather | app/src/main/java/com/github/tommykw/colorpicker/ColorPicker.kt | 1 | 3809 | package com.github.tommykw.colorpicker
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
/**
* Created by tommy on 2016/06/03.
*/
class ColorPicker @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
val colors = intArrayOf(Color.RED, Color.GREEN, Color.BLUE)
val strokeSize = 2 * context.resources.displayMetrics.density
val rainbowPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
}
val rainbowBackgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
}
val pickPaint = Paint(Paint.ANTI_ALIAS_FLAG)
var pick = 0.5f
var verticalGridSize = 0f
var rainbowBaseline = 0f
var showPreview = false
var listener: OnColorChangedListener? = null
override fun onDraw(canvas: Canvas) {
drawPicker(canvas)
drawColorAim(canvas, rainbowBaseline, verticalGridSize.toInt() / 2, verticalGridSize * 0.5f, color)
if (showPreview) {
drawColorAim(canvas, verticalGridSize, (verticalGridSize / 1.4f).toInt(), verticalGridSize * 0.7f, color)
}
}
private fun drawPicker(canvas: Canvas) {
val lineX = verticalGridSize / 2f
val lineY = rainbowBaseline.toFloat()
rainbowPaint.strokeWidth = verticalGridSize / 1.5f + strokeSize
rainbowBackgroundPaint.strokeWidth = rainbowPaint.strokeWidth + strokeSize
canvas.drawLine(lineX, lineY, width - lineX, lineY, rainbowBackgroundPaint)
canvas.drawLine(lineX, lineY, width - lineX, lineY, rainbowPaint)
}
private fun drawColorAim(canvas: Canvas, baseLine: Float, offset: Int, size: Float, color: Int) {
val circleCenterX = offset + pick * (canvas.width - offset * 2)
canvas.drawCircle(circleCenterX, baseLine, size, pickPaint.apply { this.color = Color.WHITE })
canvas.drawCircle(circleCenterX, baseLine, size - strokeSize, pickPaint.apply { this.color = color })
}
@SuppressLint("DrawAllocation")
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val height = measuredHeight
val width = measuredWidth
val shader = LinearGradient(
height / 4.0f,
height / 2.0f,
width - height / 4.0f,
height / 2.0f,
colors,
null,
Shader.TileMode.CLAMP
)
verticalGridSize = height / 3f
rainbowPaint.shader = shader
rainbowBaseline = verticalGridSize / 2f + verticalGridSize * 2
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val action = event.action
if (action == MotionEvent.ACTION_MOVE || action == MotionEvent.ACTION_DOWN) {
pick = event.x / measuredWidth.toFloat()
if (pick < 0) {
pick = 0f
} else if (pick > 1) {
pick = 1f
}
listener?.onColorChanged(color)
showPreview = true
} else if (action == MotionEvent.ACTION_UP) {
showPreview = false
}
postInvalidateOnAnimation()
return true
}
val color: Int
get() = Utils.interpreterColor(pick, colors)
fun setOnColorChangedListener(listener: OnColorChangedListener) {
this.listener = listener
}
interface OnColorChangedListener {
fun onColorChanged(color: Int)
}
} | apache-2.0 | 097361452d22dfceee5aa962e4ac312d | 34.607477 | 117 | 0.638488 | 4.622573 | false | false | false | false |
mdanielwork/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/accounts/GithubProjectDefaultAccountHolder.kt | 4 | 2062 | // 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.github.authentication.accounts
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.project.Project
import org.jetbrains.plugins.github.util.GithubNotifications
/**
* Handles default Github account for project
*
* TODO: auto-detection
*/
@State(name = "GithubDefaultAccount", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
internal class GithubProjectDefaultAccountHolder(private val project: Project,
private val accountManager: GithubAccountManager) : PersistentStateComponent<AccountState> {
var account: GithubAccount? = null
init {
ApplicationManager.getApplication()
.messageBus
.connect(project)
.subscribe(GithubAccountManager.ACCOUNT_REMOVED_TOPIC, object : AccountRemovedListener {
override fun accountRemoved(removedAccount: GithubAccount) {
if (account == removedAccount) account = null
}
})
}
override fun getState(): AccountState {
return AccountState().apply { defaultAccountId = account?.id }
}
override fun loadState(state: AccountState) {
account = state.defaultAccountId?.let(::findAccountById)
}
private fun findAccountById(id: String): GithubAccount? {
val account = accountManager.accounts.find { it.id == id }
if (account == null) runInEdt {
GithubNotifications.showWarning(project, "Missing Default Github Account", "",
GithubNotifications.getConfigureAction(project))
}
return account
}
}
internal class AccountState {
var defaultAccountId: String? = null
}
| apache-2.0 | b43020f269658832d269a30217c43c4b | 36.490909 | 141 | 0.733269 | 5.004854 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/templates/ConsoleJvmApplicationTemplate.kt | 5 | 2171 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.templates
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.Reader
import org.jetbrains.kotlin.tools.projectWizard.core.Writer
import org.jetbrains.kotlin.tools.projectWizard.core.asPath
import org.jetbrains.kotlin.tools.projectWizard.core.buildList
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.ModuleIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.runTaskIrs
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.moduleType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.SourcesetType
object ConsoleJvmApplicationTemplate : Template() {
@NonNls
override val id: String = "consoleJvmApp"
override val title: String = KotlinNewProjectWizardBundle.message("module.template.console.jvm.title")
override val description: String = KotlinNewProjectWizardBundle.message("module.template.console.jvm.description")
private const val fileToCreate = "Main.kt"
override val filesToOpenInEditor = listOf(fileToCreate)
override fun isApplicableTo(module: Module, projectKind: ProjectKind, reader: Reader): Boolean =
module.configurator.moduleType == ModuleType.jvm
override fun Writer.getIrsToAddToBuildFile(
module: ModuleIR
) = buildList<BuildSystemIR> {
+runTaskIrs("MainKt")
}
override fun Reader.getFileTemplates(module: ModuleIR) =
buildList<FileTemplateDescriptorWithPath> {
+(FileTemplateDescriptor("$id/main.kt.vm", fileToCreate.asPath()) asSrcOf SourcesetType.main)
}
}
| apache-2.0 | 3fac9d5f4d9254f0b70af2d2be53922b | 50.690476 | 158 | 0.804238 | 4.599576 | false | false | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/ide/inspections/SolInspectionSuppressor.kt | 1 | 1863 | package me.serce.solidity.ide.inspections
import com.intellij.codeInsight.daemon.impl.actions.AbstractBatchSuppressByNoInspectionCommentFix
import com.intellij.codeInspection.InspectionSuppressor
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.codeInspection.SuppressionUtil
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import me.serce.solidity.lang.psi.SolElement
import me.serce.solidity.lang.psi.ancestors
import me.serce.solidity.lang.psi.parentOfType
class SolInspectionSuppressor : InspectionSuppressor {
override fun getSuppressActions(element: PsiElement?, toolId: String): Array<out SuppressQuickFix> = arrayOf(
SuppressInspectionFix(toolId),
SuppressInspectionFix(SuppressionUtil.ALL)
)
override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean =
element.ancestors
.filterIsInstance<SolElement>()
.any { isSuppressedByComment(it, toolId) }
private fun isSuppressedByComment(element: PsiElement, toolId: String): Boolean {
val comment = PsiTreeUtil.skipSiblingsBackward(element, PsiWhiteSpace::class.java) as? PsiComment
if (comment == null) {
return false
}
val matcher = SuppressionUtil.SUPPRESS_IN_LINE_COMMENT_PATTERN.matcher(comment.text)
return matcher.matches() && SuppressionUtil.isInspectionToolIdMentioned(matcher.group(1), toolId)
}
private class SuppressInspectionFix(ID: String)
: AbstractBatchSuppressByNoInspectionCommentFix(ID, ID == SuppressionUtil.ALL) {
init {
text = when (ID) {
SuppressionUtil.ALL -> "Suppress all inspections for item"
else -> "Suppress for item"
}
}
override fun getContainer(context: PsiElement?) = context?.parentOfType<SolElement>(strict = false)
}
}
| mit | 2377b0f348d02b844497531ad174f3a4 | 38.638298 | 111 | 0.775631 | 4.435714 | false | false | false | false |
fwcd/kotlin-language-server | server/src/test/resources/completions/FunctionScope.kt | 1 | 272 | private class FunctionScope {
fun foo(anArgument: Int) {
val aLocal = 1
a
}
private val aClassVal = 1
private fun aClassFun() = 1
companion object {
private val aCompanionVal = 1
private fun aCompanionFun() = 1
}
} | mit | 5ec285baa5fcc9e918abab4de8d8ba48 | 18.5 | 39 | 0.580882 | 4.184615 | false | false | false | false |
Subsets and Splits