content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package kotterknife
import android.app.Activity
import android.app.Dialog
import android.app.DialogFragment
import android.app.Fragment
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import android.support.v4.app.DialogFragment as SupportDialogFragment
import android.support.v4.app.Fragment as SupportFragment
public fun <V : View> View.bindView(id: Int)
: ReadOnlyProperty<View, V> = required(id, viewFinder)
public fun <V : View> Activity.bindView(id: Int)
: ReadOnlyProperty<Activity, V> = required(id, viewFinder)
public fun <V : View> Dialog.bindView(id: Int)
: ReadOnlyProperty<Dialog, V> = required(id, viewFinder)
public fun <V : View> DialogFragment.bindView(id: Int)
: ReadOnlyProperty<DialogFragment, V> = required(id, viewFinder)
public fun <V : View> SupportDialogFragment.bindView(id: Int)
: ReadOnlyProperty<SupportDialogFragment, V> = required(id, viewFinder)
public fun <V : View> Fragment.bindView(id: Int)
: ReadOnlyProperty<Fragment, V> = required(id, viewFinder)
public fun <V : View> SupportFragment.bindView(id: Int)
: ReadOnlyProperty<SupportFragment, V> = required(id, viewFinder)
public fun <V : View> ViewHolder.bindView(id: Int)
: ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder)
public fun <V : View> View.bindOptionalView(id: Int)
: ReadOnlyProperty<View, V?> = optional(id, viewFinder)
public fun <V : View> Activity.bindOptionalView(id: Int)
: ReadOnlyProperty<Activity, V?> = optional(id, viewFinder)
public fun <V : View> Dialog.bindOptionalView(id: Int)
: ReadOnlyProperty<Dialog, V?> = optional(id, viewFinder)
public fun <V : View> DialogFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<DialogFragment, V?> = optional(id, viewFinder)
public fun <V : View> SupportDialogFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<SupportDialogFragment, V?> = optional(id, viewFinder)
public fun <V : View> Fragment.bindOptionalView(id: Int)
: ReadOnlyProperty<Fragment, V?> = optional(id, viewFinder)
public fun <V : View> SupportFragment.bindOptionalView(id: Int)
: ReadOnlyProperty<SupportFragment, V?> = optional(id, viewFinder)
public fun <V : View> ViewHolder.bindOptionalView(id: Int)
: ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder)
public fun <V : View> View.bindViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = required(ids, viewFinder)
public fun <V : View> Activity.bindViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = required(ids, viewFinder)
public fun <V : View> Dialog.bindViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = required(ids, viewFinder)
public fun <V : View> DialogFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<DialogFragment, List<V>> = required(ids, viewFinder)
public fun <V : View> SupportDialogFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<SupportDialogFragment, List<V>> = required(ids, viewFinder)
public fun <V : View> Fragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = required(ids, viewFinder)
public fun <V : View> SupportFragment.bindViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = required(ids, viewFinder)
public fun <V : View> ViewHolder.bindViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = required(ids, viewFinder)
public fun <V : View> View.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = optional(ids, viewFinder)
public fun <V : View> Activity.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = optional(ids, viewFinder)
public fun <V : View> Dialog.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = optional(ids, viewFinder)
public fun <V : View> DialogFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<DialogFragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> SupportDialogFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<SupportDialogFragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> Fragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Fragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> SupportFragment.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<SupportFragment, List<V>> = optional(ids, viewFinder)
public fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, viewFinder)
private val View.viewFinder: View.(Int) -> View?
get() = { findViewById(it) }
private val Activity.viewFinder: Activity.(Int) -> View?
get() = { findViewById(it) }
private val Dialog.viewFinder: Dialog.(Int) -> View?
get() = { findViewById(it) }
private val DialogFragment.viewFinder: DialogFragment.(Int) -> View?
get() = { dialog.findViewById(it) }
private val SupportDialogFragment.viewFinder: SupportDialogFragment.(Int) -> View?
get() = { dialog.findViewById(it) }
private val Fragment.viewFinder: Fragment.(Int) -> View?
get() = { view.findViewById(it) }
private val SupportFragment.viewFinder: SupportFragment.(Int) -> View?
get() = { view!!.findViewById(it) }
private val ViewHolder.viewFinder: ViewHolder.(Int) -> View?
get() = { itemView.findViewById(it) }
private fun viewNotFound(id:Int, desc: KProperty<*>): Nothing =
throw IllegalStateException("View ID $id for '${desc.name}' not found.")
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(ids: IntArray, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> ids.map { t.finder(it) as V? ?: viewNotFound(it, desc) } }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(ids: IntArray, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> ids.map { t.finder(it) as V? }.filterNotNull() }
// Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it
private class Lazy<T, V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: T, property: KProperty<*>): V {
if (value == EMPTY) {
value = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return value as V
}
} | app/src/main/java/kotterknife/ButterKnife.kt | 4226648247 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.uwb.impl
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import androidx.core.uwb.RangingCapabilities
import androidx.core.uwb.UwbAddress
import androidx.core.uwb.UwbClientSessionScope
import androidx.core.uwb.UwbComplexChannel
import androidx.core.uwb.UwbControleeSessionScope
import androidx.core.uwb.UwbControllerSessionScope
import androidx.core.uwb.UwbManager
import androidx.core.uwb.backend.IUwb
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.nearby.Nearby
import kotlinx.coroutines.tasks.await
import androidx.core.uwb.helper.checkSystemFeature
import androidx.core.uwb.helper.handleApiException
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
internal class UwbManagerImpl(private val context: Context) : UwbManager {
companion object {
const val TAG = "UwbMangerImpl"
var iUwb: IUwb? = null
}
init {
val connection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
iUwb = IUwb.Stub.asInterface(service)
Log.i(TAG, "iUwb service created successfully.")
}
override fun onServiceDisconnected(p0: ComponentName?) {
iUwb = null
}
}
val intent = Intent("androidx.core.uwb.backend.service")
intent.setPackage("androidx.core.uwb.backend")
context.bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
@Deprecated("Renamed to controleeSessionScope")
override suspend fun clientSessionScope(): UwbClientSessionScope {
return createClientSessionScope(false)
}
override suspend fun controleeSessionScope(): UwbControleeSessionScope {
return createClientSessionScope(false) as UwbControleeSessionScope
}
override suspend fun controllerSessionScope(): UwbControllerSessionScope {
return createClientSessionScope(true) as UwbControllerSessionScope
}
private suspend fun createClientSessionScope(isController: Boolean): UwbClientSessionScope {
checkSystemFeature(context)
val hasGmsCore = GoogleApiAvailability.getInstance()
.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS
return if (hasGmsCore) createGmsClientSessionScope(isController)
else createAospClientSessionScope(isController)
}
private suspend fun createGmsClientSessionScope(isController: Boolean): UwbClientSessionScope {
Log.i(TAG, "Creating Gms Client session scope")
val uwbClient = if (isController)
Nearby.getUwbControllerClient(context) else Nearby.getUwbControleeClient(context)
try {
val nearbyLocalAddress = uwbClient.localAddress.await()
val nearbyRangingCapabilities = uwbClient.rangingCapabilities.await()
val localAddress = UwbAddress(nearbyLocalAddress.address)
val rangingCapabilities = RangingCapabilities(
nearbyRangingCapabilities.supportsDistance(),
nearbyRangingCapabilities.supportsAzimuthalAngle(),
nearbyRangingCapabilities.supportsElevationAngle())
return if (isController) {
val uwbComplexChannel = uwbClient.complexChannel.await()
UwbControllerSessionScopeImpl(
uwbClient,
rangingCapabilities,
localAddress,
UwbComplexChannel(uwbComplexChannel.channel, uwbComplexChannel.preambleIndex)
)
} else {
UwbControleeSessionScopeImpl(
uwbClient,
rangingCapabilities,
localAddress
)
}
} catch (e: ApiException) {
handleApiException(e)
throw RuntimeException("Unexpected error. This indicates that the library is not " +
"up-to-date with the service backend.")
}
}
private fun createAospClientSessionScope(isController: Boolean): UwbClientSessionScope {
Log.i(TAG, "Creating Aosp Client session scope")
val uwbClient = if (isController)
iUwb?.controllerClient else iUwb?.controleeClient
if (uwbClient == null) {
Log.e(TAG, "Failed to get UwbClient. AOSP backend is not available.")
}
try {
val aospLocalAddress = uwbClient!!.localAddress
val aospRangingCapabilities = uwbClient.rangingCapabilities
val localAddress = aospLocalAddress?.address?.let { UwbAddress(it) }
val rangingCapabilities = aospRangingCapabilities?.let {
RangingCapabilities(
it.supportsDistance,
it.supportsAzimuthalAngle,
it.supportsElevationAngle)
}
return if (isController) {
val uwbComplexChannel = uwbClient.complexChannel
UwbControllerSessionScopeAospImpl(
uwbClient,
rangingCapabilities!!,
localAddress!!,
UwbComplexChannel(uwbComplexChannel!!.channel, uwbComplexChannel.preambleIndex)
)
} else {
UwbControleeSessionScopeAospImpl(
uwbClient,
rangingCapabilities!!,
localAddress!!
)
}
} catch (e: Exception) {
throw e
}
}
} | core/uwb/uwb/src/main/java/androidx/core/uwb/impl/UwbManagerImpl.kt | 474632345 |
/*
* 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.benchmark.gradle
import org.gradle.api.DefaultTask
import org.gradle.api.logging.LogLevel
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.property
import org.gradle.work.DisableCachingByDefault
@Suppress("UnstableApiUsage")
@DisableCachingByDefault(
because = "UnlockClocks affects device state, and may be modified/reset outside of this task"
)
open class UnlockClocksTask : DefaultTask() {
init {
group = "Android"
description = "unlocks clocks of device by rebooting"
}
@Input
val adbPath: Property<String> = project.objects.property()
@TaskAction
fun exec() {
val adb = Adb(adbPath.get(), logger)
project.logger.log(LogLevel.LIFECYCLE, "Rebooting device to reset clocks")
adb.execSync("reboot")
}
}
| benchmark/gradle-plugin/src/main/kotlin/androidx/benchmark/gradle/UnlockClocksTask.kt | 699999895 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.collection
import androidx.collection.internal.EMPTY_INTS
import androidx.collection.internal.EMPTY_OBJECTS
import androidx.collection.internal.binarySearch
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
private const val DEBUG = false
private const val TAG = "ArrayMap"
/**
* Attempt to spot concurrent modifications to this data structure.
*
* It's best-effort, but any time we can throw something more diagnostic than an
* ArrayIndexOutOfBoundsException deep in the ArrayMap internals it's going to
* save a lot of development time.
*
* Good times to look for CME include after any allocArrays() call and at the end of
* functions that change mSize (put/remove/clear).
*/
private const val CONCURRENT_MODIFICATION_EXCEPTIONS = true
/**
* The minimum amount by which the capacity of a ArrayMap will increase.
* This is tuned to be relatively space-efficient.
*/
private const val BASE_SIZE = 4
/**
* Base implementation of [ArrayMap][androidx.collection.ArrayMap] that doesn't include any standard
* Java container API interoperability. These features are generally heavier-weight ways
* to interact with the container, so discouraged, but they can be useful to make it
* easier to use as a drop-in replacement for HashMap. If you don't need them, this
* class can be preferable since it doesn't bring in any of the implementation of those
* APIs, allowing that code to be stripped by ProGuard.
*
* @constructor Create a new [SimpleArrayMap] with a given initial capacity. The default capacity of
* an array map is 0, and will grow once items are added to it.
*/
public open class SimpleArrayMap<K, V> @JvmOverloads public constructor(capacity: Int = 0) {
private var hashes: IntArray = when (capacity) {
0 -> EMPTY_INTS
else -> IntArray(capacity)
}
private var array: Array<Any?> = when (capacity) {
0 -> EMPTY_OBJECTS
else -> arrayOfNulls<Any?>(capacity shl 1)
}
private var size: Int = 0
/**
* Create a new [SimpleArrayMap] with the mappings from the given [map].
*/
public constructor(map: SimpleArrayMap<out K, out V>?) : this() {
if (map != null) {
this.putAll(map)
}
}
/**
* Returns the index of a key in the set, given its [hashCode]. This is a helper for the
* non-null case of [indexOfKey].
*
* @param key The key to search for.
* @param hash Pre-computed [hashCode] of [key].
* @return Returns the index of the key if it exists, else a negative integer.
*/
private fun indexOf(key: K, hash: Int): Int {
val n = size
// Important fast case: if nothing is in here, nothing to look for.
if (n == 0) {
return 0.inv()
}
val index = binarySearch(hashes, n, hash)
// If the hash code wasn't found, then we have no entry for this key.
if (index < 0) {
return index
}
// If the key at the returned index matches, that's what we want.
if (key == array[index shl 1]) {
return index
}
// Search for a matching key after the index.
var end: Int = index + 1
while (end < n && hashes[end] == hash) {
if (key == array[end shl 1]) return end
end++
}
// Search for a matching key before the index.
var i = index - 1
while (i >= 0 && hashes[i] == hash) {
if (key == array[i shl 1]) {
return i
}
i--
}
// Key not found -- return negative value indicating where a
// new entry for this key should go. We use the end of the
// hash chain to reduce the number of array entries that will
// need to be copied when inserting.
return end.inv()
}
private fun indexOfNull(): Int {
val n = size
// Important fast case: if nothing is in here, nothing to look for.
if (n == 0) {
return 0.inv()
}
val index = binarySearch(hashes, n, 0)
// If the hash code wasn't found, then we have no entry for this key.
if (index < 0) {
return index
}
// If the key at the returned index matches, that's what we want.
if (null == array[index shl 1]) {
return index
}
// Search for a matching key after the index.
var end: Int = index + 1
while (end < n && hashes[end] == 0) {
if (null == array[end shl 1]) return end
end++
}
// Search for a matching key before the index.
var i = index - 1
while (i >= 0 && hashes[i] == 0) {
if (null == array[i shl 1]) return i
i--
}
// Key not found -- return negative value indicating where a
// new entry for this key should go. We use the end of the
// hash chain to reduce the number of array entries that will
// need to be copied when inserting.
return end.inv()
}
/**
* Make the array map empty. All storage is released.
*
* @throws ConcurrentModificationException if it was detected that this [SimpleArrayMap] was
* written to while this operation was running.
*/
public open fun clear() {
if (size > 0) {
hashes = EMPTY_INTS
array = EMPTY_OBJECTS
size = 0
}
@Suppress("KotlinConstantConditions")
if (CONCURRENT_MODIFICATION_EXCEPTIONS && size > 0) {
throw ConcurrentModificationException()
}
}
/**
* Ensure the array map can hold at least [minimumCapacity] items.
*
* @throws ConcurrentModificationException if it was detected that this [SimpleArrayMap] was
* written to while this operation was running.
*/
public open fun ensureCapacity(minimumCapacity: Int) {
val osize = size
if (hashes.size < minimumCapacity) {
hashes = hashes.copyOf(minimumCapacity)
array = array.copyOf(minimumCapacity * 2)
}
if (CONCURRENT_MODIFICATION_EXCEPTIONS && size != osize) {
throw ConcurrentModificationException()
}
}
/**
* Check whether a key exists in the array.
*
* @param key The key to search for.
* @return Returns `true` if the key exists, else `false`.
*/
public open fun containsKey(key: K): Boolean {
return indexOfKey(key) >= 0
}
/**
* Returns the index of a key in the set.
*
* @param key The key to search for.
* @return Returns the index of the key if it exists, else a negative integer.
*/
public open fun indexOfKey(key: K): Int = when (key) {
null -> indexOfNull()
else -> indexOf(key, key.hashCode())
}
// @RestrictTo is required since internal is implemented as public with name mangling in Java
// and we are overriding the name mangling to make it callable from a Java subclass in this
// package (ArrayMap).
@JvmName("__restricted\$indexOfValue")
internal fun indexOfValue(value: V): Int {
val n = size * 2
val array = array
if (value == null) {
var i = 1
while (i < n) {
if (array[i] == null) {
return i shr 1
}
i += 2
}
} else {
var i = 1
while (i < n) {
if (value == array[i]) {
return i shr 1
}
i += 2
}
}
return -1
}
/**
* Check whether a value exists in the array. This requires a linear search
* through the entire array.
*
* @param value The value to search for.
* @return Returns `true` if the value exists, else `false`.
*/
public open fun containsValue(value: V): Boolean {
return indexOfValue(value) >= 0
}
/**
* Retrieve a value from the array.
*
* @param key The key of the value to retrieve.
* @return Returns the value associated with the given key, or `null` if there is no such key.
*/
public open operator fun get(key: K): V? {
return getOrDefaultInternal(key, null)
}
/**
* Retrieve a value from the array, or [defaultValue] if there is no mapping for the key.
*
* @param key The key of the value to retrieve.
* @param defaultValue The default mapping of the key
* @return Returns the value associated with the given key, or [defaultValue] if there is no
* mapping for the key.
*/
// Unfortunately key must stay of type Any? otherwise it will not register as an override of
// Java's Map interface, which is necessary since ArrayMap is written in Java and implements
// both Map and SimpleArrayMap.
public open fun getOrDefault(key: Any?, defaultValue: V): V {
return getOrDefaultInternal(key, defaultValue)
}
@Suppress("NOTHING_TO_INLINE")
private inline fun <T : V?> getOrDefaultInternal(key: Any?, defaultValue: T): T {
@Suppress("UNCHECKED_CAST")
val index = indexOfKey(key as K)
@Suppress("UNCHECKED_CAST")
return when {
index >= 0 -> array[(index shl 1) + 1] as T
else -> defaultValue
}
}
/**
* Return the key at the given index in the array.
*
* @param index The desired index, must be between 0 and [size]-1 (inclusive).
* @return Returns the key stored at the given index.
* @throws IllegalArgumentException if [index] is not between 0 and [size]-1
*/
public open fun keyAt(index: Int): K {
require(index in 0 until size) {
"Expected index to be within 0..size()-1, but was $index"
}
@Suppress("UNCHECKED_CAST")
return array[index shl 1] as K
}
/**
* Return the value at the given index in the array.
*
* @param index The desired index, must be between 0 and [size]-1 (inclusive).
* @return Returns the value stored at the given index.
* @throws IllegalArgumentException if [index] is not between 0 and [size]-1
*/
public open fun valueAt(index: Int): V {
require(index in 0 until size) {
"Expected index to be within 0..size()-1, but was $index"
}
@Suppress("UNCHECKED_CAST")
return array[(index shl 1) + 1] as V
}
/**
* Set the value at a given index in the array.
*
* @param index The desired index, must be between 0 and [size]-1 (inclusive).
* @param value The new value to store at this index.
* @return Returns the previous value at the given index.
* @throws IllegalArgumentException if [index] is not between 0 and [size]-1
*/
public open fun setValueAt(index: Int, value: V): V {
require(index in 0 until size) {
"Expected index to be within 0..size()-1, but was $index"
}
val indexInArray = (index shl 1) + 1
@Suppress("UNCHECKED_CAST")
val old = array[indexInArray] as V
array[indexInArray] = value
return old
}
/**
* Return `true` if the array map contains no items.
*/
public open fun isEmpty(): Boolean = size <= 0
/**
* Add a new value to the array map.
*
* @param key The key under which to store the value. If this key already exists in the array,
* its value will be replaced.
* @param value The value to store for the given key.
* @return Returns the old value that was stored for the given key, or `null` if there
* was no such key.
* @throws ConcurrentModificationException if it was detected that this [SimpleArrayMap] was
* written to while this operation was running.
*/
public open fun put(key: K, value: V): V? {
val osize = size
val hash: Int = key?.hashCode() ?: 0
var index: Int = key?.let { indexOf(it, hash) } ?: indexOfNull()
if (index >= 0) {
index = (index shl 1) + 1
@Suppress("UNCHECKED_CAST")
val old = array[index] as V?
array[index] = value
return old
}
index = index.inv()
if (osize >= hashes.size) {
val n = when {
osize >= BASE_SIZE * 2 -> osize + (osize shr 1)
osize >= BASE_SIZE -> BASE_SIZE * 2
else -> BASE_SIZE
}
if (DEBUG) {
println("$TAG put: grow from ${hashes.size} to $n")
}
hashes = hashes.copyOf(n)
array = array.copyOf(n shl 1)
if (CONCURRENT_MODIFICATION_EXCEPTIONS && osize != size) {
throw ConcurrentModificationException()
}
}
if (index < osize) {
if (DEBUG) {
println("$TAG put: move $index-${osize - index} to ${index + 1}")
}
hashes.copyInto(hashes, index + 1, index, osize)
array.copyInto(array, (index + 1) shl 1, index shl 1, size shl 1)
}
if (CONCURRENT_MODIFICATION_EXCEPTIONS && (osize != size || index >= hashes.size)) {
throw ConcurrentModificationException()
}
hashes[index] = hash
array[index shl 1] = key
array[(index shl 1) + 1] = value
size++
return null
}
/**
* Perform a [put] of all key/value pairs in [map]
*
* @param map The array whose contents are to be retrieved.
*/
public open fun putAll(map: SimpleArrayMap<out K, out V>) {
val n = map.size
ensureCapacity(size + n)
if (size == 0) {
if (n > 0) {
map.hashes.copyInto(
destination = hashes,
destinationOffset = 0,
startIndex = 0,
endIndex = n
)
map.array.copyInto(
destination = array,
destinationOffset = 0,
startIndex = 0,
endIndex = n shl 1
)
size = n
}
} else {
for (i in 0 until n) {
put(map.keyAt(i), map.valueAt(i))
}
}
}
/**
* Add a new value to the array map only if the key does not already have a value or it is
* mapped to `null`.
*
* @param key The key under which to store the value.
* @param value The value to store for the given key.
* @return Returns the value that was stored for the given key, or `null` if there was no such
* key.
*/
public open fun putIfAbsent(key: K, value: V): V? {
var mapValue = get(key)
if (mapValue == null) {
mapValue = put(key, value)
}
return mapValue
}
/**
* Remove an existing key from the array map.
*
* @param key The key of the mapping to remove.
* @return Returns the value that was stored under the key, or `null` if there was no such key.
*/
public open fun remove(key: K): V? {
val index = indexOfKey(key)
return if (index >= 0) {
removeAt(index)
} else null
}
/**
* Remove an existing key from the array map only if it is currently mapped to [value].
*
* @param key The key of the mapping to remove.
* @param value The value expected to be mapped to the key.
* @return Returns `true` if the mapping was removed.
*/
public open fun remove(key: K, value: V): Boolean {
val index = indexOfKey(key)
if (index >= 0) {
val mapValue = valueAt(index)
if (value == mapValue) {
removeAt(index)
return true
}
}
return false
}
/**
* Remove the key/value mapping at the given index.
*
* @param index The desired index, must be between 0 and [size]-1 (inclusive).
* @return Returns the value that was stored at this index.
* @throws ConcurrentModificationException if it was detected that this [SimpleArrayMap] was
* written to while this operation was running.
* @throws IllegalArgumentException if [index] is not between 0 and [size]-1
*/
public open fun removeAt(index: Int): V {
require(index in 0 until size) {
"Expected index to be within 0..size()-1, but was $index"
}
val old = array[(index shl 1) + 1]
val osize = size
if (osize <= 1) {
// Now empty.
if (DEBUG) {
println("$TAG remove: shrink from ${hashes.size} to 0")
}
clear()
} else {
val nsize = osize - 1
if (hashes.size > (BASE_SIZE * 2) && osize < hashes.size / 3) {
// Shrunk enough to reduce size of arrays. We don't allow it to
// shrink smaller than (BASE_SIZE*2) to avoid flapping between
// that and BASE_SIZE.
val n = when {
osize > (BASE_SIZE * 2) -> osize + (osize shr 1)
else -> BASE_SIZE * 2
}
if (DEBUG) {
println("$TAG remove: shrink from ${hashes.size} to $n")
}
val ohashes = hashes
val oarray: Array<Any?> = array
hashes = hashes.copyOf(n)
array = array.copyOf(n shl 1)
if (CONCURRENT_MODIFICATION_EXCEPTIONS && osize != size) {
throw ConcurrentModificationException()
}
if (index > 0) {
if (DEBUG) {
println("$TAG remove: copy from 0-$index to 0")
}
ohashes.copyInto(
destination = hashes,
destinationOffset = 0,
startIndex = 0,
endIndex = index
)
oarray.copyInto(
destination = array,
destinationOffset = 0,
startIndex = 0,
endIndex = index shl 1
)
}
if (index < nsize) {
if (DEBUG) {
println("$TAG remove: copy from ${index + 1}-$nsize to $index")
}
ohashes.copyInto(
destination = hashes,
destinationOffset = index,
startIndex = index + 1,
endIndex = nsize + 1
)
oarray.copyInto(
destination = array,
destinationOffset = index shl 1,
startIndex = (index + 1) shl 1,
endIndex = (nsize + 1) shl 1
)
}
} else {
if (index < nsize) {
if (DEBUG) {
println("$TAG remove: move ${index + 1}-$nsize to $index")
}
hashes.copyInto(
destination = hashes,
destinationOffset = index,
startIndex = index + 1,
endIndex = nsize + 1
)
array.copyInto(
destination = array,
destinationOffset = index shl 1,
startIndex = (index + 1) shl 1,
endIndex = (nsize + 1) shl 1
)
}
array[nsize shl 1] = null
array[(nsize shl 1) + 1] = null
}
if (CONCURRENT_MODIFICATION_EXCEPTIONS && osize != size) {
throw ConcurrentModificationException()
}
size = nsize
}
@Suppress("UNCHECKED_CAST")
return old as V
}
/**
* Replace the mapping for [key] only if it is already mapped to a value.
*
* @param key The key of the mapping to replace.
* @param value The value to store for the given key.
* @return Returns the previous mapped value or `null`.
*/
public open fun replace(key: K, value: V): V? {
val index = indexOfKey(key)
return when {
index >= 0 -> setValueAt(index, value)
else -> null
}
}
/**
* Replace the mapping for [key] only if it is already mapped to [oldValue].
*
* @param key The key of the mapping to replace.
* @param oldValue The value expected to be mapped to the key.
* @param newValue The value to store for the given key.
* @return Returns `true` if the value was replaced.
*/
public open fun replace(key: K, oldValue: V, newValue: V): Boolean {
val index = indexOfKey(key)
if (index >= 0) {
val mapValue = valueAt(index)
if (oldValue == mapValue) {
setValueAt(index, newValue)
return true
}
}
return false
}
/**
* Return the number of items in this array map.
*/
public open fun size(): Int {
return size
}
/**
* This implementation returns `false` if the object is not a [Map] or
* [SimpleArrayMap], or if the maps have different sizes. Otherwise, for each
* key in this map, values of both maps are compared. If the values for any
* key are not equal, the method returns false, otherwise it returns `true`.
*/
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
try {
if (other is SimpleArrayMap<*, *>) {
if (size() != other.size()) {
return false
}
@Suppress("UNCHECKED_CAST")
val otherSimpleArrayMap = other as SimpleArrayMap<Any?, Any?>
for (i in 0 until size) {
val key = keyAt(i)
val mine = valueAt(i)
// TODO use index-based ops for this
val theirs = otherSimpleArrayMap[key]
if (mine == null) {
if (theirs != null || !otherSimpleArrayMap.containsKey(key)) {
return false
}
} else if (mine != theirs) {
return false
}
}
return true
} else if (other is Map<*, *>) {
if (size() != other.size) {
return false
}
for (i in 0 until size) {
val key = keyAt(i)
val mine = valueAt(i)
val theirs = other[key]
if (mine == null) {
if (theirs != null || !other.containsKey(key)) {
return false
}
} else if (mine != theirs) {
return false
}
}
return true
}
} catch (ignored: NullPointerException) {
} catch (ignored: ClassCastException) {
}
return false
}
override fun hashCode(): Int {
val hashes = hashes
val array = array
var result = 0
var i = 0
var v = 1
val s = size
while (i < s) {
val value = array[v]
result += hashes[i] xor (value?.hashCode() ?: 0)
i++
v += 2
}
return result
}
/**
* Returns a string representation of the object.
*
* This implementation composes a string by iterating over its mappings. If
* this map contains itself as a key or a value, the string "(this Map)"
* will appear in its place.
*/
override fun toString(): String {
if (isEmpty()) {
return "{}"
}
return buildString(size * 28) {
append('{')
for (i in 0 until size) {
if (i > 0) {
append(", ")
}
val key = keyAt(i)
if (key !== this) {
append(key)
} else {
append("(this Map)")
}
append('=')
val value = valueAt(i)
if (value !== this) {
append(value)
} else {
append("(this Map)")
}
}
append('}')
}
}
}
| collection/collection/src/commonMain/kotlin/androidx/collection/SimpleArrayMap.kt | 4190743631 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.semantics.SemanticsNode
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpRect
import androidx.compose.ui.unit.height
import androidx.compose.ui.unit.isUnspecified
import androidx.compose.ui.unit.toSize
import androidx.compose.ui.unit.width
import kotlin.math.abs
/**
* Asserts that the layout of this node has width equal to [expectedWidth].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertWidthIsEqualTo(expectedWidth: Dp): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.width.assertIsEqualTo(expectedWidth, "width")
}
}
/**
* Asserts that the layout of this node has height equal to [expectedHeight].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertHeightIsEqualTo(expectedHeight: Dp): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.height.assertIsEqualTo(expectedHeight, "height")
}
}
/**
* Asserts that the touch bounds of this node has width equal to [expectedWidth].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertTouchWidthIsEqualTo(
expectedWidth: Dp
): SemanticsNodeInteraction {
return withTouchBoundsInRoot {
it.width.assertIsEqualTo(expectedWidth, "width")
}
}
/**
* Asserts that the touch bounds of this node has height equal to [expectedHeight].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertTouchHeightIsEqualTo(
expectedHeight: Dp
): SemanticsNodeInteraction {
return withTouchBoundsInRoot {
it.height.assertIsEqualTo(expectedHeight, "height")
}
}
/**
* Asserts that the layout of this node has width that is greater than or equal to
* [expectedMinWidth].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertWidthIsAtLeast(expectedMinWidth: Dp): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.width.assertIsAtLeast(expectedMinWidth, "width")
}
}
/**
* Asserts that the layout of this node has height that is greater than or equal to
* [expectedMinHeight].
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertHeightIsAtLeast(
expectedMinHeight: Dp
): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.height.assertIsAtLeast(expectedMinHeight, "height")
}
}
/**
* Asserts that the layout of this node has position in the root composable that is equal to the
* given position.
*
* @param expectedLeft The left (x) position to assert.
* @param expectedTop The top (y) position to assert.
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertPositionInRootIsEqualTo(
expectedLeft: Dp,
expectedTop: Dp
): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.left.assertIsEqualTo(expectedLeft, "left")
it.top.assertIsEqualTo(expectedTop, "top")
}
}
/**
* Asserts that the layout of this node has the top position in the root composable that is equal to
* the given position.
*
* @param expectedTop The top (y) position to assert.
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertTopPositionInRootIsEqualTo(
expectedTop: Dp
): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.top.assertIsEqualTo(expectedTop, "top")
}
}
/**
* Asserts that the layout of this node has the left position in the root composable that is
* equal to the given position.
*
* @param expectedLeft The left (x) position to assert.
*
* @throws AssertionError if comparison fails.
*/
fun SemanticsNodeInteraction.assertLeftPositionInRootIsEqualTo(
expectedLeft: Dp
): SemanticsNodeInteraction {
return withUnclippedBoundsInRoot {
it.left.assertIsEqualTo(expectedLeft, "left")
}
}
/**
* Returns the bounds of the layout of this node. The bounds are relative to the root composable.
*/
fun SemanticsNodeInteraction.getUnclippedBoundsInRoot(): DpRect {
lateinit var bounds: DpRect
withUnclippedBoundsInRoot {
bounds = it
}
return bounds
}
/**
* Returns the bounds of the layout of this node as clipped to the root. The bounds are relative to
* the root composable.
*/
fun SemanticsNodeInteraction.getBoundsInRoot(): DpRect {
val node = fetchSemanticsNode("Failed to retrieve bounds of the node.")
return with(node.layoutInfo.density) {
node.boundsInRoot.let {
DpRect(it.left.toDp(), it.top.toDp(), it.right.toDp(), it.bottom.toDp())
}
}
}
/**
* Returns the position of an [alignment line][AlignmentLine], or [Dp.Unspecified] if the line is
* not provided.
*/
fun SemanticsNodeInteraction.getAlignmentLinePosition(alignmentLine: AlignmentLine): Dp {
return withDensity {
val pos = it.getAlignmentLinePosition(alignmentLine)
if (pos == AlignmentLine.Unspecified) {
Dp.Unspecified
} else {
pos.toDp()
}
}
}
private fun <R> SemanticsNodeInteraction.withDensity(
operation: Density.(SemanticsNode) -> R
): R {
val node = fetchSemanticsNode("Failed to retrieve density for the node.")
val density = node.layoutInfo.density
return operation.invoke(density, node)
}
private fun SemanticsNodeInteraction.withUnclippedBoundsInRoot(
assertion: (DpRect) -> Unit
): SemanticsNodeInteraction {
val node = fetchSemanticsNode("Failed to retrieve bounds of the node.")
val bounds = with(node.layoutInfo.density) {
node.unclippedBoundsInRoot.let {
DpRect(it.left.toDp(), it.top.toDp(), it.right.toDp(), it.bottom.toDp())
}
}
assertion.invoke(bounds)
return this
}
private fun SemanticsNodeInteraction.withTouchBoundsInRoot(
assertion: (DpRect) -> Unit
): SemanticsNodeInteraction {
val node = fetchSemanticsNode("Failed to retrieve bounds of the node.")
val bounds = with(node.layoutInfo.density) {
node.touchBoundsInRoot.let {
DpRect(it.left.toDp(), it.top.toDp(), it.right.toDp(), it.bottom.toDp())
}
}
assertion.invoke(bounds)
return this
}
private val SemanticsNode.unclippedBoundsInRoot: Rect
get() {
return if (layoutInfo.isPlaced) {
Rect(positionInRoot, size.toSize())
} else {
Dp.Unspecified.value.let { Rect(it, it, it, it) }
}
}
/**
* Returns if this value is equal to the [reference], within a given [tolerance]. If the
* reference value is [Float.NaN], [Float.POSITIVE_INFINITY] or [Float.NEGATIVE_INFINITY], this
* only returns true if this value is exactly the same (tolerance is disregarded).
*/
private fun Dp.isWithinTolerance(reference: Dp, tolerance: Dp): Boolean {
return when {
reference.isUnspecified -> this.isUnspecified
reference.value.isInfinite() -> this.value == reference.value
else -> abs(this.value - reference.value) <= tolerance.value
}
}
/**
* Asserts that this value is equal to the given [expected] value.
*
* Performs the comparison with the given [tolerance] or the default one if none is provided. It is
* recommended to use tolerance when comparing positions and size coming from the framework as there
* can be rounding operation performed by individual layouts so the values can be slightly off from
* the expected ones.
*
* @param expected The expected value to which this one should be equal to.
* @param subject Used in the error message to identify which item this assertion failed on.
* @param tolerance The tolerance within which the values should be treated as equal.
*
* @throws AssertionError if comparison fails.
*/
fun Dp.assertIsEqualTo(expected: Dp, subject: String, tolerance: Dp = Dp(.5f)) {
if (!isWithinTolerance(expected, tolerance)) {
// Comparison failed, report the error in DPs
throw AssertionError(
"Actual $subject is $this, expected $expected (tolerance: $tolerance)"
)
}
}
/**
* Asserts that this value is greater than or equal to the given [expected] value.
*
* Performs the comparison with the given [tolerance] or the default one if none is provided. It is
* recommended to use tolerance when comparing positions and size coming from the framework as there
* can be rounding operation performed by individual layouts so the values can be slightly off from
* the expected ones.
*
* @param expected The expected value to which this one should be greater than or equal to.
* @param subject Used in the error message to identify which item this assertion failed on.
* @param tolerance The tolerance within which the values should be treated as equal.
*
* @throws AssertionError if comparison fails.
*/
private fun Dp.assertIsAtLeast(expected: Dp, subject: String, tolerance: Dp = Dp(.5f)) {
if (!(isWithinTolerance(expected, tolerance) || (!isUnspecified && this > expected))) {
// Comparison failed, report the error in DPs
throw AssertionError(
"Actual $subject is $this, expected at least $expected (tolerance: $tolerance)"
)
}
}
| compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/BoundsAssertions.kt | 3794573927 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.core.imagecapture
import android.graphics.Bitmap
import androidx.camera.core.imagecapture.Utils.CAMERA_CAPTURE_RESULT
import androidx.camera.core.imagecapture.Utils.CROP_RECT
import androidx.camera.core.imagecapture.Utils.HEIGHT
import androidx.camera.core.imagecapture.Utils.ROTATION_DEGREES
import androidx.camera.core.imagecapture.Utils.SENSOR_TO_BUFFER
import androidx.camera.core.imagecapture.Utils.TIMESTAMP
import androidx.camera.core.imagecapture.Utils.WIDTH
import androidx.camera.core.processing.Packet
import androidx.camera.testing.ExifUtil
import androidx.camera.testing.TestImageUtil
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth
import java.nio.ByteBuffer
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented tests for [RgbaImageProxy].
*/
@SmallTest
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = 21)
class RgbaImageProxyDeviceTest {
@Test
fun createImageFromBitmap_verifyResult() {
// Arrange.
val bitmap = TestImageUtil.createBitmap(WIDTH, HEIGHT)
// Act.
val image = RgbaImageProxy(
Packet.of(
bitmap,
ExifUtil.createExif(TestImageUtil.createJpegBytes(WIDTH, HEIGHT)),
CROP_RECT,
ROTATION_DEGREES,
SENSOR_TO_BUFFER,
CAMERA_CAPTURE_RESULT
)
)
// Assert.
val restoredBitmap = Bitmap.createBitmap(image.width, image.height, Bitmap.Config.ARGB_8888)
restoredBitmap.copyPixelsFromBuffer(image.planes[0].buffer)
Truth.assertThat(TestImageUtil.getAverageDiff(bitmap, restoredBitmap)).isEqualTo(0)
Truth.assertThat(image.image).isNull()
Truth.assertThat(image.width).isEqualTo(WIDTH)
Truth.assertThat(image.height).isEqualTo(HEIGHT)
Truth.assertThat(image.cropRect).isEqualTo(CROP_RECT)
Truth.assertThat(image.imageInfo.rotationDegrees).isEqualTo(ROTATION_DEGREES)
Truth.assertThat(image.imageInfo.sensorToBufferTransformMatrix).isEqualTo(SENSOR_TO_BUFFER)
Truth.assertThat(image.imageInfo.timestamp).isEqualTo(TIMESTAMP)
}
@Test
fun createImageFromByteBuffer_verifyResult() {
// Arrange.
val bitmap = TestImageUtil.createBitmap(WIDTH, HEIGHT)
val byteBuffer = ByteBuffer.allocateDirect(bitmap.allocationByteCount)
bitmap.copyPixelsToBuffer(byteBuffer)
// Act.
val image = RgbaImageProxy(
byteBuffer,
4,
bitmap.width,
bitmap.height,
CROP_RECT,
ROTATION_DEGREES,
SENSOR_TO_BUFFER,
TIMESTAMP
)
// Assert.
val restoredBitmap = image.createBitmap()
Truth.assertThat(TestImageUtil.getAverageDiff(bitmap, restoredBitmap)).isEqualTo(0)
Truth.assertThat(image.width).isEqualTo(WIDTH)
Truth.assertThat(image.height).isEqualTo(HEIGHT)
Truth.assertThat(image.cropRect).isEqualTo(CROP_RECT)
Truth.assertThat(image.imageInfo.rotationDegrees).isEqualTo(ROTATION_DEGREES)
Truth.assertThat(image.imageInfo.sensorToBufferTransformMatrix).isEqualTo(SENSOR_TO_BUFFER)
Truth.assertThat(image.imageInfo.timestamp).isEqualTo(TIMESTAMP)
}
} | camera/camera-core/src/androidTest/java/androidx/camera/core/imagecapture/RgbaImageProxyDeviceTest.kt | 1368493689 |
// 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.codeInspection.incorrectFormatting
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.lang.LangBundle
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
import kotlin.math.abs
internal class IncorrectFormattingInspectionHelper(
private val formattingChanges: FormattingChanges,
val file: PsiFile,
val document: Document,
val manager: InspectionManager,
val isOnTheFly: Boolean) {
fun createAllReports(): Array<ProblemDescriptor>? {
val mismatches = formattingChanges.mismatches
if (mismatches.isEmpty()) return null
val result = arrayListOf<ProblemDescriptor>()
val (indentMismatches, inLineMismatches) = classifyMismatches(mismatches)
result += indentMismatchDescriptors(indentMismatches)
result += inLineMismatchDescriptors(inLineMismatches)
return result
.takeIf { it.isNotEmpty() }
?.toTypedArray()
}
fun createGlobalReport() =
manager.createProblemDescriptor(
file,
LangBundle.message("inspection.incorrect.formatting.global.problem.descriptor", file.name),
arrayOf(ReformatQuickFix, ShowDetailedReportIntention),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
false
)
private fun isIndentMismatch(mismatch: FormattingChanges.WhitespaceMismatch): Boolean =
mismatch.preFormatRange.startOffset.let {
it == 0 || document.text[it] == '\n'
}
// Distinguish between indent mismatches and others (aka in-line)
private fun classifyMismatches(mismatches: List<FormattingChanges.WhitespaceMismatch>)
: Pair<List<FormattingChanges.WhitespaceMismatch>, List<FormattingChanges.WhitespaceMismatch>> {
val indentMismatch = mismatches.groupBy { isIndentMismatch(it) }
return Pair(
indentMismatch[true] ?: emptyList(),
indentMismatch[false] ?: emptyList()
)
}
// Start line mismatches, "indents", grouped by consequent lines
private fun indentMismatchDescriptors(indentMismatches: List<FormattingChanges.WhitespaceMismatch>) =
sequence {
val currentBlock = arrayListOf<FormattingChanges.WhitespaceMismatch>()
indentMismatches.forEach { mismatch ->
currentBlock.lastOrNull()?.let { prev ->
if (!document.areRangesAdjacent(prev.preFormatRange, mismatch.preFormatRange)) {
yieldAll(createIndentProblemDescriptors(currentBlock))
currentBlock.clear()
}
}
currentBlock.add(mismatch)
}
yieldAll(createIndentProblemDescriptors(currentBlock))
}
private fun createReplacementString(mismatch: FormattingChanges.WhitespaceMismatch): String =
mismatch.postFormatRange.let {
formattingChanges.postFormatText.substring(it.startOffset, it.endOffset)
}
private fun TextRange.excludeLeadingLinefeed(): TextRange =
if (!isEmpty && document.text[startOffset] == '\n') TextRange(startOffset + 1, endOffset) else this
private fun createMessage(mismatch: FormattingChanges.WhitespaceMismatch) =
if (mismatch.preFormatRange.isEmpty) {
LangBundle.message("inspection.incorrect.formatting.wrong.whitespace.problem.descriptor.missing.whitespace")
}
else {
LangBundle.message("inspection.incorrect.formatting.wrong.whitespace.problem.descriptor.incorrect.whitespace")
}
private fun createIndentProblemDescriptors(mismatches: ArrayList<FormattingChanges.WhitespaceMismatch>) =
sequence {
val blockFix = ReplaceQuickFix(mismatches.map { document.createRangeMarker(it.preFormatRange) to createReplacementString(it) })
mismatches.forEach {
yield(
createProblemDescriptor(
it.preFormatRange.excludeLeadingLinefeed(),
createMessage(it),
blockFix, ReformatQuickFix, HideDetailedReportIntention
)
)
}
}
// In-line mismatches, grouped by line
private fun inLineMismatchDescriptors(inLineMismatches: List<FormattingChanges.WhitespaceMismatch>) =
sequence {
yieldAll(
inLineMismatches
.groupBy { document.getLineNumber(it.preFormatRange.startOffset) }
.flatMap { (_, mismatches) ->
val commonFix = ReplaceQuickFix(mismatches.map { document.createRangeMarker(it.preFormatRange) to createReplacementString(it) })
mismatches.map {
createProblemDescriptor(
it.preFormatRange,
createMessage(it),
commonFix, ReformatQuickFix, HideDetailedReportIntention
)
}
}
)
}
private fun createProblemDescriptor(range: TextRange, @Nls message: String, vararg fixes: LocalQuickFix): ProblemDescriptor {
val element = file.findElementAt(range.startOffset)
val targetElement = element ?: file
val targetRange = element
?.textRange
?.intersection(range)
?.shiftLeft(element.textRange.startOffset) // relative range
?: range // original range if no element
return manager.createProblemDescriptor(
targetElement,
targetRange,
message,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
*fixes
)
}
}
private fun Document.areRangesAdjacent(first: TextRange, second: TextRange): Boolean {
if (abs(getLineNumber(first.startOffset) - getLineNumber(second.endOffset - 1)) < 2) return true
if (abs(getLineNumber(second.startOffset) - getLineNumber(first.endOffset - 1)) < 2) return true
return false
} | platform/lang-impl/src/com/intellij/codeInspection/incorrectFormatting/IncorrectFormattingInspectionHelper.kt | 2677418526 |
package com.intellij.ide.customize.transferSettings.providers.vsmac
import com.intellij.icons.AllIcons
import com.intellij.ide.customize.transferSettings.models.IdeVersion
import com.intellij.ide.customize.transferSettings.providers.DefaultImportPerformer
import com.intellij.ide.customize.transferSettings.providers.TransferSettingsProvider
import com.intellij.ide.customize.transferSettings.providers.vsmac.VSMacSettingsProcessor.Companion.getGeneralSettingsFile
import com.intellij.ide.customize.transferSettings.providers.vsmac.VSMacSettingsProcessor.Companion.vsPreferences
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.util.SmartList
import com.jetbrains.rd.util.Date
import java.nio.file.Files
import java.nio.file.Paths
private val logger = logger<VSMacTransferSettingsProvider>()
class VSMacTransferSettingsProvider : TransferSettingsProvider {
override val name = "Visual Studio for Mac"
override fun isAvailable() = SystemInfoRt.isMac
override fun getIdeVersions(skipIds: List<String>) = when (val version = detectVSForMacVersion()) {
null -> SmartList()
else -> SmartList(getIdeVersion(version))
}
override fun getImportPerformer(ideVersion: IdeVersion) = DefaultImportPerformer()
private fun getIdeVersion(version: String) = IdeVersion(
name = "Visual Studio for Mac",
id = "VSMAC",
icon = AllIcons.Idea_logo_welcome,
lastUsed = getLastUsed(version),
settings = VSMacSettingsProcessor().getProcessedSettings(version),
provider = this
)
private fun detectVSForMacVersion(): String? {
val pathToDir = Paths.get(vsPreferences)
if (!Files.isDirectory(pathToDir)) {
return null
}
var max = 0L
var lastUsedVersion: String? = null
Files.list(pathToDir).use { files ->
for (path in files) {
if (!Files.isDirectory(path) && Files.isHidden(path)) continue
val maybeVersion = path.fileName.toString()
val recentlyUsedFile = getGeneralSettingsFile(maybeVersion)
if (recentlyUsedFile.exists()) {
val lastModificationTime = recentlyUsedFile.lastModified()
if (max < lastModificationTime) {
max = lastModificationTime
lastUsedVersion = maybeVersion
}
}
}
}
return lastUsedVersion
}
private fun getLastUsed(version: String): Date? {
val recentlyUsedFile = getGeneralSettingsFile(version)
return try {
Date(recentlyUsedFile.lastModified())
}
catch (t: Throwable) {
logger.warn(t)
null
}
}
}
| platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vsmac/VSMacTransferSettingsProvider.kt | 4105944566 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.core
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference
class EventManager {
private val listeners = mutableListOf<(SettingReference<*, *>?) -> Unit>()
fun addSettingUpdaterEventListener(listener: (SettingReference<*, *>?) -> Unit) {
listeners += listener
}
fun fireListeners(reference: SettingReference<*, *>?) {
listeners.forEach { it(reference) }
}
} | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/EventManager.kt | 4234051263 |
import com.intellij.ui.Gray
import java.awt.Color
class UseGrayConstantFixWhenNumberConstantsReferenced {
fun any() {
@Suppress("UNUSED_VARIABLE")
val gray = Gray._125
}
companion object {
private const val GRAY_VALUE = 125
}
}
| plugins/devkit/devkit-kotlin-tests/testData/inspections/useGrayFix/UseGrayConstantFixWhenNumberConstantsReferenced_after.kt | 2498592655 |
// 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.junit
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.kotlin.util.AbstractKotlinBundle
@NonNls
private const val BUNDLE = "messages.KotlinJUnitBundle"
internal object KotlinJUnitBundle : AbstractKotlinBundle(BUNDLE) {
@Nls
@JvmStatic
fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
} | plugins/kotlin/run-configurations/junit/src/org/jetbrains/kotlin/idea/junit/KotlinJUnitBundle.kt | 1481685603 |
import a.b.c.d.foo
fun f(p: Int) {
<selection>foo(p)</selection>
} | plugins/kotlin/idea/tests/testData/copyPaste/imports/UnresolvedOverload.kt | 2892319462 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github.ui.cloneDialog
import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser
import org.jetbrains.plugins.github.api.data.GithubRepo
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import javax.swing.AbstractListModel
internal class GHCloneDialogRepositoryListModel : AbstractListModel<GHRepositoryListItem>() {
private val itemsByAccount = LinkedHashMap<GithubAccount, MutableList<GHRepositoryListItem>>()
private val repositoriesByAccount = hashMapOf<GithubAccount, MutableSet<GithubRepo>>()
override fun getSize(): Int = itemsByAccount.values.sumOf { it.size }
override fun getElementAt(index: Int): GHRepositoryListItem {
var offset = 0
for ((_, items) in itemsByAccount) {
if (index >= offset + items.size) {
offset += items.size
continue
}
return items[index - offset]
}
throw IndexOutOfBoundsException(index)
}
fun getItemAt(index: Int): Pair<GithubAccount, GHRepositoryListItem> {
var offset = 0
for ((account, items) in itemsByAccount) {
if (index >= offset + items.size) {
offset += items.size
continue
}
return account to items[index - offset]
}
throw IndexOutOfBoundsException(index)
}
fun indexOf(account: GithubAccount, item: GHRepositoryListItem): Int {
if (!itemsByAccount.containsKey(account)) return -1
var startOffset = 0
for ((_account, items) in itemsByAccount) {
if (_account == account) {
val idx = items.indexOf(item)
if (idx < 0) return -1
return startOffset + idx
}
else {
startOffset += items.size
}
}
return -1
}
fun clear(account: GithubAccount) {
repositoriesByAccount.remove(account)
val (startOffset, endOffset) = findAccountOffsets(account) ?: return
itemsByAccount.remove(account)
fireIntervalRemoved(this, startOffset, endOffset)
}
fun setError(account: GithubAccount, error: Throwable) {
val accountItems = itemsByAccount.getOrPut(account) { mutableListOf() }
val (startOffset, endOffset) = findAccountOffsets(account) ?: return
val errorItem = GHRepositoryListItem.Error(account, error)
accountItems.add(0, errorItem)
fireIntervalAdded(this, endOffset, endOffset + 1)
fireContentsChanged(this, startOffset, endOffset + 1)
}
/**
* Since each repository can be in several states at the same time (shared access for a collaborator and shared access for org member) and
* repositories for collaborators are loaded in separate request before repositories for org members, we need to update order of re-added
* repo in order to place it close to other organization repos
*/
fun addRepositories(account: GithubAccount, details: GithubAuthenticatedUser, repos: List<GithubRepo>) {
val repoSet = repositoriesByAccount.getOrPut(account) { mutableSetOf() }
val items = itemsByAccount.getOrPut(account) { mutableListOf() }
var (startOffset, endOffset) = findAccountOffsets(account) ?: return
val toAdd = mutableListOf<GHRepositoryListItem.Repo>()
for (repo in repos) {
val item = GHRepositoryListItem.Repo(account, details, repo)
val isNew = repoSet.add(repo)
if (isNew) {
toAdd.add(item)
}
else {
val idx = items.indexOf(item)
items.removeAt(idx)
fireIntervalRemoved(this, startOffset + idx, startOffset + idx)
endOffset--
}
}
items.addAll(toAdd)
fireIntervalAdded(this, endOffset, endOffset + toAdd.size)
}
private fun findAccountOffsets(account: GithubAccount): Pair<Int, Int>? {
if (!itemsByAccount.containsKey(account)) return null
var startOffset = 0
var endOffset = 0
for ((_account, items) in itemsByAccount) {
endOffset = startOffset + items.size
if (_account == account) {
break
}
else {
startOffset += items.size
}
}
return startOffset to endOffset
}
} | plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHCloneDialogRepositoryListModel.kt | 2797690827 |
// WITH_RUNTIME
// PROBLEM: none
val pi = <caret>3.14159265359
| plugins/kotlin/idea/tests/testData/inspectionsLocal/floatingPointLiteralPrecision/doublePi11.kt | 1423565861 |
// FIX: Replace with 'getValue' call
// WITH_RUNTIME
fun test(map: Map<Int, String>) {
val s = map[1]<caret>!!
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/mapGetWithNotNullAssertionOperator/indexedAccess.kt | 3702268769 |
package de.stefanmedack.ccctv.persistence
import android.arch.persistence.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import de.stefanmedack.ccctv.model.ConferenceGroup
import de.stefanmedack.ccctv.persistence.entities.LanguageList
import de.stefanmedack.ccctv.util.EMPTY_STRING
import info.metadude.kotlin.library.c3media.models.AspectRatio
import info.metadude.kotlin.library.c3media.models.RelatedEvent
import org.threeten.bp.DateTimeException
import org.threeten.bp.LocalDate
import org.threeten.bp.OffsetDateTime
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.format.DateTimeParseException
class C3TypeConverters {
private val gson = Gson()
private val offsetDateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME
private val localDateFormatter = DateTimeFormatter.ISO_DATE
// *********************************************************
// *** List<String> ****************************************
// *********************************************************
@TypeConverter
fun fromStringList(listString: String?): List<String> =
if (listString.isNullOrEmpty()) {
listOf()
} else {
gson.fromJson(listString, object : TypeToken<ArrayList<String>>() {}.type)
}
@TypeConverter
fun toStringList(list: List<String>?): String? = gson.toJson(list)
// *********************************************************
// *** List<Language> **************************************
// *********************************************************
@TypeConverter
fun fromLanguageList(listString: String?): LanguageList =
if (listString.isNullOrEmpty()) {
LanguageList()
} else {
gson.fromJson(listString, object : TypeToken<LanguageList>() {}.type)
}
@TypeConverter
fun toLanguageList(languageList: LanguageList): String? = gson.toJson(languageList)
// *********************************************************
// *** Metadata ********************************************
// *********************************************************
@TypeConverter
fun fromRelatedEventsString(metadataString: String?): List<RelatedEvent>? = gson
.fromJson(metadataString, object : TypeToken<List<RelatedEvent>>() {}.type)
@TypeConverter
fun toRelatedEventsString(metadata: List<RelatedEvent>?) = metadata?.let { gson.toJson(it) }
// *********************************************************
// *** AspectRatio *****************************************
// *********************************************************
@TypeConverter
fun fromAspectRatioString(aspectRatioString: String?) = AspectRatio.toAspectRatio(aspectRatioString)
@TypeConverter
fun toAspectRatioString(aspectRatio: AspectRatio) = AspectRatio.toText(aspectRatio) ?: EMPTY_STRING
// *********************************************************
// *** OffsetDateTime **************************************
// *********************************************************
@TypeConverter
fun fromOffsetDateTimeString(dateTimeString: String?): OffsetDateTime? = dateTimeString?.let {
try {
OffsetDateTime.parse(dateTimeString, offsetDateTimeFormatter)
} catch (e: DateTimeParseException) {
null
}
}
@TypeConverter
fun toOffsetDateTimeString(offsetDateTime: OffsetDateTime?) = offsetDateTime?.let {
try {
it.format(offsetDateTimeFormatter)
} catch (e: DateTimeException) {
null
}
}
// *********************************************************
// *** LocalDate *******************************************
// *********************************************************
@TypeConverter
fun fromLocalDateString(text: String?): LocalDate? = text?.let {
try {
LocalDate.parse(text, localDateFormatter)
} catch (e: DateTimeParseException) {
null
}
}
@TypeConverter
fun toLocalDateString(localDate: LocalDate?) = localDate?.let {
try {
it.format(localDateFormatter)
} catch (e: DateTimeException) {
null
}
}
// *********************************************************
// *** ConferenceGroup *******************************************
// *********************************************************
@TypeConverter
fun fromConferenceGroupString(text: String?): ConferenceGroup? = text?.let { ConferenceGroup.valueOf(it) }
@TypeConverter
fun toConferenceGroupString(conferenceGroup: ConferenceGroup?) = conferenceGroup?.name
} | app/src/main/java/de/stefanmedack/ccctv/persistence/C3TypeConverters.kt | 3675792917 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.builder.impl
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.UiSwitcher
import com.intellij.openapi.ui.getUserData
import com.intellij.openapi.ui.putUserData
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.Expandable
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import org.jetbrains.annotations.ApiStatus
import java.awt.Component
import javax.swing.JComponent
import javax.swing.border.EmptyBorder
@ApiStatus.Internal
internal class CollapsibleRowImpl(dialogPanelConfig: DialogPanelConfig,
panelContext: PanelContext,
parent: PanelImpl,
@NlsContexts.BorderTitle title: String,
init: Panel.() -> Unit) :
RowImpl(dialogPanelConfig, panelContext, parent, RowLayout.INDEPENDENT), CollapsibleRow {
private val collapsibleTitledSeparator = CollapsibleTitledSeparator(title)
override var expanded by collapsibleTitledSeparator::expanded
override fun setText(@NlsContexts.Separator text: String) {
collapsibleTitledSeparator.text = text
}
override fun addExpandedListener(action: (Boolean) -> Unit) {
collapsibleTitledSeparator.expandedProperty.afterChange { action(it) }
}
init {
collapsibleTitledSeparator.setLabelFocusable(true)
(collapsibleTitledSeparator.label.border as? EmptyBorder)?.borderInsets?.let {
collapsibleTitledSeparator.putClientProperty(DslComponentProperty.VISUAL_PADDINGS,
Gaps(top = it.top, left = it.left, bottom = it.bottom))
}
val expandable = ExpandableImpl(collapsibleTitledSeparator)
collapsibleTitledSeparator.label.putClientProperty(Expandable::class.java, expandable)
val action = DumbAwareAction.create { expanded = !expanded }
action.registerCustomShortcutSet(ActionUtil.getShortcutSet("CollapsiblePanel-toggle"), collapsibleTitledSeparator.label)
val collapsibleTitledSeparator = this.collapsibleTitledSeparator
panel {
row {
cell(collapsibleTitledSeparator)
.horizontalAlign(HorizontalAlign.FILL)
}
val expandablePanel = panel(init)
collapsibleTitledSeparator.onAction(expandablePanel::visible)
collapsibleTitledSeparator.putUserData(UiSwitcher.UI_SWITCHER, UiSwitcherImpl(expandable, expandablePanel))
}
}
private class ExpandableImpl(private val separator: CollapsibleTitledSeparator) : Expandable {
override fun expand() {
separator.expanded = true
}
override fun collapse() {
separator.expanded = false
}
override fun isExpanded(): Boolean {
return separator.expanded
}
}
private class UiSwitcherImpl(
private val expandable: Expandable,
private val panel: Panel
) : UiSwitcher {
override fun show(component: Component) {
if (component is JComponent) {
val hierarchy = component.getUserData(DSL_PANEL_HIERARCHY)
if (hierarchy != null && panel in hierarchy) {
expandable.expand()
}
}
}
}
}
| platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/CollapsibleRowImpl.kt | 1644504516 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints
import com.intellij.lang.Language
import com.intellij.lang.LanguageExtension
import com.intellij.lang.LanguageExtensionPoint
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import com.intellij.util.xmlb.annotations.Property
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
import kotlin.reflect.KMutableProperty0
private const val EXTENSION_POINT_NAME = "com.intellij.codeInsight.inlayProvider"
enum class InlayGroup(val key: String, @Nls val description: String? = null) {
CODE_VISION_GROUP_NEW("settings.hints.new.group.code.vision", ApplicationBundle.message("settings.hints.new.group.code.vision.description")),
CODE_VISION_GROUP("settings.hints.group.code.vision", ApplicationBundle.message("settings.hints.new.group.code.vision.description")),
PARAMETERS_GROUP("settings.hints.group.parameters", ApplicationBundle.message("settings.hints.group.parameters.description")),
TYPES_GROUP("settings.hints.group.types", ApplicationBundle.message("settings.hints.group.types.description")),
VALUES_GROUP("settings.hints.group.values", ApplicationBundle.message("settings.hints.group.values.description")),
ANNOTATIONS_GROUP("settings.hints.group.annotations", ApplicationBundle.message("settings.hints.group.annotations.description")),
METHOD_CHAINS_GROUP("settings.hints.group.method.chains"),
LAMBDAS_GROUP("settings.hints.group.lambdas", ApplicationBundle.message("settings.hints.group.lambdas.description")),
CODE_AUTHOR_GROUP("settings.hints.group.code.author", ApplicationBundle.message("settings.hints.group.code.author.description")),
URL_PATH_GROUP("settings.hints.group.url.path", ApplicationBundle.message("settings.hints.group.url.path.description")),
OTHER_GROUP("settings.hints.group.other");
override fun toString(): @Nls String {
return ApplicationBundle.message(key)
}}
object InlayHintsProviderExtension : LanguageExtension<InlayHintsProvider<*>>(EXTENSION_POINT_NAME) {
private fun findLanguagesWithHintsSupport(): List<Language> {
val extensionPointName = inlayProviderName
return extensionPointName.extensionList.map { it.language }
.toSet()
.mapNotNull { Language.findLanguageByID(it) }
}
fun findProviders() : List<ProviderInfo<*>> {
return findLanguagesWithHintsSupport().flatMap { language ->
InlayHintsProviderExtension.allForLanguage(language).map { ProviderInfo(language, it) }
}
}
val inlayProviderName = ExtensionPointName<LanguageExtensionPoint<InlayHintsProvider<*>>>(EXTENSION_POINT_NAME)
}
/**
* Provider of inlay hints for single language. If you need to create hints for multiple languages, please use [InlayHintsProviderFactory].
* Both block and inline hints collection are supported.
* Block hints draws between lines of code text. Inline ones are placed on the code text line (like parameter hints)
* @param T settings type of this provider, if no settings required, please, use [NoSettings]
* @see com.intellij.openapi.editor.InlayModel.addInlineElement
* @see com.intellij.openapi.editor.InlayModel.addBlockElement
*
* To test it you may use InlayHintsProviderTestCase.
* Mark as [com.intellij.openapi.project.DumbAware] to enable it in dumb mode.
*/
interface InlayHintsProvider<T : Any> {
/**
* If this method is called, provider is enabled for this file
* Warning! Your collector should not use any settings besides [settings]
*/
fun getCollectorFor(file: PsiFile, editor: Editor, settings: T, sink: InlayHintsSink): InlayHintsCollector?
/**
* Returns quick collector of placeholders.
* Placeholders are shown on editor opening and stay until [getCollectorFor] collector hints are calculated.
*/
@ApiStatus.Experimental
@JvmDefault
fun getPlaceholdersCollectorFor(file: PsiFile, editor: Editor, settings: T, sink: InlayHintsSink): InlayHintsCollector? = null
/**
* Settings must be plain java object, fields of these settings will be copied via serialization.
* Must implement `equals` method, otherwise settings won't be able to track modification.
* Returned object will be used to create configurable and collector.
* It persists automatically.
*/
fun createSettings(): T
@get:Nls(capitalization = Nls.Capitalization.Sentence)
/**
* Name of this kind of hints. It will be used in settings and in context menu.
* Please, do not use word "hints" to avoid duplication
*/
val name: String
@JvmDefault
val group: InlayGroup get() = InlayGroup.OTHER_GROUP
/**
* Used for persisting settings.
*/
val key: SettingsKey<T>
@JvmDefault
val description: String?
@Nls
get() {
return getProperty("inlay." + key.id + ".description")
}
/**
* Text, that will be used in the settings as a preview.
*/
val previewText: String?
/**
* Creates configurable, that immediately applies changes from UI to [settings].
*/
fun createConfigurable(settings: T): ImmediateConfigurable
/**
* Checks whether the language is accepted by the provider.
*/
fun isLanguageSupported(language: Language): Boolean = true
@JvmDefault
fun createFile(project: Project, fileType: FileType, document: Document): PsiFile {
val factory = PsiFileFactory.getInstance(project)
return factory.createFileFromText("dummy", fileType, document.text)
}
@Nls
@JvmDefault
fun getProperty(key: String): String? = null
@JvmDefault
fun preparePreview(editor: Editor, file: PsiFile, settings: T) {
}
@Nls
@JvmDefault
fun getCaseDescription(case: ImmediateConfigurable.Case): String? {
return getProperty("inlay." + this.key.id + "." + case.id)
}
val isVisibleInSettings: Boolean
get() = true
}
/**
* The same as [UnnamedConfigurable], but not waiting for apply() to save settings.
*/
interface ImmediateConfigurable {
/**
* Creates component, which listen to its components and immediately updates state of settings object
* This is required to make preview in settings works instantly
* Note, that if you need to express only cases of this provider, you should use [cases] instead
*/
fun createComponent(listener: ChangeListener): JComponent
/**
* Loads state from its configurable.
*/
@JvmDefault
fun reset() {}
/**
* Text, that will be used in settings for checkbox to enable/disable hints.
*/
@JvmDefault
val mainCheckboxText: String
get() = "Show hints"
@JvmDefault
val cases : List<Case>
get() = emptyList()
class Case(
@Nls val name: String,
val id: String,
private val loadFromSettings: () -> Boolean,
private val onUserChanged: (Boolean) -> Unit,
@NlsContexts.DetailedDescription
val extendedDescription: String? = null
) {
var value: Boolean
get() = loadFromSettings()
set(value) = onUserChanged(value)
constructor(@Nls name: String, id: String, property: KMutableProperty0<Boolean>, @NlsContexts.DetailedDescription extendedDescription: String? = null) : this(
name,
id,
{ property.get() },
{property.set(it)},
extendedDescription
)
}
}
interface ChangeListener {
/**
* This method should be called on any change of corresponding settings.
*/
fun settingsChanged()
}
/**
* This class should be used if provider should not have settings. If you use e.g. [Unit] you will have annoying warning in logs.
*/
@Property(assertIfNoBindings = false)
class NoSettings {
override fun equals(other: Any?): Boolean = other is NoSettings
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
/**
* Similar to [com.intellij.openapi.util.Key], but it also requires language to be unique.
* Allows type-safe access to settings of provider.
*/
@Suppress("unused")
data class SettingsKey<T>(val id: String) {
fun getFullId(language: Language): String = language.id + "." + id
}
interface AbstractSettingsKey<T: Any> {
fun getFullId(language: Language): String
}
data class InlayKey<T: Any, C: Any>(val id: String) : AbstractSettingsKey<T>, ContentKey<C> {
override fun getFullId(language: Language): String = language.id + "." + id
}
/**
* Allows type-safe access to content of the root presentation.
*/
interface ContentKey<C: Any> | platform/lang-api/src/com/intellij/codeInsight/hints/InlayHintsProvider.kt | 1187589712 |
/*
* Copyright 2010-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 codegen.`try`.finally11
import kotlin.test.*
@Test fun runTest() {
try {
try {
return
} catch (e: Error) {
println("Catch 1")
} finally {
println("Finally")
throw Error()
}
} catch (e: Error) {
println("Catch 2")
}
println("Done")
} | backend.native/tests/codegen/try/finally11.kt | 980153034 |
// 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.devkit.workspaceModel
import com.intellij.workspaceModel.codegen.InterfaceTraverser
import com.intellij.workspaceModel.codegen.InterfaceVisitor
import com.intellij.workspaceModel.codegen.deft.meta.Obj
import com.intellij.workspaceModel.codegen.deft.meta.ObjClass
import com.intellij.workspaceModel.codegen.deft.meta.ObjProperty
import com.intellij.workspaceModel.codegen.deft.meta.ValueType
import com.intellij.devkit.workspaceModel.metaModel.impl.ObjClassImpl
import com.intellij.devkit.workspaceModel.metaModel.impl.ObjModuleImpl
import com.intellij.devkit.workspaceModel.metaModel.impl.OwnPropertyImpl
import org.jetbrains.kotlin.descriptors.SourceElement
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class InterfaceTraverserTest {
@Test
fun `test boolean`() {
val type = createType()
type.addField("myName", ValueType.Boolean)
val collector = StringBuilder()
InterfaceTraverser().traverse(type, MyInterfaceVisitor(collector))
assertEquals("- Boolean - myName\n", collector.toString())
}
private fun ObjClassImpl<Obj>.addField(name: String, type: ValueType<*>) {
addField(OwnPropertyImpl(this, name, type, ObjProperty.ValueKind.Plain, false, false, false, 0, false, SourceElement.NO_SOURCE))
}
@Test
fun `test int`() {
val type = createType()
type.addField("myName", ValueType.Int)
val collector = StringBuilder()
InterfaceTraverser().traverse(type, MyInterfaceVisitor(collector))
assertEquals("- Int - myName\n", collector.toString())
}
@Test
fun `test string`() {
val type = createType()
type.addField("myName", ValueType.String)
val collector = StringBuilder()
InterfaceTraverser().traverse(type, MyInterfaceVisitor(collector))
assertEquals("- String - myName\n", collector.toString())
}
@Test
fun `test list`() {
val type = createType()
type.addField("myName", ValueType.List(ValueType.String))
val collector = StringBuilder()
InterfaceTraverser().traverse(type, MyInterfaceVisitor(collector))
assertEquals("""
-- Start loop --
- String - _myName
-- Finish loop --
""".trimIndent(), collector.toString())
}
@Test
fun `test map`() {
val type = createType()
type.addField("myName", ValueType.Map(ValueType.String, ValueType.Int))
val collector = StringBuilder()
InterfaceTraverser().traverse(type, MyInterfaceVisitor(collector))
assertEquals("""
-- Start Map --
- String - key_myName
- Int - value_myName
-- Finish Map --
""".trimIndent(), collector.toString())
}
@Test
fun `test optional`() {
val type = createType()
type.addField("myName", ValueType.Optional(ValueType.Int))
val collector = StringBuilder()
InterfaceTraverser().traverse(type, MyInterfaceVisitor(collector))
assertEquals("""
-- Start Optional --
- Int - _myName
-- Finish Optional --
""".trimIndent(), collector.toString())
}
@Test
fun `test blob`() {
val type = createType()
type.addField("myName", ValueType.Blob<Any>("my.class", emptyList()))
val collector = StringBuilder()
InterfaceTraverser().traverse(type, MyInterfaceVisitor(collector))
assertEquals("""
-- Blob | myName | my.class --
""".trimIndent(), collector.toString())
}
private fun createType(): ObjClassImpl<Obj> {
return ObjClassImpl(ObjModuleImpl("module"), "MyClass", ObjClass.Openness.final, SourceElement.NO_SOURCE)
}
}
class MyInterfaceVisitor(val collector: StringBuilder) : InterfaceVisitor {
override fun visitBoolean(varName: String): Boolean {
collector.appendLine("- Boolean - $varName")
return true
}
override fun visitInt(varName: String): Boolean {
collector.appendLine("- Int - $varName")
return true
}
override fun visitString(varName: String): Boolean {
collector.appendLine("- String - $varName")
return true
}
override fun visitListStart(varName: String, itemVarName: String, listArgumentType: ValueType<*>): Boolean {
collector.appendLine("-- Start loop --")
return true
}
override fun visitListEnd(varName: String, itemVarName: String, traverseResult: Boolean, listArgumentType: ValueType<*>): Boolean {
collector.appendLine("-- Finish loop --")
return true
}
override fun visitMapStart(varName: String,
keyVarName: String,
valueVarName: String,
keyType: ValueType<*>,
valueType: ValueType<*>): Boolean {
collector.appendLine("-- Start Map --")
return true
}
override fun visitMapEnd(varName: String,
keyVarName: String,
valueVarName: String,
keyType: ValueType<*>,
valueType: ValueType<*>,
traverseResult: Boolean): Boolean {
collector.appendLine("-- Finish Map --")
return true
}
override fun visitOptionalStart(varName: String, notNullVarName: String, type: ValueType<*>): Boolean {
collector.appendLine("-- Start Optional --")
return true
}
override fun visitOptionalEnd(varName: String, notNullVarName: String, type: ValueType<*>, traverseResult: Boolean): Boolean {
collector.appendLine("-- Finish Optional --")
return true
}
override fun visitUnknownBlob(varName: String, javaSimpleName: String): Boolean {
collector.appendLine("-- Blob | $varName | $javaSimpleName --")
return true
}
override fun visitKnownBlobStart(varName: String, javaSimpleName: String): Boolean {
TODO("Not yet implemented")
}
override fun visitKnownBlobFinish(varName: String, javaSimpleName: String, traverseResult: Boolean): Boolean {
TODO("Not yet implemented")
}
override fun visitDataClassStart(varName: String, dataClass: ValueType.DataClass<*>): Boolean {
TODO("Not yet implemented")
}
override fun visitDataClassEnd(varName: String, dataClass: ValueType.DataClass<*>, traverseResult: Boolean): Boolean {
TODO("Not yet implemented")
}
}
| plugins/devkit/intellij.devkit.workspaceModel/tests/testSrc/com/intellij/devkit/workspaceModel/InterfaceTraverserTest.kt | 3191497503 |
fun <T, V> foo(t: T): T = t
fun <T, V> foo(t: T, p: Int): T = t
fun <X> foo(p: Boolean, x: X) {}
fun bar() {
foo<<caret>>
}
/*
Text: (<highlight>T</highlight>, V), Disabled: false, Strikeout: false, Green: false
Text: (<highlight>X</highlight>), Disabled: false, Strikeout: false, Green: false
*/ | plugins/kotlin/idea/tests/testData/parameterInfo/typeArguments/OverloadsNoParens.kt | 1350339281 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.script.configuration.listener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Alarm
import com.intellij.util.concurrency.AppExecutorUtil
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.configuration.listener.ScriptChangeListener.Companion.LISTENER
import org.jetbrains.kotlin.idea.core.script.isScriptChangesNotifierDisabled
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
internal class ScriptChangesNotifier(private val project: Project) {
private val scriptsQueue: Alarm
private val scriptChangesListenerDelayMillis = 1400
init {
val parentDisposable = KotlinPluginDisposable.getInstance(project)
scriptsQueue = Alarm(Alarm.ThreadToUse.POOLED_THREAD, parentDisposable)
project.messageBus.connect(parentDisposable).subscribe(
FileEditorManagerListener.FILE_EDITOR_MANAGER,
object : FileEditorManagerListener {
override fun fileOpened(source: FileEditorManager, file: VirtualFile) {
runScriptDependenciesUpdateIfNeeded(file)
}
override fun selectionChanged(event: FileEditorManagerEvent) {
event.newFile?.let { runScriptDependenciesUpdateIfNeeded(it) }
}
private fun runScriptDependenciesUpdateIfNeeded(file: VirtualFile) {
if (isUnitTestMode()) {
updateScriptDependenciesIfNeeded(file)
} else {
AppExecutorUtil.getAppExecutorService().submit {
updateScriptDependenciesIfNeeded(file)
}
}
}
},
)
EditorFactory.getInstance().eventMulticaster.addDocumentListener(
object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
val document = event.document
val file = FileDocumentManager.getInstance().getFile(document)?.takeIf { it.isInLocalFileSystem } ?: return
// Do not listen for changes in files that are not open
val editorManager = FileEditorManager.getInstance(project) ?: return
if (file !in editorManager.openFiles) {
return
}
if (isUnitTestMode()) {
getListener(project, file)?.documentChanged(file)
} else {
scriptsQueue.cancelAllRequests()
if (!project.isDisposed) {
scriptsQueue.addRequest(
{ getListener(project, file)?.documentChanged(file) },
scriptChangesListenerDelayMillis,
true,
)
}
}
}
},
parentDisposable
)
// Init project scripting idea EP listeners
LISTENER.getExtensions(project)
}
private val defaultListener = DefaultScriptChangeListener(project)
private val listeners: Collection<ScriptChangeListener>
get() = mutableListOf<ScriptChangeListener>().apply {
addAll(LISTENER.getExtensions(project))
add(defaultListener)
}
internal fun updateScriptDependenciesIfNeeded(file: VirtualFile) {
getListener(project, file)?.editorActivated(file)
}
private fun getListener(project: Project, file: VirtualFile): ScriptChangeListener? {
if (project.isDisposed || areListenersDisabled()) return null
return listeners.firstOrNull { it.isApplicable(file) }
}
private fun areListenersDisabled(): Boolean {
return isUnitTestMode() && ApplicationManager.getApplication().isScriptChangesNotifierDisabled == true
}
}
| plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/listener/ScriptChangesNotifier.kt | 915015328 |
package target
import source.Expr
data class Const(val number: Double) : Expr() | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/sealedSubclassWithSkippedRoot/after/target/Const.kt | 2363313220 |
// "Replace '@JvmField' with 'const'" "true"
// WITH_STDLIB
<caret>@JvmField private val number: Int = 42 | plugins/kotlin/idea/tests/testData/quickfix/replaceJvmFieldWithConst/toplevel.kt | 3978053305 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.api
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference
interface GroovyCallReference : GroovyReference {
val arguments: Arguments?
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/api/GroovyCallReference.kt | 2873089771 |
intArrayOf(1, 2, 3) | plugins/kotlin/j2k/old/tests/testData/fileOrElement/arrayInitializerExpression/newInt.kt | 2431763119 |
// "Remove useless cast" "true"
fun foo() {}
fun test() {
foo()
// comment
({ "" } as<caret> () -> String)
} | plugins/kotlin/idea/tests/testData/quickfix/expressions/removeUselessCastForLambdaInParens2.kt | 1260780237 |
package net.gouline.kotlindemo
/**
* Debug configuration.
*/
object BuildTypeConfig {
val LOG_MESSAGE = "DEBUG BUILD"
} | kotlin-demo/app/src/debug/java/net/gouline/kotlindemo/BuildTypeConfig.kt | 529434539 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.resolve
import com.intellij.ide.presentation.Presentation
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyPropertyBase
@Presentation(typeName = "Gradle Extension")
class GradleExtensionProperty(name: String, private val type: PsiType?, context: PsiElement) : GroovyPropertyBase(name, context) {
override fun getPropertyType(): PsiType? = type
override fun toString(): String = "Gradle Extension: $name"
}
| plugins/gradle/java/src/service/resolve/GradleExtensionProperty.kt | 894281 |
fun test(x: Any): Int? {
<caret>(x as? String) ?: (return null)
return foo(x)
}
fun foo(x: String) = 1 | plugins/kotlin/idea/tests/testData/inspectionsLocal/safeCastWithReturn/hasParenthesize.kt | 2450722960 |
interface A {
fun x(): String
}
class B(val c: Int) : A {
override fun x(): String { return "$c" }
}
class C(val d: Int) : A {
override fun x(): String { return "$d" }
}
<warning descr="SSR">class D(b: B) : A by b</warning>
class E(b: C) : A by b
class F(val b: B) : A {
override fun x(): String { return "$b" }
}
interface G {
fun x(): String
}
class H(val c: Int) : G {
override fun x(): String { return "$c" }
}
class I(b: H) : G by b | plugins/kotlin/idea/tests/testData/structuralsearch/class/classDelegation.kt | 3834270985 |
package com.goldenpiedevs.schedule.app.ui.widget
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import androidx.core.content.ContextCompat
import com.goldenpiedevs.schedule.app.R
import com.goldenpiedevs.schedule.app.core.dao.timetable.*
import com.goldenpiedevs.schedule.app.core.ext.currentWeek
import com.goldenpiedevs.schedule.app.core.ext.todayNumberInWeek
import com.goldenpiedevs.schedule.app.core.utils.preference.AppPreference
import java.util.*
/**
* WidgetDataProvider acts as the adapter for the collection view widget,
* providing RemoteViews to the widget in the getViewAt method.
*/
class WidgetDataProvider(val context: Context) : RemoteViewsService.RemoteViewsFactory {
private var mCollection: MutableList<DaoLessonModel> = ArrayList()
override fun onCreate() {
initData()
}
override fun onDataSetChanged() {
initData()
}
override fun onDestroy() {
mCollection.clear()
}
override fun getCount(): Int {
return mCollection.size
}
override fun getViewAt(position: Int): RemoteViews {
val model = mCollection[position]
val view = RemoteViews(context.packageName,
R.layout.widget_item_view)
view.setViewVisibility(R.id.widget_lesson_has_note, if (model.haveNote) View.VISIBLE else View.INVISIBLE)
view.setTextViewText(R.id.widget_lesson_title, model.lessonName)
view.setTextColor(R.id.widget_lesson_number,
if (model.haveNote) Color.WHITE else ContextCompat.getColor(context, R.color.secondary_text))
view.setTextViewText(R.id.widget_lesson_number, model.lessonNumber.toString())
view.setTextViewText(R.id.widget_lesson_time, model.getTime())
view.setTextViewText(R.id.widget_lesson_location, "${model.lessonRoom} ${model.lessonType}")
val extras = Bundle()
extras.putString(ScheduleWidgetProvider.LESSON_ID, model.id)
val fillInIntent = Intent()
fillInIntent.putExtras(extras)
view.setOnClickFillInIntent(R.id.widget_item_row_view, fillInIntent)
return view
}
override fun getLoadingView(): RemoteViews? {
return null
}
override fun getViewTypeCount(): Int {
return 1
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun hasStableIds(): Boolean {
return true
}
private fun initData() {
mCollection.clear()
val data = DaoDayModel.getLessons()
.forGroupWithName(AppPreference.groupName)
.forWeek(currentWeek + 1)
.firstOrNull { it.dayNumber == todayNumberInWeek }
?.lessons
data?.let {
mCollection.addAll(it)
}
}
}
| app/src/main/java/com/goldenpiedevs/schedule/app/ui/widget/WidgetDataProvider.kt | 3406576804 |
// 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.test
import com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiFile
import com.intellij.testFramework.UsefulTestCase
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.test.InTextDirectivesUtils
object DirectiveBasedActionUtils {
const val DISABLE_ERRORS_DIRECTIVE = "// DISABLE-ERRORS"
const val DISABLE_WARNINGS_DIRECTIVE = "// DISABLE-WARNINGS"
const val ENABLE_WARNINGS_DIRECTIVE = "// ENABLE-WARNINGS"
const val ACTION_DIRECTIVE = "// ACTION:"
fun checkForUnexpectedErrors(file: KtFile, diagnosticsProvider: (KtFile) -> Diagnostics = { it.analyzeWithContent().diagnostics }) {
if (InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, DISABLE_ERRORS_DIRECTIVE).isNotEmpty()) {
return
}
checkForUnexpected(file, diagnosticsProvider, "// ERROR:", "errors", Severity.ERROR)
}
fun checkForUnexpectedWarnings(
file: KtFile,
disabledByDefault: Boolean = true,
directiveName: String = Severity.WARNING.name,
diagnosticsProvider: (KtFile) -> Diagnostics = { it.analyzeWithContent().diagnostics }
) {
if (disabledByDefault && InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, ENABLE_WARNINGS_DIRECTIVE).isEmpty() ||
!disabledByDefault && InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, DISABLE_WARNINGS_DIRECTIVE).isNotEmpty()) {
return
}
checkForUnexpected(file, diagnosticsProvider, "// $directiveName:", "warnings", Severity.WARNING)
}
private fun checkForUnexpected(
file: KtFile,
diagnosticsProvider: (KtFile) -> Diagnostics,
directive: String,
name: String,
severity: Severity
) {
val expected = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, directive)
.sorted()
.map { "$directive $it" }
val diagnostics = diagnosticsProvider(file)
val actual = diagnostics
.filter { it.severity == severity }
.map { "$directive ${DefaultErrorMessages.render(it).replace("\n", "<br>")}" }
.sorted()
if (actual.isEmpty() && expected.isEmpty()) return
UsefulTestCase.assertOrderedEquals(
"All actual $name should be mentioned in test data with '$directive' directive. " +
"But no unnecessary $name should be me mentioned, file:\n${file.text}",
actual,
expected
)
}
fun inspectionChecks(name: String, file: PsiFile) {
InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, "// INSPECTION-CLASS:").takeIf { it.isNotEmpty() }?.let { inspectionNames ->
val inspectionManager = InspectionManager.getInstance(file.project)
val inspections = inspectionNames.map { Class.forName(it).getDeclaredConstructor().newInstance() as AbstractKotlinInspection }
val problems = mutableListOf<ProblemDescriptor>()
ProgressManager.getInstance().executeProcessUnderProgress(
{
for (inspection in inspections) {
problems += inspection.processFile(
file,
inspectionManager
)
}
}, DaemonProgressIndicator()
)
val directive = "// INSPECTION:"
val expected = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, directive)
.sorted()
.map { "$directive $it" }
val actual = problems
// lineNumber is 0-based
.map { "$directive [${it.highlightType.name}:${it.lineNumber + 1}] $it" }
.sorted()
if (actual.isEmpty() && expected.isEmpty()) return
KotlinLightCodeInsightFixtureTestCaseBase.assertOrderedEquals(
"All actual $name should be mentioned in test data with '$directive' directive. " +
"But no unnecessary $name should be me mentioned, file:\n${file.text}",
actual,
expected
)
}
}
fun checkAvailableActionsAreExpected(file: PsiFile, availableActions: Collection<IntentionAction>) {
val expectedActions = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, ACTION_DIRECTIVE).sorted()
UsefulTestCase.assertEmpty("Irrelevant actions should not be specified in $ACTION_DIRECTIVE directive for they are not checked anyway",
expectedActions.filter { isIrrelevantAction(it) })
if (InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, "// IGNORE_IRRELEVANT_ACTIONS").isNotEmpty()) {
return
}
val actualActions = availableActions.map { it.text }.sorted()
UsefulTestCase.assertOrderedEquals(
"Some unexpected actions available at current position. Use '$ACTION_DIRECTIVE' directive",
filterOutIrrelevantActions(actualActions).map { "$ACTION_DIRECTIVE $it" },
expectedActions.map { "$ACTION_DIRECTIVE $it" }
)
}
//TODO: hack, implemented because irrelevant actions behave in different ways on build server and locally
// this behaviour should be investigated and hack can be removed
private fun filterOutIrrelevantActions(actions: Collection<String>): Collection<String> {
return actions.filter { !isIrrelevantAction(it) }
}
private fun isIrrelevantAction(action: String) = action.isEmpty() || IRRELEVANT_ACTION_PREFIXES.any { action.startsWith(it) }
private val IRRELEVANT_ACTION_PREFIXES = listOf(
"Disable ",
"Edit intention settings",
"Edit inspection profile setting",
"Inject language or reference",
"Suppress '",
"Run inspection on",
"Inspection '",
"Suppress for ",
"Suppress all ",
"Edit cleanup profile settings",
"Fix all '",
"Cleanup code",
"Go to ",
"Show local variable type hints",
"Show function return type hints",
"Show property type hints",
"Show parameter type hints",
"Show argument name hints",
"Show hints for suspending calls",
"Add 'JUnit",
"Add 'testng"
)
}
| plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/DirectiveBasedActionUtils.kt | 1988138727 |
package pl.pw.mgr.lightsensor.calibrations
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import kotlinx.android.synthetic.main.activity_calibration.*
import pl.pw.mgr.lightsensor.App
import pl.pw.mgr.lightsensor.R
import pl.pw.mgr.lightsensor.common.C
import pl.pw.mgr.lightsensor.common.C.Companion.NO_RES_ID
import pl.pw.mgr.lightsensor.common.ConfirmationListener
import pl.pw.mgr.lightsensor.data.model.Calibration
import pl.pw.mgr.lightsensor.points.PointsActivity
import javax.inject.Inject
class CalibrationsActivity : AppCompatActivity(), CalibrationsContract.View {
@Inject internal lateinit var presenter: CalibrationsPresenter
private lateinit var adapter: CalibrationsAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_calibration)
DaggerCalibrationsComponent.builder()
.repositoryComponent((application as App).repositoryComponent)
.calibrationsPresenterModule(CalibrationsPresenterModule(this))
.build()
.inject(this)
adapter = CalibrationsAdapter(this)
recycler_view.setHasFixedSize(true)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.adapter = adapter
recycler_view.addItemDecoration(
DividerItemDecoration(applicationContext, DividerItemDecoration.VERTICAL).also {
it.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider))
}
)
add_btn.setOnClickListener { presenter.onAddCalibrationClicked() }
edit_btn.setOnClickListener { presenter.onEditCalibrationClicked(adapter.getSelectedCalibration()) }
delete_btn.setOnClickListener { presenter.onDeleteCalibrationClicked(adapter.getSelectedCalibration()) }
}
override fun onStart() {
super.onStart()
presenter.start()
}
override fun showCalibrations(items: List<Calibration>) = adapter.setItems(items)
override fun showAdditionalCalibration(calibration: Calibration) = adapter.addItem(calibration)
override fun removeFromUI(calibration: Calibration) = adapter.removeItem(calibration)
override fun showEmptyCalibrationsInfo() {
TODO("Not implemented yet")
}
override fun showAddConfirmationDialog() {
MaterialDialog.Builder(this)
.title(R.string.activity_calibration_dialog_add_title)
.positiveText(R.string.activity_calibration_dialog_positive_btn)
.negativeText(R.string.activity_calibration_dialog_negative_btn)
.alwaysCallInputCallback()
.input(R.string.activity_calibration_dialog_add_input_hint,
NO_RES_ID,
false,
{ dialog, input -> dialog.getActionButton(DialogAction.POSITIVE).isEnabled = !input.isBlank() })
.onPositive { dialog, _ -> presenter.addCalibration(dialog.inputEditText?.text.toString()) }
.show()
}
override fun showDeleteConfirmationDialog(listener: ConfirmationListener) {
MaterialDialog.Builder(this)
.title(R.string.activity_calibration_dialog_delete_title)
.positiveText(R.string.activity_calibration_dialog_positive_btn)
.negativeText(R.string.activity_calibration_dialog_negative_btn)
.onPositive { _, _ -> listener.onConfirm() }
.onNegative { _, _ -> listener.onDecline() }
.show()
}
override fun showChoseCalibrationInfo() = Snackbar.make(activity_calibration_root, R.string.activity_calibration_chose_calibration_err, Snackbar.LENGTH_SHORT).show()
override fun showEditCalibrationUI(calibration: Calibration) = startActivity(Intent(this, PointsActivity::class.java).apply {
putExtra(C.Calibrations.ID, calibration.id)
})
override fun isActive() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
!isDestroyed
} else {
!isFinishing
}
override fun onBackPressed() {
adapter.getSelectedCalibration()?.let {
setResult(Activity.RESULT_OK, Intent().putExtra(C.Calibrations.ID, it.id))
} ?: setResult(Activity.RESULT_CANCELED)
super.onBackPressed()
}
}
| app/src/main/java/pl/pw/mgr/lightsensor/calibrations/CalibrationsActivity.kt | 2670529536 |
package Kotlin101.Objects.Traits
fun main(args : Array<String>){
var adam = Cowboy("Adam")
adam.does()
}
trait Shooting {
public var name : String
fun does(){
print("$name can Shoot")
}
}
class Cowboy (name : String): Shooting{
override var name = name
} | src/Objects/Traits.kt | 1728047261 |
/*-
* #%L
* ff4j-spring-boot-web-api
* %%
* Copyright (C) 2013 - 2019 FF4J
* %%
* 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.
* #L%
*/
package org.ff4j.spring.boot.web.api.resources
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import org.ff4j.services.MonitoringServices
import org.ff4j.services.constants.FeatureConstants.RESOURCE_FF4J_MONITORING
import org.ff4j.services.domain.EventRepositoryApiBean
import org.ff4j.web.FF4jWebConstants.PARAM_END
import org.ff4j.web.FF4jWebConstants.PARAM_START
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType.APPLICATION_JSON_VALUE
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
/**
* Created by Paul
*
* @author [Paul Williams](mailto:[email protected])
*/
@Api(tags = ["Monitoring"], description = "The API for monitoring related operations")
@RestController
@RequestMapping(value = [RESOURCE_FF4J_MONITORING])
class MonitoringResource(@Autowired val monitoringServices: MonitoringServices) {
@ApiOperation(value = "Display Monitoring information for all features", notes = "The EventRepository handle to store audit events is not required", response = EventRepositoryApiBean::class)
@ApiResponses(
ApiResponse(code = 200, message = "Status of event repository bean", response = EventRepositoryApiBean::class),
ApiResponse(code = 404, message = "No event repository defined", response = String::class))
@GetMapping(produces = [APPLICATION_JSON_VALUE])
fun getMonitoringStatus(@RequestParam(value = PARAM_START, required = false, defaultValue = "0") start: Long, @RequestParam(value = PARAM_END, required = false, defaultValue = "0") end: Long): EventRepositoryApiBean =
monitoringServices.getMonitoringStatus(start, end)
}
| ff4j-spring-boot-web-api/src/main/kotlin/org/ff4j/spring/boot/web/api/resources/MonitoringResource.kt | 678764273 |
/*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.customtabs.client
import android.content.ComponentName
import android.support.customtabs.CustomTabsClient
import android.support.customtabs.CustomTabsServiceConnection
import java.lang.ref.WeakReference
/**
* Implementation for the CustomTabsServiceConnection that avoids leaking the
* ServiceConnectionCallback
*/
class ServiceConnection(connectionCallback: ServiceConnectionCallback) : CustomTabsServiceConnection() {
// A weak reference to the ServiceConnectionCallback to avoid leaking it.
private val mConnectionCallback: WeakReference<ServiceConnectionCallback> = WeakReference(connectionCallback)
override fun onCustomTabsServiceConnected(name: ComponentName, client: CustomTabsClient) {
val connectionCallback = mConnectionCallback.get()
connectionCallback?.onServiceConnected(client)
}
override fun onServiceDisconnected(name: ComponentName) {
val connectionCallback = mConnectionCallback.get()
connectionCallback?.onServiceDisconnected()
}
} | presentation/src/main/java/com/sinyuk/fanfou/customtabs/client/ServiceConnection.kt | 2865669743 |
package bj.vinylbrowser.model.master
import android.os.Parcel
import android.os.Parcelable
/**
* Created by Josh Laird on 19/05/2017.
*/
data class Video(val duration: Int, val description: String, val embed: Boolean,
val uri: String, val title: String) : Parcelable {
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(duration)
dest.writeString(description)
dest.writeInt(if (embed) 1 else 0)
dest.writeString(uri)
dest.writeString(title)
}
override fun describeContents(): Int {
return 0
}
} | app/src/main/java/bj/vinylbrowser/model/master/Video.kt | 4245316561 |
package ch.rmy.android.http_shortcuts.activities.settings.globalcode
import ch.rmy.android.framework.viewmodel.ViewModelEvent
abstract class GlobalScriptingEvent : ViewModelEvent() {
object ShowCodeSnippetPicker : GlobalScriptingEvent()
data class InsertCodeSnippet(
val textBeforeCursor: String,
val textAfterCursor: String,
) : GlobalScriptingEvent()
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/settings/globalcode/GlobalScriptingEvent.kt | 2614230312 |
package stan.androiddemo.project.petal.Module.Follow
import android.content.Context
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.TextView
import com.chad.library.adapter.base.BaseViewHolder
import com.facebook.drawee.view.SimpleDraweeView
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import stan.androiddemo.R
import stan.androiddemo.UI.BasePetalRecyclerFragment
import stan.androiddemo.project.petal.API.FollowAPI
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Event.OnBoardFragmentInteractionListener
import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient
import stan.androiddemo.project.petal.Model.BoardPinsInfo
import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder
class PetalFollowBoardFragment : BasePetalRecyclerFragment<BoardPinsInfo>() {
var mLimit = Config.LIMIT
lateinit var mAttentionFormat: String
lateinit var mGatherFormat: String
lateinit var mUsernameFormat: String
private var mListener: OnBoardFragmentInteractionListener<BoardPinsInfo>? = null
companion object {
fun newInstance():PetalFollowBoardFragment{
return PetalFollowBoardFragment()
}
}
override fun getTheTAG(): String {
return this.toString()
}
override fun initView() {
super.initView()
mAttentionFormat = resources.getString(R.string.text_gather_number)
mGatherFormat = resources.getString(R.string.text_attention_number)
mUsernameFormat = resources.getString(R.string.text_by_username)
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnBoardFragmentInteractionListener<*>){
mListener = context as OnBoardFragmentInteractionListener<BoardPinsInfo>
}
}
override fun getLayoutManager(): RecyclerView.LayoutManager {
return GridLayoutManager(context,2)
}
override fun getItemLayoutId(): Int {
return R.layout.petal_cardview_board_item
}
override fun itemLayoutConvert(helper: BaseViewHolder, t: BoardPinsInfo) {
val img = helper.getView<SimpleDraweeView>(R.id.img_card_board)
helper.getView<TextView>(R.id.txt_board_title).text = t.title
helper.getView<TextView>(R.id.txt_board_gather).text = String.format(mGatherFormat,t.pin_count)
helper.getView<TextView>(R.id.txt_board_attention).text = String.format(mAttentionFormat,t.follow_count)
helper.getView<TextView>(R.id.txt_board_username).text = String.format(mUsernameFormat,t.user?.username)
img.setOnClickListener {
mListener?.onClickBoardItemImage(t,it)
}
helper.getView<TextView>(R.id.txt_board_username).setOnClickListener {
mListener?.onClickBoardItemImage(t,it)
}
var url = ""
if (t.pins!= null && t.pins!!.size > 0){
if (t.pins!!.first().file?.key != null){
url = t.pins!!.first().file!!.key!!
}
}
url = String.format(mUrlGeneralFormat,url)
img.aspectRatio = 1F
ImageLoadBuilder.Start(context,img,url).setProgressBarImage(progressLoading).build()
}
override fun requestListData(page: Int): Subscription {
return RetrofitClient.createService(FollowAPI::class.java).httpsMyFollowingBoardRx(mAuthorization!!,page,mLimit)
.map { it.boards }.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object: Subscriber<List<BoardPinsInfo>>(){
override fun onCompleted() {
}
override fun onError(e: Throwable?) {
e?.printStackTrace()
loadError()
checkException(e)
}
override fun onNext(t: List<BoardPinsInfo>?) {
if (t == null){
loadError()
return
}
loadSuccess(t!!)
}
})
}
}
| app/src/main/java/stan/androiddemo/project/petal/Module/Follow/PetalFollowBoardFragment.kt | 3720399212 |
package stan.androiddemo
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| app/src/test/java/stan/androiddemo/ExampleUnitTest.kt | 995354621 |
package com.bugsnag.android.gradle.internal
import okio.buffer
import okio.gzip
import okio.sink
import okio.source
import java.io.File
import java.io.InputStream
/**
* Outputs the contents of stdout into the gzip file output file
*
* @param stdout The input stream
* @param outputFile The output file
* included in the output file or not
*/
internal fun outputZipFile(stdout: InputStream, outputFile: File) {
stdout.source().use { source ->
outputFile.sink().gzip().buffer().use { gzipSink ->
gzipSink.writeAll(source)
}
}
}
| src/main/kotlin/com/bugsnag/android/gradle/internal/IOUtil.kt | 3162940560 |
package io.kotest.core.listeners
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import io.kotest.core.test.TestType
interface BeforeEachListener : Listener {
/**
* Registers a new before-each callback to be executed before every [TestCase]
* with type [TestType.Test].
* The [TestCase] about to be executed is provided as the parameter.
*/
suspend fun beforeEach(testCase: TestCase): Unit = Unit
}
interface AfterEachListener : Listener {
/**
* Registers a new after-each callback to be executed after every [TestCase]
* with type [TestType.Test].
* The callback provides two parameters - the test case that has just completed,
* and the [TestResult] outcome of that test.
*/
suspend fun afterEach(testCase: TestCase, result: TestResult): Unit = Unit
}
| kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/listeners/each.kt | 652673293 |
package io.kotest.assertions.json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.floatOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.longOrNull
fun JsonElement.toJsonNode(): JsonNode = when (this) {
JsonNull -> JsonNode.NullNode
is JsonObject -> JsonNode.ObjectNode(entries.map { it.key to it.value.toJsonNode() }.toMap())
is JsonArray -> JsonNode.ArrayNode(map { it.toJsonNode() })
is JsonPrimitive -> when {
intOrNull != null -> JsonNode.IntNode(intOrNull!!)
longOrNull != null -> JsonNode.LongNode(longOrNull!!)
doubleOrNull != null -> JsonNode.DoubleNode(doubleOrNull!!)
floatOrNull != null -> JsonNode.FloatNode(floatOrNull!!)
booleanOrNull != null -> JsonNode.BooleanNode(booleanOrNull!!)
contentOrNull != null -> JsonNode.StringNode(contentOrNull!!)
else -> error("Unsupported kotlinx-serialization type $this")
}
}
| kotest-assertions/kotest-assertions-json/src/commonMain/kotlin/io/kotest/assertions/json/wrappers.kt | 2693984432 |
/**
* BreadWallet
*
* Created by Pablo Budelli <[email protected]> on 12/6/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.settings.fastsync
import com.breadwallet.ui.settings.fastsync.FastSync.F
import com.breadwallet.ui.settings.fastsync.FastSync.M
import com.spotify.mobius.First
import com.spotify.mobius.First.first
import com.spotify.mobius.Init
object FastSyncInit : Init<M, F> {
override fun init(model: M): First<M, F> =
first(
model,
setOf(F.LoadCurrencyIds)
)
}
| app/src/main/java/com/breadwallet/ui/settings/fastsync/FastSyncInit.kt | 813510269 |
package com.byoutline.secretsauce.lifecycle
import android.app.Activity
import android.app.Application
import android.os.Bundle
/**
* Wraps given [Application.ActivityLifecycleCallbacks], so only lifecycle of [this] [Activity]
* are forwarded. Calling this method will immediately register wrapped callback and it will be
* automatically unregistered when activity is destroyed.
*
* This is supposed to help avoid boilerplate in [Application.ActivityLifecycleCallbacks].
* For example instead of:
* ```kotlin
* class ExampleActivity: AppCompatActivity {
* override fun onCreate(savedInstanceState: Bundle?) {
* super.onCreate(savedInstanceState)
* application.registerActivityLifecycleCallbacks(LifecycleListener(this))
* }
* }
*
* class LifecycleListener(val view: Activity): ActivityLifecycleCallbacksAdapter() {
* override fun onActivityResumed(a: Activity?) {
* if(view === a) doSomething()
* }
* override fun onActivityDestroyed(a: Activity?) {
* if (a === view) view.application.unregisterActivityLifecycleCallbacks(this)
* }
* }
* ```
* you can write:
* ```kotlin
* class ExampleActivity: AppCompatActivity {
* override fun onCreate(savedInstanceState: Bundle?) {
* super.onCreate(savedInstanceState)
* registerLifecycleCallbacksForThisActivityOnly(LifecycleListener())
* }
* }
*
* class LifecycleListener(): ActivityLifecycleCallbacksAdapter() {
* override fun onActivityResumed(a: Activity?) {
* doSomething()
* }
* }
* ```
*/
fun Activity.registerLifecycleCallbacksForThisActivityOnly(callbacksToWrap: Application.ActivityLifecycleCallbacks) {
val wrapped = SingleActivityLifecycleCallbacks(this, callbacksToWrap)
application.registerActivityLifecycleCallbacks(wrapped)
}
/**
* Wrapper for regular [Application.ActivityLifecycleCallbacks] that passes lifecycle callbacks
* only if they concern declared activity. Also it automatically unregister itself from application.
* This is supposed to help avoid boilerplate in lifecycle callback.
*/
private class SingleActivityLifecycleCallbacks(
private val view: Activity,
private val delegate: Application.ActivityLifecycleCallbacks
) : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(a: Activity?, savedInstanceState: Bundle?) {
if (a === view) delegate.onActivityCreated(a, savedInstanceState)
}
override fun onActivityStarted(a: Activity?) {
if (a === view) delegate.onActivityStarted(a)
}
override fun onActivityResumed(a: Activity?) {
if (a === view) delegate.onActivityResumed(a)
}
override fun onActivityPaused(a: Activity?) {
if (a === view) delegate.onActivityPaused(a)
}
override fun onActivityStopped(a: Activity?) {
if (a === view) delegate.onActivityStopped(a)
}
override fun onActivitySaveInstanceState(a: Activity?, outState: Bundle?) {
if (a === view) delegate.onActivitySaveInstanceState(a, outState)
}
override fun onActivityDestroyed(a: Activity?) {
if (a === view) {
delegate.onActivityDestroyed(a)
view.application.unregisterActivityLifecycleCallbacks(this)
}
}
}
/**
* Adapter for [Application.ActivityLifecycleCallbacks] for cases where you want to
* override just one of the callbacks.
*
* Example (before and after):
*
* ```kotlin
* class LifecycleListenerBefore: Application.ActivityLifecycleCallbacks {
* override fun onActivityCreated(a: Activity?, savedInstanceState: Bundle?) {}
* override fun onActivityStarted(a: Activity?) {}
* override fun onActivityResumed(a: Activity?) {
* doSomething()
* }
* override fun onActivityPaused(a: Activity?) {}
* override fun onActivityStopped(a: Activity?) {}
* override fun onActivitySaveInstanceState(a: Activity?, outState: Bundle?) {}
* override fun onActivityDestroyed(a: Activity?) {}
* }
*
* class LifecycleListenerAfter: ActivityLifecycleCallbacksAdapter() {
* override fun onActivityResumed(a: Activity?) {
* doSomething()
* }
* }
* ```
*/
abstract class ActivityLifecycleCallbacksAdapter : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(a: Activity?, savedInstanceState: Bundle?) {}
override fun onActivityStarted(a: Activity?) {}
override fun onActivityResumed(a: Activity?) {}
override fun onActivityPaused(a: Activity?) {}
override fun onActivityStopped(a: Activity?) {}
override fun onActivitySaveInstanceState(a: Activity?, outState: Bundle?) {}
override fun onActivityDestroyed(a: Activity?) {}
}
| SecretSauce/src/main/java/com/byoutline/secretsauce/lifecycle/SingleActivityLifecycleCallbacks.kt | 1150478187 |
package com.quran.mobile.feature.downloadmanager.model.sheikhdownload
sealed class SuraDownloadStatusEvent {
data class Progress(
val progress: Int,
val sura: Int,
val ayah: Int,
val downloadedAmount: Long,
val totalAmount: Long
) : SuraDownloadStatusEvent()
object Done: SuraDownloadStatusEvent()
data class Error(val errorCode: Int, val errorMessage: String): SuraDownloadStatusEvent()
}
val NoProgress = SuraDownloadStatusEvent.Progress(-1, -1, -1, -1, -1)
| feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/model/sheikhdownload/SuraDownloadStatusEvent.kt | 801285197 |
package com.quran.mobile.recitation.presenter
import com.quran.data.di.QuranPageScope
import com.quran.data.di.QuranReadingPageScope
import com.quran.recitation.presenter.RecitationHighlightsPresenter
import com.quran.recitation.presenter.RecitationHighlightsPresenter.RecitationPage
import com.squareup.anvil.annotations.ContributesBinding
import javax.inject.Inject
@QuranPageScope
@ContributesBinding(scope = QuranReadingPageScope::class, boundType = RecitationHighlightsPresenter::class)
class RecitationHighlightsPresenterImpl @Inject constructor(): RecitationHighlightsPresenter {
override fun bind(what: RecitationPage) {}
override fun unbind(what: RecitationPage) {}
override fun refresh() {}
}
| feature/recitation/src/main/java/com/quran/mobile/recitation/presenter/RecitationHighlightsPresenterImpl.kt | 4099475126 |
package com.osfans.trime.util
import android.view.View
import android.view.Window
import android.widget.FrameLayout
import android.widget.LinearLayout
/** (This Kotlin file has been taken from florisboard project)
* This file has been taken from the Android LatinIME project. Following modifications were done by
* florisboard to the original source code:
* - Convert the code from Java to Kotlin
* - Change package name to match the current project's one
* - Remove method newLayoutParam()
* - Remove method placeViewAt()
* - Remove unnecessary variable params in updateLayoutGravityOf(), lp can directly be used due to
* Kotlin's smart cast feature
* - Remove unused imports
*
* The original source code can be found at the following location:
* https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+/refs/heads/master/java/src/com/android/inputmethod/latin/utils/ViewLayoutUtils.java
*/
object ViewUtils {
@JvmStatic
fun updateLayoutHeightOf(window: Window, layoutHeight: Int) {
val params = window.attributes
if (params != null && params.height != layoutHeight) {
params.height = layoutHeight
window.attributes = params
}
}
@JvmStatic
fun updateLayoutHeightOf(view: View, layoutHeight: Int) {
val params = view.layoutParams
if (params != null && params.height != layoutHeight) {
params.height = layoutHeight
view.layoutParams = params
}
}
@JvmStatic
fun updateLayoutGravityOf(view: View, layoutGravity: Int) {
val lp = view.layoutParams
if (lp is LinearLayout.LayoutParams) {
if (lp.gravity != layoutGravity) {
lp.gravity = layoutGravity
view.layoutParams = lp
}
} else if (lp is FrameLayout.LayoutParams) {
if (lp.gravity != layoutGravity) {
lp.gravity = layoutGravity
view.layoutParams = lp
}
} else {
throw IllegalArgumentException(
"Layout parameter doesn't have gravity: " +
lp.javaClass.name
)
}
}
}
| app/src/main/java/com/osfans/trime/util/ViewUtils.kt | 1371186571 |
package io.kotlinthree.ui
import android.content.Context
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import io.kotlinthree.R
import io.kotlinthree.api.News
import io.kotlinthree.ui.base.HBaseAdapter
import io.kotlinthree.util.HViewHolder
/**
* Created by jameson on 12/19/15.
*/
class NewsListAdapter(context: Context, list: List<News>) : HBaseAdapter<News>(context, list) {
override fun onNewItemViewRes(): Int {
return R.layout.item_news_list
}
override fun onBindItemView(convertView: View, data: News, position: Int, parent: ViewGroup) {
HViewHolder.getTextView(convertView, R.id.title).text = data.title
Glide.with(context).load(data.images[0]).crossFade().into(HViewHolder.getImageView(convertView, R.id.image));
}
}
| app/src/main/java/io/kotlinthree/ui/NewsListAdapter.kt | 1444779122 |
/*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.statbuilds.bukkit.statattribute
import com.rpkit.core.service.ServiceProvider
interface RPKStatAttributeProvider: ServiceProvider {
val statAttributes: List<RPKStatAttribute>
fun getStatAttribute(name: String): RPKStatAttribute?
} | bukkit/rpk-stat-build-lib-bukkit/src/main/kotlin/com/rpkit/statbuilds/bukkit/statattribute/RPKStatAttributeProvider.kt | 1597826222 |
/*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.action.item
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import okio.buffer
import okio.sink
import okio.source
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
class TabListSingleActionTest {
@Test
fun testDecodeEncode() {
val fiftyJson = """{"1":3, "2":true, "3":3}"""
val reader = JsonReader.of(ByteArrayInputStream(fiftyJson.toByteArray()).source().buffer())
val action = TabListSingleAction(0, reader)
assertThat(action.mode).isEqualTo(3)
assertThat(action.isLeftButton).isEqualTo(true)
assertThat(action.lastTabMode).isEqualTo(3)
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT)
val os = ByteArrayOutputStream()
val writer = JsonWriter.of(os.sink().buffer())
writer.beginArray()
action.writeIdAndData(writer)
writer.endArray()
writer.flush()
assertThat(os.toString()).isEqualTo("""[0,{"1":3,"2":true,"3":3}]""")
}
} | legacy/src/test/java/jp/hazuki/yuzubrowser/legacy/action/item/TabListSingleActionTest.kt | 467275519 |
/*
* Copyright 2016 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.economy.bukkit.command.currency
import com.rpkit.economy.bukkit.RPKEconomyBukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
/**
* Currency command.
* Parent command for all currency management commands.
*/
class CurrencyCommand(private val plugin: RPKEconomyBukkit): CommandExecutor {
private val currencyAddCommand = CurrencyAddCommand(plugin)
private val currencyRemoveCommand = CurrencyRemoveCommand(plugin)
private val currencyListCommand = CurrencyListCommand(plugin)
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (args.isNotEmpty()) {
val newArgs = args.drop(1).toTypedArray()
if (args[0].equals("add", ignoreCase = true) || args[0].equals("create", ignoreCase = true) || args[0].equals("new", ignoreCase = true)) {
return currencyAddCommand.onCommand(sender, command, label, newArgs)
} else if (args[0].equals("remove", ignoreCase = true) || args[0].equals("delete", ignoreCase = true)) {
return currencyRemoveCommand.onCommand(sender, command, label, newArgs)
} else if (args[0].equals("list", ignoreCase = true)) {
return currencyListCommand.onCommand(sender, command, label, newArgs)
} else {
sender.sendMessage(plugin.messages["currency-usage"])
}
} else {
sender.sendMessage(plugin.messages["currency-usage"])
}
return true
}
}
| bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/command/currency/CurrencyCommand.kt | 3183808861 |
/*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("FlowQuery")
package com.squareup.sqldelight.runtime.coroutines
import com.squareup.sqldelight.Query
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.CONFLATED
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
/** Turns this [Query] into a [Flow] which emits whenever the underlying result set changes. */
@JvmName("toFlow")
fun <T : Any> Query<T>.asFlow(): Flow<Query<T>> = flow {
val channel = Channel<Unit>(CONFLATED)
channel.trySend(Unit)
val listener = object : Query.Listener {
override fun queryResultsChanged() {
channel.trySend(Unit)
}
}
addListener(listener)
try {
for (item in channel) {
emit(this@asFlow)
}
} finally {
removeListener(listener)
}
}
@JvmOverloads
fun <T : Any> Flow<Query<T>>.mapToOne(
context: CoroutineContext = Dispatchers.Default
): Flow<T> = map {
withContext(context) {
it.executeAsOne()
}
}
@JvmOverloads
fun <T : Any> Flow<Query<T>>.mapToOneOrDefault(
defaultValue: T,
context: CoroutineContext = Dispatchers.Default
): Flow<T> = map {
withContext(context) {
it.executeAsOneOrNull() ?: defaultValue
}
}
@JvmOverloads
fun <T : Any> Flow<Query<T>>.mapToOneOrNull(
context: CoroutineContext = Dispatchers.Default
): Flow<T?> = map {
withContext(context) {
it.executeAsOneOrNull()
}
}
@JvmOverloads
fun <T : Any> Flow<Query<T>>.mapToOneNotNull(
context: CoroutineContext = Dispatchers.Default
): Flow<T> = mapNotNull {
withContext(context) {
it.executeAsOneOrNull()
}
}
@JvmOverloads
fun <T : Any> Flow<Query<T>>.mapToList(
context: CoroutineContext = Dispatchers.Default
): Flow<List<T>> = map {
withContext(context) {
it.executeAsList()
}
}
| extensions/coroutines-extensions/src/commonMain/kotlin/com/squareup/sqldelight/runtime/coroutines/FlowExtensions.kt | 3409207906 |
package de.maxdobler.systemicconsensus
import android.app.Application
import de.maxdobler.systemicconsensus.di.AndroidModule
import de.maxdobler.systemicconsensus.di.DaggerAppComponent
class MyApplication : Application() {
val component by lazy {
DaggerAppComponent.builder()
.androidModule(AndroidModule(this))
.build()
}
override fun onCreate() {
super.onCreate()
}
} | app/src/main/java/de/maxdobler/systemicconsensus/MyApplication.kt | 2986314541 |
package site.yanglong.promotion.service.impl
import site.yanglong.promotion.model.UserRoles
import site.yanglong.promotion.mapper.UserRolesMapper
import site.yanglong.promotion.service.UserRolesService
import com.baomidou.mybatisplus.service.impl.ServiceImpl
import org.springframework.stereotype.Service
/**
*
*
* 服务实现类
*
*
* @author Dr.YangLong
* @since 2017-11-01
*/
@Service
class UserRolesServiceImpl : ServiceImpl<UserRolesMapper, UserRoles>(), UserRolesService
| src/main/kotlin/site/yanglong/promotion/service/impl/UserRolesServiceImpl.kt | 2709079203 |
package com.androidessence.cashcaretaker.ui.transaction
import androidx.databinding.BaseObservable
import com.androidessence.cashcaretaker.R
import com.androidessence.cashcaretaker.core.models.Transaction
import com.androidessence.cashcaretaker.util.asCurrency
import com.androidessence.cashcaretaker.util.asUIString
class TransactionViewModel : BaseObservable() {
var transaction: Transaction? = null
set(value) {
field = value
notifyChange()
}
val description: String
get() {
val description = transaction?.description.orEmpty()
return when {
description.isEmpty() -> NO_DESCRIPTION
else -> description
}
}
val dateString: String
get() = transaction?.date?.asUIString().orEmpty()
val amount: String
get() = transaction?.amount?.asCurrency().orEmpty()
val indicatorColorResource: Int
get() = when {
transaction?.withdrawal == true -> R.color.mds_red_500
else -> R.color.mds_green_500
}
companion object {
const val NO_DESCRIPTION = "N/A"
}
}
| app/src/main/java/com/androidessence/cashcaretaker/ui/transaction/TransactionViewModel.kt | 2316469382 |
package nice3point.by.schedule.Adapters
import android.app.FragmentManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import io.realm.Realm
import io.realm.RealmResults
import nice3point.by.schedule.Database.TableObject
import nice3point.by.schedule.Database.TeachersObject
import nice3point.by.schedule.R
import nice3point.by.schedule.ScheduleDialogChanger.VScheduleChanger
import nice3point.by.schedule.TeachersInfoActivity.TeacherInfo
import nice3point.by.schedule.TechnicalModule
class RVAdapter(private val realmResults: RealmResults<TableObject>, private val manager: FragmentManager) : RecyclerView.Adapter<RVAdapter.PersonViewHolder>() {
private lateinit var context: Context
override fun onAttachedToRecyclerView(recyclerView: RecyclerView?) {
super.onAttachedToRecyclerView(recyclerView)
}
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): PersonViewHolder {
context = viewGroup.context
val v = LayoutInflater.from(context).inflate(R.layout.card_view_global, viewGroup, false)
return PersonViewHolder(v)
}
override fun onBindViewHolder(personViewHolder: PersonViewHolder, i: Int) {
val teacher = realmResults[i].teacher
val subject = realmResults[i].subject
val type = realmResults[i].type
val time = realmResults[i].time
val cabinet = realmResults[i].cabinet
val day = realmResults[i].table_name
personViewHolder.Card_subject.text = subject
personViewHolder.Card_teacher.text = teacher
personViewHolder.Card_time.text = time
personViewHolder.Card_cabinet.text = cabinet
// if (i == 0) {
// personViewHolder.relativeLayout.setPadding(30, 30, 30, 0);
// personViewHolder.separator.setPadding(30, 30,30,0);
// } else if (i == (getItemCount() - 1)) {
// personViewHolder.relativeLayout.setPadding(30, 30, 30, 30);
// personViewHolder.separator.setVisibility(View.INVISIBLE);
//
// } else {
// personViewHolder.relativeLayout.setPadding(30, 30, 30, 0);
// personViewHolder.separator.setPadding(30, 30,30,0);
// }
if (type.length >= 4) {
if ("Лаб".equals(type.substring(0, 3), ignoreCase = true)) {
if (!type.contains(" ")) {
personViewHolder.Card_type.text = type
personViewHolder.Card_type.setBackgroundColor(Color.parseColor("#9900AA"))
} else {
personViewHolder.Card_type.text = type.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
personViewHolder.Card_type.setBackgroundColor(Color.parseColor("#9900AA"))
personViewHolder.Card_typeRight.text = type.substring(type.indexOf(" "))
}
} else if ("Практика".equals(type, ignoreCase = true)) {
personViewHolder.Card_type.text = type
personViewHolder.Card_type.setBackgroundColor(Color.parseColor("#00ba00"))
} else
personViewHolder.Card_type.text = type
} else {
personViewHolder.Card_type.text = type
}
personViewHolder.relativeLayout.setOnClickListener {
if (!teacher.isEmpty()) {
val realm = Realm.getInstance(TechnicalModule.getTeacheInfoRealmConfig())
val results = realm.where(TeachersObject::class.java).equalTo("suname", teacher).findFirst()
if (results != null) {
val intent = Intent(context, TeacherInfo::class.java)
intent.putExtra(TeacherInfo.INTENT_SUBJ_KEY, results.subject)
intent.putExtra(TeacherInfo.INTENT_TEL_KEY, results.tel)
intent.putExtra(TeacherInfo.INTENT_SUNAME_KEY, results.suname)
intent.putExtra(TeacherInfo.INTENT_NAME_KEY, results.name)
intent.putExtra(TeacherInfo.INTENT_PHOTO_KEY, results.photo)
context.startActivity(intent)
}
realm.close()
}
}
personViewHolder.relativeLayout.setOnLongClickListener {
val dialog = VScheduleChanger.newInstance(day, teacher, cabinet, type, time, subject)
dialog.show(manager, "Изменение раписания")
true
}
}
override fun getItemCount(): Int {
return realmResults.size
}
inner class PersonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var Card_subject: TextView
var Card_teacher: TextView
var Card_time: TextView
var Card_type: TextView
var Card_cabinet: TextView
var Card_typeRight: TextView
var relativeLayout: RelativeLayout
init {
Card_subject = itemView.findViewById(R.id.Card_subject)
Card_teacher = itemView.findViewById(R.id.Card_teacher)
Card_time = itemView.findViewById(R.id.Card_time)
Card_type = itemView.findViewById(R.id.Card_type)
Card_typeRight = itemView.findViewById(R.id.Card_typeRight)
Card_cabinet = itemView.findViewById(R.id.Card_cabinet)
relativeLayout = itemView.findViewById(R.id.rv_card)
}
}
}
| app/src/main/java/nice3point/by/schedule/Adapters/RVAdapter.kt | 4127983988 |
package chat.rocket.android.chatrooms.di
import chat.rocket.android.chatrooms.ui.ChatRoomsFragment
import chat.rocket.android.dagger.scope.PerFragment
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class ChatRoomsFragmentProvider {
@ContributesAndroidInjector(modules = [ChatRoomsFragmentModule::class])
@PerFragment
abstract fun provideChatRoomsFragment(): ChatRoomsFragment
} | app/src/main/java/chat/rocket/android/chatrooms/di/ChatRoomsFragmentProvider.kt | 1746348055 |
package com.openconference.model.screen
import com.openconference.R
/**
*
*
* @author Hannes Dorfmann
*/
class SpeakersScreen : Screen {
override fun titleRes(): Int = R.string.screen_title_speakers
override fun iconRes(): Int = R.drawable.ic_speakers
} | app/src/main/java/com/openconference/model/screen/SpeakersScreen.kt | 151783899 |
package org.droidplanner.android.fragments.actionbar
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.RadioButton
import android.widget.TextView
import com.google.android.gms.analytics.HitBuilders
import com.o3dr.android.client.Drone
import com.o3dr.android.client.apis.VehicleApi
import com.o3dr.services.android.lib.drone.attribute.AttributeType
import com.o3dr.services.android.lib.drone.property.State
import com.o3dr.services.android.lib.drone.property.Type
import com.o3dr.services.android.lib.drone.property.VehicleMode
import org.droidplanner.android.R
import org.droidplanner.android.utils.analytics.GAUtils
/**
* Created by Fredia Huya-Kouadio on 9/25/15.
*/
public class FlightModeAdapter(context: Context, val drone: Drone) : SelectionListAdapter<VehicleMode>(context) {
private var selectedMode: VehicleMode
private val flightModes : List<VehicleMode>
init {
val state: State = drone.getAttribute(AttributeType.STATE)
selectedMode = state.vehicleMode
val type: Type = drone.getAttribute(AttributeType.TYPE);
flightModes = VehicleMode.getVehicleModePerDroneType(type.droneType)
// BRZ 05/12/2016
// Removing unwanted flight modes
flightModes.remove(VehicleMode.COPTER_ACRO)
flightModes.remove(VehicleMode.COPTER_ALT_HOLD)
flightModes.remove(VehicleMode.COPTER_AUTO)
flightModes.remove(VehicleMode.COPTER_AUTOTUNE)
flightModes.remove(VehicleMode.COPTER_BRAKE) // Bring back later
flightModes.remove(VehicleMode.COPTER_CIRCLE)
flightModes.remove(VehicleMode.COPTER_DRIFT)
flightModes.remove(VehicleMode.COPTER_FLIP)
//flightModes.remove(VehicleMode.COPTER_GUIDED)
flightModes.remove(VehicleMode.COPTER_LOITER)
flightModes.remove(VehicleMode.COPTER_LAND) // Bring Back Later
flightModes.remove(VehicleMode.COPTER_POSHOLD)
flightModes.remove(VehicleMode.COPTER_RTL)
flightModes.remove(VehicleMode.COPTER_SPORT)
flightModes.remove(VehicleMode.COPTER_STABILIZE)
}
override fun getCount() = flightModes.size
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View{
val vehicleMode = flightModes[position]
val containerView = convertView ?: LayoutInflater.from(parent.context).inflate(R.layout.item_selection, parent, false)
val holder = (containerView.tag as ViewHolder?) ?: ViewHolder(containerView.findViewById(R.id.item_selectable_option) as TextView,
containerView.findViewById(R.id.item_selectable_check) as RadioButton)
val clickListener = object : View.OnClickListener {
override fun onClick(v: View?) {
if (drone.isConnected) {
selectedMode = vehicleMode
holder.checkView.isChecked = true
VehicleApi.getApi(drone).setVehicleMode(vehicleMode)
//Record the attempt to change flight modes
val eventBuilder = HitBuilders.EventBuilder().setCategory(GAUtils.Category.FLIGHT).setAction("Flight mode changed").setLabel(vehicleMode.label)
GAUtils.sendEvent(eventBuilder)
listener?.onSelection()
}
}
}
holder.checkView.isChecked = vehicleMode === selectedMode
holder.checkView.setOnClickListener(clickListener)
holder.labelView.text = vehicleMode.label
holder.labelView.setOnClickListener(clickListener)
containerView.setOnClickListener(clickListener)
containerView.tag = holder
return containerView
}
override fun getSelection() = flightModes.indexOf(selectedMode)
public class ViewHolder(val labelView: TextView, val checkView: RadioButton)
} | Android/src/org/droidplanner/android/fragments/actionbar/FlightModeAdapter.kt | 791823737 |
package wiresegal.cmdctrl.common.commands.control
import net.minecraft.command.CommandBase
import net.minecraft.command.CommandException
import net.minecraft.command.CommandResultStats
import net.minecraft.command.ICommandSender
import net.minecraft.nbt.NBTPrimitive
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.server.MinecraftServer
import net.minecraft.util.text.TextComponentTranslation
import wiresegal.cmdctrl.common.CommandControl
import wiresegal.cmdctrl.common.commands.data.TileSelector
import wiresegal.cmdctrl.common.core.CTRLException
import wiresegal.cmdctrl.common.core.CTRLUsageException
import wiresegal.cmdctrl.common.core.getObject
import wiresegal.cmdctrl.common.core.notifyCTRLListener
/**
* @author WireSegal
* Created at 9:19 AM on 12/14/16.
*/
object CommandProbeNBT : CommandBase() {
@Throws(CommandException::class)
override fun execute(server: MinecraftServer, sender: ICommandSender, args: Array<out String>) {
if (args.isEmpty())
throw CTRLUsageException(getCommandUsage(sender))
val selector = args[0]
val key = if (args.size > 1) args[1] else ""
val displayKey = if (key.isBlank()) "commandcontrol.probenbt.blank" else key
val compound: NBTTagCompound
if (TileSelector.isTileSelector(selector)) {
val tile = TileSelector.matchOne(server, sender, selector) ?: throw CTRLException("commandcontrol.probenbt.notile")
compound = tile.writeToNBT(NBTTagCompound())
} else {
val entity = getEntity(server, sender, selector) ?: throw CTRLException("commandcontrol.probenbt.noentity")
compound = entityToNBT(entity)
}
val obj = if (key.isNotBlank())
compound.getObject(key) ?: throw CTRLException("commandcontrol.probenbt.notag", key)
else compound
if (obj is NBTPrimitive) sender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, obj.int)
notifyCTRLListener(sender, this, "commandcontrol.probenbt.success", TextComponentTranslation(displayKey), obj)
}
override fun getRequiredPermissionLevel() = 2
override fun getCommandName() = "probenbt"
override fun getCommandUsage(sender: ICommandSender?) = CommandControl.translate("commandcontrol.probenbt.usage")
override fun isUsernameIndex(args: Array<out String>?, index: Int) = index == 0
}
| src/main/java/wiresegal/cmdctrl/common/commands/control/CommandProbeNBT.kt | 4199706717 |
/* 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.viewshedgeoprocessing
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.concurrent.Job
import com.esri.arcgisruntime.concurrent.ListenableFuture
import com.esri.arcgisruntime.data.FeatureCollectionTable
import com.esri.arcgisruntime.data.Field
import com.esri.arcgisruntime.geometry.GeometryType
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.viewshedgeoprocessing.databinding.ActivityMainBinding
import com.esri.arcgisruntime.symbology.SimpleFillSymbol
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.esri.arcgisruntime.symbology.SimpleRenderer
import com.esri.arcgisruntime.tasks.geoprocessing.GeoprocessingFeatures
import com.esri.arcgisruntime.tasks.geoprocessing.GeoprocessingJob
import com.esri.arcgisruntime.tasks.geoprocessing.GeoprocessingParameters
import com.esri.arcgisruntime.tasks.geoprocessing.GeoprocessingTask
import java.util.concurrent.ExecutionException
import kotlin.math.roundToInt
class MainActivity : AppCompatActivity() {
private val TAG: String = this::class.java.simpleName
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val loadingView: View by lazy {
activityMainBinding.loadingView
}
private val geoprocessingTask: GeoprocessingTask by lazy { GeoprocessingTask(getString(R.string.viewshed_service)) }
private var geoprocessingJob: GeoprocessingJob? = null
private val inputGraphicsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }
private val resultGraphicsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }
// objects that implement Loadable must be class fields to prevent being garbage collected before loading
private lateinit var featureCollectionTable: FeatureCollectionTable
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 renderers for graphics overlays
val fillColor = Color.argb(120, 226, 119, 40)
val fillSymbol = SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, fillColor, null)
resultGraphicsOverlay.renderer = SimpleRenderer(fillSymbol)
val pointSymbol = SimpleMarkerSymbol(
SimpleMarkerSymbol.Style.CIRCLE,
Color.RED,
10F
)
inputGraphicsOverlay.renderer = SimpleRenderer(pointSymbol)
mapView.apply {
// create a map with the Basemap type topographic
map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
// set the viewpoint
setViewpoint(Viewpoint(45.3790, 6.8490, 100000.0))
// add graphics overlays to the map view
graphicsOverlays.addAll(listOf(resultGraphicsOverlay, inputGraphicsOverlay))
// add onTouchListener for calculating the new viewshed
onTouchListener = object : DefaultMapViewOnTouchListener(
applicationContext,
mapView
) {
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
val screenPoint = android.graphics.Point(
e.x.roundToInt(),
e.y.roundToInt()
)
val mapPoint = mMapView.screenToLocation(screenPoint)
addGraphicForPoint(mapPoint)
calculateViewshedFrom(mapPoint)
return super.onSingleTapConfirmed(e)
}
}
}
}
/**
* Adds a graphic at the chosen mapPoint.
*
* @param point in MapView coordinates.
*/
private fun addGraphicForPoint(point: Point) {
// remove existing graphics
inputGraphicsOverlay.graphics.clear()
// add new graphic to the graphics overlay
inputGraphicsOverlay.graphics.add(Graphic(point))
}
/**
* Uses the given point to create a FeatureCollectionTable which is passed to performGeoprocessing.
*
* @param point in MapView coordinates.
*/
private fun calculateViewshedFrom(point: Point) {
// display the LoadingView while calculating the Viewshed
loadingView.visibility = View.VISIBLE
// remove previous graphics
resultGraphicsOverlay.graphics.clear()
// cancel any previous job
geoprocessingJob?.cancelAsync()
// create field with same alias as name
val field = Field.createString("observer", "", 8)
// create feature collection table for point geometry
featureCollectionTable =
FeatureCollectionTable(listOf(field), GeometryType.POINT, point.spatialReference)
featureCollectionTable.loadAsync()
// create a new feature and assign the geometry
val newFeature = featureCollectionTable.createFeature().apply {
geometry = point
}
// add newFeature and call perform Geoprocessing on done loading
featureCollectionTable.addFeatureAsync(newFeature)
featureCollectionTable.addDoneLoadingListener {
if (featureCollectionTable.loadStatus == LoadStatus.LOADED) {
performGeoprocessing(featureCollectionTable)
}
}
}
/**
* Creates a GeoprocessingJob from the GeoprocessingTask. Displays the resulting viewshed on the map.
*
* @param featureCollectionTable the feature collection table containing the observation point.
*/
private fun performGeoprocessing(featureCollectionTable: FeatureCollectionTable) {
// geoprocessing parameters
val parameterFuture: ListenableFuture<GeoprocessingParameters> =
geoprocessingTask.createDefaultParametersAsync()
parameterFuture.addDoneListener {
try {
val parameters = parameterFuture.get().apply {
processSpatialReference = featureCollectionTable.spatialReference
outputSpatialReference = featureCollectionTable.spatialReference
// use the feature collection table to create the required GeoprocessingFeatures input
inputs["Input_Observation_Point"] =
GeoprocessingFeatures(featureCollectionTable)
}
// initialize job from geoprocessingTask
geoprocessingJob = geoprocessingTask.createJob(parameters)
// start the job
geoprocessingJob?.start()
// listen for job success
geoprocessingJob?.addJobDoneListener {
// hide the LoadingView when job is done loading
loadingView.visibility = View.GONE
if (geoprocessingJob?.status == Job.Status.SUCCEEDED) {
// get the viewshed from geoprocessingResult
(geoprocessingJob?.result?.outputs?.get("Viewshed_Result") as? GeoprocessingFeatures)?.let { viewshedResult ->
// for each feature in the result
for (feature in viewshedResult.features) {
// add the feature as a graphic
resultGraphicsOverlay.graphics.add(Graphic(feature.geometry))
}
}
} else {
Toast.makeText(
applicationContext,
"Geoprocessing result failed!",
Toast.LENGTH_LONG
).show()
Log.e(TAG, geoprocessingJob?.error?.cause.toString())
}
}
} catch (e: Exception) {
when (e) {
is InterruptedException, is ExecutionException -> ("Error getting geoprocessing result: " + e.message).also {
Toast.makeText(this, it, Toast.LENGTH_LONG).show()
Log.e(TAG, it)
}
else -> throw e
}
}
}
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| kotlin/viewshed-geoprocessing/src/main/java/com/esri/arcgisruntime/sample/viewshedgeoprocessing/MainActivity.kt | 4122326288 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.tools.ledger
import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor
import com.google.android.libraries.pcc.chronicle.api.FieldType
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
object DtdJson {
/**
* Serializes/deserializes [DataTypeDescriptor] objects. NOTE: the [DataTypeDescriptor.cls] value
* is not serialized, and is always deserialized to [Any.javaClass]. This is because it is not
* useful for ledger comparison and would be error-prone when using [Class.forName] for builds
* where the type is not included.
*/
object DataTypeDescriptorTypeAdapter : TypeAdapter<DataTypeDescriptor>() {
private const val NAME_FIELD = "name"
private const val FIELDS_FIELD = "fields"
private const val INNER_TYPES_FIELD = "innerTypes"
override fun write(out: JsonWriter, value: DataTypeDescriptor) {
out.makeObject {
writeNamedField(DataHubLedger.gson, NAME_FIELD, value.name)
writeNamedMap(DataHubLedger.gson, FIELDS_FIELD, value.fields)
writeNamedArray(DataHubLedger.gson, INNER_TYPES_FIELD, value.innerTypes) { it.name }
}
}
override fun read(reader: JsonReader): DataTypeDescriptor {
var name = ""
var fields = mapOf<String, FieldType>()
var innerTypes = setOf<DataTypeDescriptor>()
reader.readObject {
when (it) {
NAME_FIELD -> name = nextString()
FIELDS_FIELD -> fields = readMap(DataHubLedger.gson)
INNER_TYPES_FIELD -> innerTypes = readSet(DataHubLedger.gson)
else ->
throw IllegalArgumentException("Unexpected key in DataTypeDescriptor: \"$it\" at $path")
}
}
return DataTypeDescriptor(name, fields, innerTypes, Any::class)
}
}
/** Serializes/deserializes [FieldType] instances to JSON. */
object FieldTypeTypeAdapter : TypeAdapter<FieldType>() {
private const val ARRAY = "Array"
private const val BOOLEAN = "Boolean"
private const val BYTE = "Byte"
private const val BYTE_ARRAY = "ByteArray"
private const val CHAR = "Char"
private const val DOUBLE = "Double"
private const val DURATION = "Duration"
private const val ENUM = "Enum"
private const val FLOAT = "Float"
private const val INSTANT = "Instant"
private const val INTEGER = "Int"
private const val LIST = "List"
private const val LONG = "Long"
private const val NESTED = "Nested"
private const val NULLABLE = "Nullable"
private const val OPAQUE = "Opaque"
private const val REFERENCE = "Reference"
private const val SHORT = "Short"
private const val STRING = "String"
private const val TUPLE = "Tuple"
private const val NAME_FIELD = "name"
private const val TYPE_FIELD = "type"
private const val TYPE_PARAMETER_FIELD = "parameter"
private const val TYPE_PARAMETERS_FIELD = "parameters"
private const val VALUES_FIELD = "values"
private val STRING_TO_FIELDTYPE =
mapOf(
BOOLEAN to FieldType.Boolean,
BYTE to FieldType.Byte,
BYTE_ARRAY to FieldType.ByteArray,
CHAR to FieldType.Char,
DOUBLE to FieldType.Double,
DURATION to FieldType.Duration,
FLOAT to FieldType.Float,
INSTANT to FieldType.Instant,
INTEGER to FieldType.Integer,
LONG to FieldType.Long,
SHORT to FieldType.Short,
STRING to FieldType.String
)
override fun write(out: JsonWriter, value: FieldType) {
when (value) {
FieldType.Boolean -> out.value(BOOLEAN)
FieldType.Byte -> out.value(BYTE)
FieldType.ByteArray -> out.value(BYTE_ARRAY)
FieldType.Char -> out.value(CHAR)
FieldType.Double -> out.value(DOUBLE)
FieldType.Duration -> out.value(DURATION)
FieldType.Float -> out.value(FLOAT)
FieldType.Instant -> out.value(INSTANT)
FieldType.Integer -> out.value(INTEGER)
FieldType.Long -> out.value(LONG)
FieldType.Short -> out.value(SHORT)
FieldType.String -> out.value(STRING)
is FieldType.Array -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, ARRAY)
out.writeNamedField(DataHubLedger.gson, TYPE_PARAMETER_FIELD, value.itemFieldType)
}
}
is FieldType.Enum -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, ENUM)
out.writeNamedField(DataHubLedger.gson, NAME_FIELD, value.name)
out.writeNamedStringArray(DataHubLedger.gson, VALUES_FIELD, value.possibleValues)
}
}
is FieldType.List -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, LIST)
out.writeNamedField(DataHubLedger.gson, TYPE_PARAMETER_FIELD, value.itemFieldType)
}
}
is FieldType.Nested -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, NESTED)
out.writeNamedField(DataHubLedger.gson, NAME_FIELD, value.name)
}
}
is FieldType.Nullable -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, NULLABLE)
out.writeNamedField(DataHubLedger.gson, TYPE_PARAMETER_FIELD, value.itemFieldType)
}
}
is FieldType.Opaque -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, OPAQUE)
out.writeNamedField(DataHubLedger.gson, NAME_FIELD, value.name)
}
}
is FieldType.Reference -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, REFERENCE)
out.writeNamedField(DataHubLedger.gson, NAME_FIELD, value.name)
}
}
is FieldType.Tuple -> {
out.makeObject {
out.writeNamedField(DataHubLedger.gson, TYPE_FIELD, TUPLE)
out.writeNamedArray(DataHubLedger.gson, TYPE_PARAMETERS_FIELD, value.itemFieldTypes) {
it.javaClass.toGenericString()
}
}
}
}
}
override fun read(reader: JsonReader): FieldType {
if (reader.peek() == JsonToken.STRING) {
val typeName = reader.nextString()
return requireNotNull(STRING_TO_FIELDTYPE[typeName]) {
"Unrecognized field type: $typeName"
}
}
var type = ""
var name: String? = null
var typeParameter: FieldType? = null
var typeParameters = emptyList<FieldType>()
var possibleValues = emptyList<String>()
reader.readObject {
when (it) {
NAME_FIELD -> name = nextString()
TYPE_FIELD -> type = nextString()
TYPE_PARAMETER_FIELD -> typeParameter = read(reader)
TYPE_PARAMETERS_FIELD -> typeParameters = readList(DataHubLedger.gson)
VALUES_FIELD -> possibleValues = readStringList()
else -> throw IllegalArgumentException("Unexpected key FieldType: \"$it\" at $path")
}
}
return when (type) {
ARRAY ->
FieldType.Array(requireNotNull(typeParameter) { "Expected type parameter for Array" })
ENUM -> FieldType.Enum(requireNotNull(name) { "Expected name for Enum" }, possibleValues)
LIST -> FieldType.List(requireNotNull(typeParameter) { "Expected type parameter for List" })
NESTED -> FieldType.Nested(requireNotNull(name) { "Expected name for Nested" })
NULLABLE ->
FieldType.Nullable(
requireNotNull(typeParameter) { "Expected type parameter for Nullable" }
)
OPAQUE -> FieldType.Opaque(requireNotNull(name) { "Expected name for Opaque" })
REFERENCE -> FieldType.Reference(requireNotNull(name) { "Expected name for Reference" })
TUPLE -> FieldType.Tuple(typeParameters)
else -> throw IllegalArgumentException("Unexpected FieldType type: \"$type\"")
}
}
}
}
| java/com/google/android/libraries/pcc/chronicle/tools/ledger/DtdJson.kt | 425183348 |
package org.xwiki.android.sync.auth
import android.accounts.AccountManager
import android.content.Intent
import android.util.Log
import androidx.core.view.get
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import junit.framework.TestCase
import okhttp3.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.xwiki.android.sync.*
import java.io.IOException
import java.net.URL
/**
* AuthenticatorActivityTest
*/
private const val TEST_USERNAME = "aa700"
private const val TEST_PASSWORD = "a7890"
@RunWith(AndroidJUnit4::class)
@MediumTest
class AuthenticatorActivityTest : LifecycleObserver {
private lateinit var activityScenario: ActivityScenario<AuthenticatorActivity>
@Before
fun setUp() {
val i = Intent(appContext, AuthenticatorActivity::class.java)
val authTokenType = AUTHTOKEN_TYPE_FULL_ACCESS + "android.uid.system"
i.putExtra(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE)
i.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType)
i.putExtra(IS_SETTING_SYNC_TYPE, false)
i.putExtra("Test", true)
activityScenario = ActivityScenario.launch(i)
}
@Test
fun testServerUrl () {
activityScenario.onActivity {
it.showViewFlipper(0)
}
activityScenario.close()
}
@Test
fun testSignUp() {
activityScenario.onActivity {
it.showViewFlipper(1)
it.signUp(it.binding.viewFlipper[1])
}
activityScenario.moveToState(Lifecycle.State.STARTED)
activityScenario.close()
}
@Test
fun testSignIn() {
activityScenario.onActivity {
it.showViewFlipper(0)
}
onView(withId(R.id.btViewSignInFlipper)).perform(click())
onView(withId(R.id.accountName))
.perform(typeText(TEST_USERNAME)) // Test user, for log in
onView(withId(R.id.accountPassword))
.perform(typeText(TEST_PASSWORD), closeSoftKeyboard())
onView(withId(R.id.signInButton)).perform(click())
}
@Test
fun checkOIDCSupport() {
activityScenario.moveToState(Lifecycle.State.STARTED)
val url = URL ("$XWIKI_DEFAULT_SERVER_ADDRESS/oidc/")
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
println(response)
TestCase.assertTrue(response.isSuccessful)
}
override fun onFailure(call: Call, e: IOException) {
Log.e("Test", e.localizedMessage)
}
})
}
@After
fun closeActivity() {
activityScenario.close()
}
} | app/src/androidTest/java/org/xwiki/android/sync/auth/AuthenticatorActivityTest.kt | 3684714667 |
package name.cantanima.chineseremainderclock
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color.*
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.util.TypedValue.COMPLEX_UNIT_SP
import android.view.MotionEvent
import android.view.MotionEvent.*
import android.view.View
import kotlin.math.max
class FlexibleNumberPicker(context: Context, attrs: AttributeSet)
: View(context, attrs), View.OnTouchListener
{
val tag = "FlexibleNumberPicker"
var min : Int = 0
set(new_min) {
field = new_min
value = (min + max) / 2
}
var max : Int = 10
set(new_max) {
field = new_max
value = (min + max) / 2
}
var skip : Int = 1
var value : Int = ( max + min ) / 2
var text_size = 12f
var high_size = 14f
var typeface = if (Typeface.DEFAULT != null) Typeface.DEFAULT else null
var back_color = BLACK
var text_color = WHITE
var high_color = YELLOW
var horizontal = true
var text_paint = Paint()
var high_paint = Paint()
var back_paint = Paint()
val bounds = Rect()
var single_width = 0
var view_width = 0
var view_height = 0
var draw_offset = 0f
var padding_above = 5
var padding_below = 5
var padding_left = 5
var padding_right = 5
var padding_between = 5
var moving = false
var xprev = 0f
init {
val resources = context.resources
val choices = context.obtainStyledAttributes(attrs, R.styleable.FlexibleNumberPicker)
min = choices.getInt(R.styleable.FlexibleNumberPicker_min, min)
max = choices.getInt(R.styleable.FlexibleNumberPicker_max, max)
skip = choices.getInt(R.styleable.FlexibleNumberPicker_skip, skip)
value = choices.getInt(R.styleable.FlexibleNumberPicker_initial, value)
// TODO: typeface
text_size = choices.getFloat(R.styleable.FlexibleNumberPicker_text_size, text_size)
high_size = choices.getFloat(R.styleable.FlexibleNumberPicker_high_size, high_size)
back_color = choices.getColor(R.styleable.FlexibleNumberPicker_back_color, back_color)
high_color = choices.getColor(R.styleable.FlexibleNumberPicker_high_color, high_color)
text_color = choices.getColor(R.styleable.FlexibleNumberPicker_text_color, text_color)
horizontal = choices.getBoolean(R.styleable.FlexibleNumberPicker_horizontal, horizontal)
choices.recycle()
text_size = TypedValue.applyDimension(COMPLEX_UNIT_SP, text_size, resources.displayMetrics)
high_size = TypedValue.applyDimension(COMPLEX_UNIT_SP, high_size, resources.displayMetrics)
text_paint.typeface = typeface
text_paint.textSize = text_size
text_paint.color = text_color
text_paint.isAntiAlias = true
high_paint.typeface = typeface
high_paint.textSize = high_size
high_paint.color = high_color
high_paint.isAntiAlias = true
back_paint.color = back_color
back_paint.style = Paint.Style.FILL
setOnTouchListener(this)
}
/**
* Implement this to do your drawing.
*
* @param canvas the canvas on which the background will be drawn
*/
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas!!.drawRect(
0f, 0f,
view_width.toFloat(),
view_height.toFloat(),
back_paint
)
canvas.drawText(
value.toString(),
view_width / 2f - single_width / 2 + draw_offset,
(view_height.toFloat() - high_paint.descent() - high_paint.ascent()) / 2,
high_paint
)
if (value > min)
canvas.drawText(
(value - skip).toString(),
view_width / 2f - single_width * 3 / 2 + draw_offset,
(view_height.toFloat() - text_paint.descent() - text_paint.ascent()) / 2,
text_paint
)
if (value > min + skip)
canvas.drawText(
(value - 2 * skip).toString(),
view_width / 2f - single_width * 5 / 2 + draw_offset,
(view_height.toFloat() - text_paint.descent() - text_paint.ascent()) / 2,
text_paint
)
if (value < max)
canvas.drawText(
" " + (value + skip).toString(),
view_width / 2f + single_width / 2 + draw_offset,
(view_height.toFloat() - text_paint.descent() - text_paint.ascent()) / 2,
text_paint
)
if (value < max - skip)
canvas.drawText(
" " + (value + 2 * skip).toString(),
view_width / 2f + 3 * single_width / 2 + draw_offset,
(view_height.toFloat() - text_paint.descent() - text_paint.ascent()) / 2,
text_paint
)
}
/**
*
*
* Measure the view and its content to determine the measured width and the
* measured height. This method is invoked by [.measure] and
* should be overridden by subclasses to provide accurate and efficient
* measurement of their contents.
*
*
*
*
* **CONTRACT:** When overriding this method, you
* *must* call [.setMeasuredDimension] to store the
* measured width and height of this view. Failure to do so will trigger an
* `IllegalStateException`, thrown by
* [.measure]. Calling the superclass'
* [.onMeasure] is a valid use.
*
*
*
*
* The base class implementation of measure defaults to the background size,
* unless a larger size is allowed by the MeasureSpec. Subclasses should
* override [.onMeasure] to provide better measurements of
* their content.
*
*
*
*
* If this method is overridden, it is the subclass's responsibility to make
* sure the measured height and width are at least the view's minimum height
* and width ([.getSuggestedMinimumHeight] and
* [.getSuggestedMinimumWidth]).
*
*
* @param widthMeasureSpec horizontal space requirements as imposed by the parent.
* The requirements are encoded with
* [android.view.View.MeasureSpec].
* @param heightMeasureSpec vertical space requirements as imposed by the parent.
* The requirements are encoded with
* [android.view.View.MeasureSpec].
*
* @see .getMeasuredWidth
* @see .getMeasuredHeight
* @see .setMeasuredDimension
* @see .getSuggestedMinimumHeight
* @see .getSuggestedMinimumWidth
* @see android.view.View.MeasureSpec.getMode
* @see android.view.View.MeasureSpec.getSize
*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
high_paint.getTextBounds((min * 10).toString(), 0, (min * 10).toString().length, bounds)
val min_width = bounds.width()
high_paint.getTextBounds((max * 10).toString(), 0, (max * 10).toString().length, bounds)
val max_width = bounds.width()
single_width = max(min_width, max_width)
view_width = single_width * 3 + padding_between * 2 + padding_left + padding_right
view_height = bounds.height() + padding_above + padding_below
setMeasuredDimension(view_width, view_height)
}
/**
* Called when a touch event is dispatched to a view. This allows listeners to
* get a chance to respond before the target view.
*
* @param v The view the touch event has been dispatched to.
* @param event The MotionEvent object containing full information about
* the event.
* @return True if the listener has consumed the event, false otherwise.
*/
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
// let's get some information on where the touch occurred
val x = event!!.rawX
val y = event.rawY
val my_loc = intArrayOf(0, 0)
getLocationOnScreen(my_loc)
if (event.action == ACTION_UP) { // released
moving = false
} else if (event.action == ACTION_MOVE) { // moved/dragged
if (moving) {
var redraw = true
draw_offset += x - xprev
if (draw_offset <= -single_width) {
if (value < max)
value += skip
else
redraw = false
draw_offset = 0f
} else if (draw_offset >= single_width) {
if (value > min)
value -= skip
else
redraw = false
draw_offset = 0f
}
xprev = x
if (redraw) invalidate()
}
} else if (event.action == ACTION_DOWN) { // pressed down
Log.d(tag, "down at $x , $y")
Log.d(tag, "checking within " +
my_loc[0].toString() + "-" + (my_loc[0] + view_width).toString() + " , " +
my_loc[1].toString() + "-" + (my_loc[1] + view_height).toString()
)
if (
(x > my_loc[0]) and (y > my_loc[1]) and
(x < my_loc[0] + view_width) and (y < my_loc[1] + view_height)
) {
moving = true
xprev = x
}
}
return true
}
} | app/src/main/java/name/cantanima/chineseremainderclock/FlexibleNumberPicker.kt | 754747823 |
package test.assertk
actual val exceptionPackageName = "java.lang."
actual val opentestPackageName = "org.opentest4j."
| assertk/src/jvmTest/kotlin/test/assertk/exceptionName.kt | 1215038657 |
/*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider.sample
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
internal class StringAdapter(
private val isRecyclerViewVertical: Boolean,
private val fullSpanPositions: List<Int> = emptyList()
) : ListAdapter<String, StringAdapter.ViewHolder>(StringDiffUtil) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(parent, isRecyclerViewVertical)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position), position in fullSpanPositions)
}
private object StringDiffUtil : DiffUtil.ItemCallback<String>() {
override fun areItemsTheSame(oldItem: String, newItem: String): Boolean = oldItem.hashCode() == newItem.hashCode()
override fun areContentsTheSame(oldItem: String, newItem: String): Boolean = oldItem == newItem
}
class ViewHolder private constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: String, isFullSpan: Boolean) {
(itemView.layoutParams as? StaggeredGridLayoutManager.LayoutParams)?.isFullSpan = isFullSpan
(itemView as TextView).text = item
}
companion object {
operator fun invoke(parent: ViewGroup, isRecyclerViewVertical: Boolean): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
@LayoutRes val layoutRes = if (isRecyclerViewVertical) {
R.layout.cell_vertical_recycler
} else {
R.layout.cell_horizontal_recycler
}
val inflatedView = inflater.inflate(layoutRes, parent, false)
return ViewHolder(inflatedView)
}
}
}
}
| sample/src/main/kotlin/com/fondesa/recyclerviewdivider/sample/StringAdapter.kt | 875472989 |
/*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.views.timeline
import javafx.scene.Parent
import javafx.scene.control.ScrollPane
import javafx.scene.control.SplitPane
import javafx.scene.shape.Rectangle
interface TimelineWidget {
val name: String
/**
* UI weight of this widget. The default sort order of the widgets in the
* timeline view will be by ascending weight, with the "lighter" ones on top.
*/
val weight: Int
val rootNode: Parent
fun dispose()
interface TimelineWidgetUpdateTask : Runnable
val timelineWidgetUpdateTask: TimelineWidgetUpdateTask?
/**
* Many widgets will use a SplitPane to separate a tree or info pane on the
* left, and a time-based pane on the right. This method is used to return
* this pane so the manager can apply common operations on them.
*
* @return The horizontal split pane, or 'null' if the widget doesn't use
* one and uses the full horizontal width of the view.
*/
val splitPane: SplitPane?
val timeBasedScrollPane: ScrollPane?
val selectionRectangle: Rectangle?
val ongoingSelectionRectangle: Rectangle?
} | lttng-scope/src/main/kotlin/org/lttng/scope/views/timeline/TimelineWidget.kt | 737787532 |
package io.skygear.plugins.chat.ui
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.stfalcon.chatkit.messages.MessageHolders
import com.stfalcon.chatkit.utils.DateFormatter
import io.skygear.plugins.chat.R
import io.skygear.plugins.chat.ui.model.VoiceMessage
class IncomingVoiceMessageView(view: View):
MessageHolders.IncomingTextMessageViewHolder<VoiceMessage>(view)
{
var actionButton: ImageView? = null
var durationTextView: TextView? = null
var timeTextView: TextView? = null
init {
this.actionButton = view.findViewById<ImageView>(R.id.action_button)
this.durationTextView = view.findViewById<TextView>(R.id.duration)
this.timeTextView = view.findViewById<TextView>(R.id.time)
}
override fun onBind(message: VoiceMessage?) {
super.onBind(message)
message?.let { msg ->
val durationInSecond = msg.duration / 1000
[email protected]?.text =
String.format("%02d:%02d", durationInSecond / 60, durationInSecond % 60)
[email protected]?.text =
DateFormatter.format(msg.createdAt, DateFormatter.Template.TIME)
val actionButtonIcon = when(msg.state) {
VoiceMessage.State.PLAYING -> R.drawable.ic_pause
else -> R.drawable.ic_play
}
[email protected]?.setImageResource(actionButtonIcon)
}
}
}
| chat/src/main/java/io/skygear/plugins/chat/ui/IncomingVoiceMessageView.kt | 2756065437 |
package com.incentive.yellowpages.misc.converter
import android.content.Context
import com.incentive.yellowpages.data.model.LegendEnum
import com.incentive.yellowpages.data.model.ListingResponse
import com.incentive.yellowpages.data.model.MhdEnum
import com.incentive.yellowpages.data.model.WeekDayEnum
import com.incentive.yellowpages.data.remote.ApiContract
import com.incentive.yellowpages.injection.ApplicationContext
import com.incentive.yellowpages.ui.base.BaseApplication
import okhttp3.ResponseBody
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import retrofit2.Converter
import retrofit2.Retrofit
import timber.log.Timber
import java.io.IOException
import java.lang.reflect.Type
class ListingConverter : Converter<ResponseBody, ListingResponse> {
companion object {
private val PREFIX_PHONE_NUMBER = "•"
private val PREFIX_DISTRICT = "("
internal val INSTANCE = ListingConverter()
}
@ApplicationContext val context: Context = BaseApplication.appComponent.context()
class Factory : Converter.Factory() {
override fun responseBodyConverter(type: Type?, annotations: Array<Annotation>?,
retrofit: Retrofit?): Converter<ResponseBody, *> {
return INSTANCE
}
}
@Throws(IOException::class)
override fun convert(value: ResponseBody): ListingResponse? {
val builder = ListingResponse.Builder()
val document = Jsoup.parse(value.string(), ApiContract.BASE)
val fieldSets = document.select("fieldset") ?: return null
for (fieldSet in fieldSets) {
val legendEnum = LegendEnum.fromString(context, fieldSet.select("legend").text()) ?: continue
when (legendEnum) {
LegendEnum.CONTACT_INFORMATION -> parseContactInformation(fieldSet, builder)
}
}
return builder.build()
}
private fun parseContactInformation(fieldSet: Element, builder: ListingResponse.Builder) {
val ulClassContactInfo = fieldSet.select("ul[class=contactInfo]").first()
if (null != ulClassContactInfo) {
val mhds = ulClassContactInfo.select("li[class=mhd]") ?: return
for (e in mhds) {
val mhdEnum = MhdEnum.fromString(context, e.text()) ?: continue
when (mhdEnum) {
MhdEnum.EXECUTIVE -> parseExecutives(e.nextElementSibling(), builder)
MhdEnum.ADDRESS_TELEPHONE -> parseAddressTelephone(e.nextElementSibling(), builder)
MhdEnum.WEBSITE -> parseWebsite(e.nextElementSibling(), builder)
MhdEnum.LISTING_IN_SPYUR -> parseListingInSpyur(e.nextElementSibling(), builder)
}
}
val images = fieldSet.select("div[class=div-img]")
if (!images.isEmpty()) {
parseImages(images, builder)
}
val videos = fieldSet.select("div#Slide_video")
if (!videos.isEmpty()) {
parseVideos(videos, builder)
}
}
}
private fun parseVideos(videos: Elements, builder: ListingResponse.Builder) {
builder.setVideoUrl(videos.select("a[class=fl curimg]").first().attr("id"))
}
private fun parseImages(images: Elements, builder: ListingResponse.Builder) {
for (imageDiv in images) {
builder.addImage(imageDiv.select("a").first().attr("abs:href"))
}
}
private fun parseListingInSpyur(element: Element?, builder: ListingResponse.Builder) {
if (null == element) return
builder.setListingInSpyur(element.text())
}
private fun parseWebsite(element: Element?, builder: ListingResponse.Builder) {
if (null == element) return
val websiteDivs = element.select("div > div") ?: return
for (div in websiteDivs) {
builder.addWebsite(div.text())
}
}
private fun parseAddressTelephone(address: Element?, builder: ListingResponse.Builder) {
if (null == address) return
val divs = address.select("li > div") ?: return
var contactInfoBuilder: ListingResponse.ContactInfo.Builder
for (div in divs) {
contactInfoBuilder = ListingResponse.ContactInfo.Builder()
val a = div.select("div > a").first()
if (null != a) {
try {
val lat = java.lang.Double.parseDouble(a.attr("lat"))
val lon = java.lang.Double.parseDouble(a.attr("lon"))
contactInfoBuilder.setLocation(lat, lon)
} catch (ignored: NumberFormatException) {
}
}
contactInfoBuilder.setAddress(div.ownText())
// Region information
val childDivs = div.select("div > div")
if (null != childDivs && childDivs.size > 0) {
var e: Element? = childDivs.first()
do {
val text = e!!.text()
if (text.startsWith(PREFIX_DISTRICT)) {
contactInfoBuilder.setRegion(text.substring(1, text.length - 1))
} else if (text.startsWith(PREFIX_PHONE_NUMBER)) {
try {
contactInfoBuilder.addPhoneNumber(text
.substring(1)
.trim { it <= ' ' }
.replace("-", ""))
} catch (ignored: IndexOutOfBoundsException) {
Timber.e(ignored.message)
}
} else {
parseWorkingDays(e, builder)
}
e = e.nextElementSibling()
} while (e != null)
}
builder.addContactInfo(contactInfoBuilder.build())
}
}
private fun parseWorkingDays(element: Element?, builder: ListingResponse.Builder) {
if (null == element) return
val splittedWorkDays = element.text().split("\\s+".toRegex())
val workingDaysBuilder = ListingResponse.WorkingDays.Builder()
for (workingDay in splittedWorkDays) {
if (workingDay.length > 3) continue
val weekDayEnum = WeekDayEnum.fromString(context, workingDay)
when (weekDayEnum) {
WeekDayEnum.MON -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.MON)
WeekDayEnum.TUE -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.TUE)
WeekDayEnum.WED -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.WED)
WeekDayEnum.THU -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.THU)
WeekDayEnum.FRI -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.FRI)
WeekDayEnum.SAT -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.SAT)
WeekDayEnum.SUN -> workingDaysBuilder.setWorkingDay(ListingResponse.WorkingDays.Day.SUN)
}
}
builder.setWorkingDays(workingDaysBuilder.build())
}
private fun parseExecutives(executives: Element?, builder: ListingResponse.Builder) {
if (null == executives) return
val li = executives.select("li").first()
if (null != li) {
val divs = li.select("div") ?: return
for (e in divs) {
builder.addExecutive(e.text())
}
}
}
}
| app/src/main/kotlin/com/incentive/yellowpages/misc/converter/ListingConverter.kt | 1649445565 |
package coil.sample
enum class AssetType(val fileName: String) {
JPG("jpgs.json"),
GIF("gifs.json"),
SVG("svgs.json"),
MP4("video.mp4")
}
| coil-sample-common/src/main/java/coil/sample/AssetType.kt | 995953667 |
package org.luxons.sevenwonders.engine.cards
import org.luxons.sevenwonders.engine.Player
import org.luxons.sevenwonders.engine.boards.Board
import org.luxons.sevenwonders.engine.resources.*
import org.luxons.sevenwonders.model.resources.ResourceTransactions
import org.luxons.sevenwonders.model.resources.bestPrice
data class Requirements internal constructor(
val gold: Int = 0,
val resources: Resources = emptyResources(),
) {
/**
* Returns information about the extent to which the given [player] meets these requirements, either on its own or
* by buying resources to neighbours.
*/
internal fun assess(player: Player): RequirementsSatisfaction {
if (player.board.gold < gold) {
return RequirementsSatisfaction.missingRequiredGold(gold)
}
if (resources.isEmpty()) {
if (gold > 0) {
return RequirementsSatisfaction.enoughGold(gold)
}
return RequirementsSatisfaction.noRequirements()
}
if (producesRequiredResources(player.board)) {
if (gold > 0) {
return RequirementsSatisfaction.enoughResourcesAndGold(gold)
}
return RequirementsSatisfaction.enoughResources()
}
return satisfactionWithPotentialHelp(player)
}
private fun satisfactionWithPotentialHelp(player: Player): RequirementsSatisfaction {
val options = transactionOptions(resources, player)
val minPrice = options.bestPrice + gold
if (options.isEmpty()) {
return RequirementsSatisfaction.unavailableResources()
}
if (player.board.gold < minPrice) {
return RequirementsSatisfaction.missingGoldForResources(minPrice, options)
}
return RequirementsSatisfaction.metWithHelp(minPrice, options)
}
/**
* Returns whether the given board meets these requirements, if the specified resources are bought from neighbours.
*
* @param board the board to check
* @param boughtResources the resources the player intends to buy
*
* @return true if the given board meets these requirements
*/
internal fun areMetWithHelpBy(board: Board, boughtResources: ResourceTransactions): Boolean {
if (!hasRequiredGold(board, boughtResources)) {
return false
}
return producesRequiredResources(board) || producesRequiredResourcesWithHelp(board, boughtResources)
}
private fun hasRequiredGold(board: Board, resourceTransactions: ResourceTransactions): Boolean {
val resourcesPrice = board.tradingRules.computeCost(resourceTransactions)
return board.gold >= gold + resourcesPrice
}
private fun producesRequiredResources(board: Board): Boolean = board.production.contains(resources)
private fun producesRequiredResourcesWithHelp(board: Board, transactions: ResourceTransactions): Boolean {
val totalBoughtResources = transactions.asResources()
val remainingResources = resources - totalBoughtResources
return board.production.contains(remainingResources)
}
internal fun pay(player: Player, transactions: ResourceTransactions) {
player.board.removeGold(gold)
transactions.execute(player)
}
}
| sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/cards/Requirements.kt | 576540503 |
package net.perfectdreams.loritta.common.utils.extensions
expect fun String.format(vararg arguments: Any?): String | common/src/commonMain/kotlin/net/perfectdreams/loritta/common/utils/extensions/StringExtensions.kt | 2192613605 |
/*
* SimpleImageInfo.java
*
* @version 0.1
* @author Jaimon Mathew <http://www.jaimon.co.uk>
*
* A Java class to determine image width, height and MIME types for a number of image file formats without loading the whole image data.
*
* Revision history
* 0.1 - 29/Jan/2011 - Initial version created
*
* -------------------------------------------------------------------------------
This code is 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.
* -------------------------------------------------------------------------------
*/
import java.io.ByteArrayInputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
class SimpleImageInfo {
var height: Int = 0
var width: Int = 0
var mimeType: String? = null
private constructor()
@Throws(IOException::class)
constructor(file: File) {
val `is` = FileInputStream(file)
try {
processStream(`is`)
} finally {
`is`.close()
}
}
@Throws(IOException::class)
constructor(`is`: InputStream) {
processStream(`is`)
}
@Throws(IOException::class)
constructor(bytes: ByteArray) {
val `is` = ByteArrayInputStream(bytes)
try {
processStream(`is`)
} finally {
`is`.close()
}
}
@Throws(IOException::class)
private fun processStream(`is`: InputStream) {
val c1 = `is`.read()
val c2 = `is`.read()
var c3 = `is`.read()
mimeType = null
height = -1
width = height
if (c1 == 'G'.toInt() && c2 == 'I'.toInt() && c3 == 'F'.toInt()) { // GIF
`is`.skip(3)
width = readInt(`is`, 2, false)
height = readInt(`is`, 2, false)
mimeType = "image/gif"
} else if (c1 == 0xFF && c2 == 0xD8) { // JPG
while (c3 == 255) {
val marker = `is`.read()
val len = readInt(`is`, 2, true)
if (marker == 192 || marker == 193 || marker == 194) {
`is`.skip(1)
height = readInt(`is`, 2, true)
width = readInt(`is`, 2, true)
mimeType = "image/jpeg"
break
}
`is`.skip((len - 2).toLong())
c3 = `is`.read()
}
} else if (c1 == 137 && c2 == 80 && c3 == 78) { // PNG
`is`.skip(15)
width = readInt(`is`, 2, true)
`is`.skip(2)
height = readInt(`is`, 2, true)
mimeType = "image/png"
} else if (c1 == 66 && c2 == 77) { // BMP
`is`.skip(15)
width = readInt(`is`, 2, false)
`is`.skip(2)
height = readInt(`is`, 2, false)
mimeType = "image/bmp"
} else {
val c4 = `is`.read()
if (c1 == 'M'.toInt() && c2 == 'M'.toInt() && c3 == 0 && c4 == 42 || c1 == 'I'.toInt() && c2 == 'I'.toInt() && c3 == 42 && c4 == 0) { //TIFF
val bigEndian = c1 == 'M'.toInt()
var ifd = 0
val entries: Int
ifd = readInt(`is`, 4, bigEndian)
`is`.skip((ifd - 8).toLong())
entries = readInt(`is`, 2, bigEndian)
for (i in 1..entries) {
val tag = readInt(`is`, 2, bigEndian)
val fieldType = readInt(`is`, 2, bigEndian)
val count = readInt(`is`, 4, bigEndian).toLong()
val valOffset: Int
if (fieldType == 3 || fieldType == 8) {
valOffset = readInt(`is`, 2, bigEndian)
`is`.skip(2)
} else {
valOffset = readInt(`is`, 4, bigEndian)
}
if (tag == 256) {
width = valOffset
} else if (tag == 257) {
height = valOffset
}
if (width != -1 && height != -1) {
mimeType = "image/tiff"
break
}
}
}
}
if (mimeType == null) {
throw IOException("Unsupported image type")
}
}
@Throws(IOException::class)
private fun readInt(`is`: InputStream, noOfBytes: Int, bigEndian: Boolean): Int {
var ret = 0
var sv = if (bigEndian) (noOfBytes - 1) * 8 else 0
val cnt = if (bigEndian) -8 else 8
for (i in 0 until noOfBytes) {
ret = ret or (`is`.read() shl sv)
sv += cnt
}
return ret
}
override fun toString(): String {
return "MIME Type : $mimeType\t Width : $width\t Height : $height"
}
} | buildSrc/src/main/kotlin/SimpleImageInfo.kt | 3407876479 |
package com.reindeercrafts.hackernews.modules
import android.app.Application
import android.arch.persistence.room.Room
import com.reindeercrafts.hackernews.CommentLoader
import com.reindeercrafts.hackernews.data.*
import dagger.Module
import dagger.Provides
import retrofit2.Retrofit
import javax.inject.Named
import javax.inject.Singleton
@Module
class ApplicationModule(private val application: Application) {
@Singleton
@Provides
fun provideRoomDatabase(): HackerNewsDatabase {
return Room.databaseBuilder(application, HackerNewsDatabase::class.java, "hacker_news").build()
}
@Provides
@Singleton
fun provideArticleRepository(@Named("localSource") localArticleSource: ArticleSource,
@Named("remoteSource") remoteArticleSource: ArticleSource): ArticleRepository {
return ArticleRepository(localArticleSource, remoteArticleSource)
}
@Provides
@Singleton
@Named("localSource")
fun provideLocalArticleSource(hackerNewsDatabase: HackerNewsDatabase): ArticleSource {
return LocalArticleSource(hackerNewsDatabase.articleDao())
}
@Provides
@Singleton
@Named("remoteSource")
fun providRemoteArticleSource(retrofit: Retrofit, sharedPrefsHelper: SharedPrefsHelper): ArticleSource {
return RemoteArticleSource(retrofit, sharedPrefsHelper)
}
@Provides
@Singleton
fun provideRetrofit(): Retrofit {
return RetrofitHelper.retrofit
}
@Provides
@Singleton
fun providePrefsHelper(): SharedPrefsHelper {
return SharedPrefsHelper(application)
}
@Provides
@Singleton
fun provideCommentLoader(articleRepository: ArticleRepository): CommentLoader {
return CommentLoader(articleRepository)
}
} | app/src/main/java/com/reindeercrafts/hackernews/modules/ApplicationModule.kt | 2900474227 |
package com.darakeon.dfm.moves
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import android.view.View.FOCUS_DOWN
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.darakeon.dfm.R
import com.darakeon.dfm.base.BaseActivity
import com.darakeon.dfm.dialogs.alertError
import com.darakeon.dfm.dialogs.getDateDialog
import com.darakeon.dfm.extensions.ON_CLICK
import com.darakeon.dfm.extensions.addMask
import com.darakeon.dfm.extensions.backWithExtras
import com.darakeon.dfm.extensions.getFromJson
import com.darakeon.dfm.extensions.putJson
import com.darakeon.dfm.lib.api.entities.Date
import com.darakeon.dfm.lib.api.entities.moves.Move
import com.darakeon.dfm.lib.api.entities.moves.MoveCreation
import com.darakeon.dfm.lib.api.entities.moves.Nature
import com.darakeon.dfm.lib.api.entities.setCombo
import com.darakeon.dfm.lib.extensions.applyGlyphicon
import com.darakeon.dfm.lib.extensions.changeColSpan
import com.darakeon.dfm.lib.extensions.onChange
import com.darakeon.dfm.lib.extensions.showChangeList
import com.darakeon.dfm.lib.extensions.toDoubleByCulture
import kotlinx.android.synthetic.main.moves.account_in
import kotlinx.android.synthetic.main.moves.account_in_picker
import kotlinx.android.synthetic.main.moves.account_out
import kotlinx.android.synthetic.main.moves.account_out_picker
import kotlinx.android.synthetic.main.moves.category
import kotlinx.android.synthetic.main.moves.category_picker
import kotlinx.android.synthetic.main.moves.date
import kotlinx.android.synthetic.main.moves.date_picker
import kotlinx.android.synthetic.main.moves.description
import kotlinx.android.synthetic.main.moves.detail_amount
import kotlinx.android.synthetic.main.moves.detail_description
import kotlinx.android.synthetic.main.moves.detail_value
import kotlinx.android.synthetic.main.moves.detailed_value
import kotlinx.android.synthetic.main.moves.details
import kotlinx.android.synthetic.main.moves.form
import kotlinx.android.synthetic.main.moves.main
import kotlinx.android.synthetic.main.moves.nature_in
import kotlinx.android.synthetic.main.moves.nature_out
import kotlinx.android.synthetic.main.moves.nature_transfer
import kotlinx.android.synthetic.main.moves.no_accounts
import kotlinx.android.synthetic.main.moves.no_categories
import kotlinx.android.synthetic.main.moves.remove_check
import kotlinx.android.synthetic.main.moves.simple_value
import kotlinx.android.synthetic.main.moves.value
import kotlinx.android.synthetic.main.moves.warnings
import java.util.UUID
class MovesActivity : BaseActivity() {
override val contentView = R.layout.moves
override val title = R.string.title_activity_move
private var move = Move()
private val moveKey = "move"
private var moveForm = MoveCreation()
private val moveFormKey = "moveForm"
private var offlineHash = 0
private val offlineHashKey = "offlineHash"
private var accountUrl = ""
private var id: UUID? = null
private val amountDefault
get() = resources.getInteger(
R.integer.amount_default
).toString()
override val refresh: SwipeRefreshLayout?
get() = main
private var loadedScreen = false
private val fallbackManager = MovesService.manager(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arrayOf(
date_picker,
category_picker,
account_out_picker,
account_in_picker
).forEach { it.applyGlyphicon() }
accountUrl = getExtraOrUrl("accountUrl") ?: ""
val id = getExtraOrUrl("id")
if (id != null)
this.id = tryGetGuid(id)
detail_amount.setText(amountDefault)
if (savedInstanceState == null) {
if (this.id != null) {
callApi { it.getMove(this.id, this::populateScreen) }
} else {
move.date = Date()
populateResponse()
}
} else {
move = savedInstanceState.getFromJson(moveKey, Move())
moveForm = savedInstanceState.getFromJson(moveFormKey, MoveCreation())
offlineHash = savedInstanceState.getInt(offlineHashKey, 0)
populateResponse()
}
}
private fun tryGetGuid(id: String?) =
try {
UUID.fromString(id)
} catch (e: IllegalArgumentException) {
null
}
private fun populateScreen(data: MoveCreation) {
moveForm = data
val move = data.move
var error = ""
if (move != null) {
this.move = move
} else {
fallbackManager.printCounting()
val previousError = fallbackManager.error
if (previousError == null) {
this.move.date = Date()
} else {
this.move = previousError.obj
error = previousError.error
offlineHash = previousError.hashCode()
}
}
populateResponse()
if (error != "") {
val tried = getString(R.string.background_move_error)
alertError("$tried: $error")
}
}
private fun populateResponse() {
move.setDefaultData(accountUrl, isUsingCategories)
if (!isMoveAllowed())
return
main.scrollChild = form
if (move.checked)
remove_check.visibility = VISIBLE
description.setText(move.description)
description.onChange { move.description = it }
populateDate()
populateCategory()
populateAccounts()
setNatureFromAccounts()
populateValue()
loadedScreen = true
}
private fun isMoveAllowed(): Boolean {
var canMove = true
if (blockedByAccounts()) {
canMove = false
no_accounts.visibility = VISIBLE
}
if (blockedByCategories()) {
canMove = false
no_categories.visibility = VISIBLE
}
if (!canMove) {
form.visibility = GONE
warnings.visibility = VISIBLE
}
return canMove
}
private fun blockedByAccounts() =
accountCombo.isEmpty()
private fun blockedByCategories() =
isUsingCategories && categoryCombo.isEmpty()
private fun populateDate() {
date.addMask("####-##-##")
date.setText(move.date.format())
date.onChange { move.date = Date(it) }
date_picker.setOnClickListener { showDatePicker() }
}
fun showDatePicker() {
with(move.date) {
getDateDialog(year, javaMonth, day) { y, m, d ->
date.setText(Date(y, m+1, d).format())
}.show()
}
}
private fun populateCategory() {
when {
isUsingCategories -> {
populateCategoryCombo()
}
move.warnCategory -> {
setupWarnLoseCategory()
}
else -> {
hideCategory()
}
}
}
private fun populateCategoryCombo() {
categoryCombo.setCombo(
category,
category_picker,
move::categoryName,
this::changeCategory
)
}
fun changeCategory() {
showChangeList(categoryCombo, R.string.category) {
text, _ -> category.setText(text)
}
}
private fun setupWarnLoseCategory() {
category.visibility = GONE
category.changeColSpan(0)
category_picker.changeColSpan(4)
category_picker.text = move.categoryName
category_picker.paintFlags += Paint.STRIKE_THRU_TEXT_FLAG
category_picker.setOnClickListener {
this.alertError(R.string.losingCategory)
}
}
private fun hideCategory() {
category.visibility = GONE
category_picker.visibility = GONE
date.changeColSpan(7)
category.changeColSpan(0)
category_picker.changeColSpan(0)
}
private fun populateAccounts() {
accountCombo.setCombo(
account_out,
account_out_picker,
move::outUrl,
this::changeAccountOut
)
account_out.onChange {
setNatureFromAccounts()
}
accountCombo.setCombo(
account_in,
account_in_picker,
move::inUrl,
this::changeAccountIn
)
account_in.onChange {
setNatureFromAccounts()
}
}
fun changeAccountOut() {
showChangeList(accountCombo, R.string.account) { text, _ ->
account_out.setText(text)
}
}
fun changeAccountIn() {
showChangeList(accountCombo, R.string.account) { text, _ ->
account_in.setText(text)
}
}
private fun setNatureFromAccounts() {
val hasOut = !move.outUrl.isNullOrBlank()
val hasIn = !move.inUrl.isNullOrBlank()
when {
hasOut && hasIn -> move.natureEnum = Nature.Transfer
hasOut -> move.natureEnum = Nature.Out
hasIn -> move.natureEnum = Nature.In
else -> move.natureEnum = null
}
runOnUiThread {
nature_out.isChecked = false
nature_transfer.isChecked = false
nature_in.isChecked = false
when (move.natureEnum) {
Nature.Out -> nature_out.isChecked = true
Nature.Transfer -> nature_transfer.isChecked = true
Nature.In -> nature_in.isChecked = true
else -> {}
}
}
}
private fun populateValue() {
if (move.detailList.isNotEmpty()) {
useDetailed()
move.detailList.forEach {
addViewDetail(move, it.description, it.amount, it.value)
}
} else if (move.value != null) {
useSimple()
value.setText(String.format("%1$,.2f", move.value))
}
value.onChange { move.setValue(it) }
}
private fun useDetailed() {
move.isDetailed = true
simple_value.visibility = GONE
detailed_value.visibility = VISIBLE
account_in.nextFocusDownId = R.id.detail_description
scrollToTheEnd(detail_description)
}
private fun addViewDetail(move: Move, description: String, amount: Int, value: Double) {
val row = DetailBox(this, move, description, amount, value)
details.addView(row)
}
private fun useSimple() {
move.isDetailed = false
simple_value.visibility = VISIBLE
detailed_value.visibility = GONE
account_in.nextFocusDownId = R.id.value
scrollToTheEnd(value)
}
private fun scrollToTheEnd(view: View) {
form.post {
form.fullScroll(FOCUS_DOWN)
view.requestFocus()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putJson(moveKey, move)
outState.putJson(moveFormKey, moveForm)
outState.putInt(offlineHashKey, offlineHash)
}
fun useDetailed(@Suppress(ON_CLICK) view: View) {
useDetailed()
}
fun useSimple(@Suppress(ON_CLICK) view: View) {
useSimple()
}
fun addDetail(@Suppress(ON_CLICK) view: View) {
val description = detail_description.text.toString()
val amount = detail_amount.text.toString().toIntOrNull()
val value = detail_value.text.toString().toDoubleByCulture()
if (description.isEmpty() || amount == null || value == null) {
alertError(R.string.fill_all)
return
}
detail_description.setText("")
detail_amount.setText(amountDefault)
detail_value.setText("")
move.add(description, amount, value)
addViewDetail(move, description, amount, value)
scrollToTheEnd(detail_description)
}
fun save(@Suppress(ON_CLICK) view: View) {
move.clearNotUsedValues()
callApi {
it.saveMove(move) {
fallbackManager.remove(offlineHash)
clearAndBack()
}
}
}
override fun offline() {
if (loadedScreen) {
error(R.string.offline_fallback_moves, R.string.ok_button) {
MovesService.start(this, move)
clearAndBack()
}
} else {
super.offline()
}
}
private fun clearAndBack() {
intent.removeExtra("id")
backWithExtras()
}
fun cancel(@Suppress(ON_CLICK) view: View) {
fallbackManager.remove(offlineHash)
backWithExtras()
}
}
| android/App/src/main/kotlin/com/darakeon/dfm/moves/MovesActivity.kt | 3849596497 |
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.tls.internal.der
import java.math.BigInteger
import java.net.ProtocolException
import okio.Buffer
import okio.BufferedSource
import okio.ByteString
import okio.ForwardingSource
import okio.IOException
import okio.Source
import okio.buffer
/**
* Streaming decoder of data encoded following Abstract Syntax Notation One (ASN.1). There are
* multiple variants of ASN.1, including:
*
* * DER: Distinguished Encoding Rules. This further constrains ASN.1 for deterministic encoding.
* * BER: Basic Encoding Rules.
*
* This class was implemented according to the [X.690 spec][[x690]], and under the advice of
* [Lets Encrypt's ASN.1 and DER][asn1_and_der] guide.
*
* [x690]: https://www.itu.int/rec/T-REC-X.690
* [asn1_and_der]: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/
*/
internal class DerReader(source: Source) {
private val countingSource: CountingSource = CountingSource(source)
private val source: BufferedSource = countingSource.buffer()
/** Total bytes read thus far. */
private val byteCount: Long
get() = countingSource.bytesRead - source.buffer.size
/** How many bytes to read before [peekHeader] should return false, or -1L for no limit. */
private var limit = -1L
/** Type hints scoped to the call stack, manipulated with [withTypeHint]. */
private val typeHintStack = mutableListOf<Any?>()
/**
* The type hint for the current object. Used to pick adapters based on other fields, such as
* in extensions which have different types depending on their extension ID.
*/
var typeHint: Any?
get() = typeHintStack.lastOrNull()
set(value) {
typeHintStack[typeHintStack.size - 1] = value
}
/** Names leading to the current location in the ASN.1 document. */
private val path = mutableListOf<String>()
private var constructed = false
private var peekedHeader: DerHeader? = null
private val bytesLeft: Long
get() = if (limit == -1L) -1L else (limit - byteCount)
fun hasNext(): Boolean = peekHeader() != null
/**
* Returns the next header to process unless this scope is exhausted.
*
* This returns null if:
*
* * The stream is exhausted.
* * We've read all of the bytes of an object whose length is known.
* * We've reached the [DerHeader.TAG_END_OF_CONTENTS] of an object whose length is unknown.
*/
fun peekHeader(): DerHeader? {
var result = peekedHeader
if (result == null) {
result = readHeader()
peekedHeader = result
}
if (result.isEndOfData) return null
return result
}
/**
* Consume the next header in the stream and return it. If there is no header to read because we
* have reached a limit, this returns [END_OF_DATA].
*/
private fun readHeader(): DerHeader {
require(peekedHeader == null)
// We've hit a local limit.
if (byteCount == limit) return END_OF_DATA
// We've exhausted the source stream.
if (limit == -1L && source.exhausted()) return END_OF_DATA
// Read the tag.
val tagAndClass = source.readByte().toInt() and 0xff
val tagClass = tagAndClass and 0b1100_0000
val constructed = (tagAndClass and 0b0010_0000) == 0b0010_0000
val tag0 = tagAndClass and 0b0001_1111
val tag = when (tag0) {
0b0001_1111 -> readVariableLengthLong()
else -> tag0.toLong()
}
// Read the length.
val length0 = source.readByte().toInt() and 0xff
val length = when {
length0 == 0b1000_0000 -> {
// Indefinite length.
-1L
}
(length0 and 0b1000_0000) == 0b1000_0000 -> {
// Length specified over multiple bytes.
val lengthBytes = length0 and 0b0111_1111
var lengthBits = source.readByte().toLong() and 0xff
for (i in 1 until lengthBytes) {
lengthBits = lengthBits shl 8
lengthBits += source.readByte().toInt() and 0xff
}
lengthBits
}
else -> {
// Length is 127 or fewer bytes.
(length0 and 0b0111_1111).toLong()
}
}
// Note that this may be be an encoded "end of data" header.
return DerHeader(tagClass, tag, constructed, length)
}
/**
* Consume a header and execute [block], which should consume the entire value described by the
* header. It is an error to not consume a full value in [block].
*/
internal inline fun <T> read(name: String?, block: (DerHeader) -> T): T {
if (!hasNext()) throw IOException("expected a value")
val header = peekedHeader!!
peekedHeader = null
val pushedLimit = limit
val pushedConstructed = constructed
limit = if (header.length != -1L) byteCount + header.length else -1L
constructed = header.constructed
if (name != null) path += name
try {
return block(header)
} finally {
peekedHeader = null
limit = pushedLimit
constructed = pushedConstructed
if (name != null) path.removeAt(path.size - 1)
}
}
private inline fun readAll(block: (DerHeader) -> Unit) {
while (hasNext()) {
read(null, block)
}
}
/**
* Execute [block] with a new namespace for type hints. Type hints from the enclosing type are no
* longer usable by the current type's members.
*/
fun <T> withTypeHint(block: () -> T): T {
typeHintStack.add(null)
try {
return block()
} finally {
typeHintStack.removeAt(typeHintStack.size - 1)
}
}
fun readBoolean(): Boolean {
if (bytesLeft != 1L) throw ProtocolException("unexpected length: $bytesLeft at $this")
return source.readByte().toInt() != 0
}
fun readBigInteger(): BigInteger {
if (bytesLeft == 0L) throw ProtocolException("unexpected length: $bytesLeft at $this")
val byteArray = source.readByteArray(bytesLeft)
return BigInteger(byteArray)
}
fun readLong(): Long {
if (bytesLeft !in 1..8) throw ProtocolException("unexpected length: $bytesLeft at $this")
var result = source.readByte().toLong() // No "and 0xff" because this is a signed value!
while (byteCount < limit) {
result = result shl 8
result += source.readByte().toInt() and 0xff
}
return result
}
fun readBitString(): BitString {
val buffer = Buffer()
val unusedBitCount = readBitString(buffer)
return BitString(buffer.readByteString(), unusedBitCount)
}
private fun readBitString(sink: Buffer): Int {
if (bytesLeft != -1L) {
val unusedBitCount = source.readByte().toInt() and 0xff
source.read(sink, bytesLeft)
return unusedBitCount
} else {
var unusedBitCount = 0
readAll {
unusedBitCount = readBitString(sink)
}
return unusedBitCount
}
}
fun readOctetString(): ByteString {
val buffer = Buffer()
readOctetString(buffer)
return buffer.readByteString()
}
private fun readOctetString(sink: Buffer) {
if (bytesLeft != -1L && !constructed) {
source.read(sink, bytesLeft)
} else {
readAll {
readOctetString(sink)
}
}
}
fun readUtf8String(): String {
val buffer = Buffer()
readUtf8String(buffer)
return buffer.readUtf8()
}
private fun readUtf8String(sink: Buffer) {
if (bytesLeft != -1L && !constructed) {
source.read(sink, bytesLeft)
} else {
readAll {
readUtf8String(sink)
}
}
}
fun readObjectIdentifier(): String {
val result = Buffer()
val dot = '.'.toByte().toInt()
when (val xy = readVariableLengthLong()) {
in 0L until 40L -> {
result.writeDecimalLong(0)
result.writeByte(dot)
result.writeDecimalLong(xy)
}
in 40L until 80L -> {
result.writeDecimalLong(1)
result.writeByte(dot)
result.writeDecimalLong(xy - 40L)
}
else -> {
result.writeDecimalLong(2)
result.writeByte(dot)
result.writeDecimalLong(xy - 80L)
}
}
while (byteCount < limit) {
result.writeByte(dot)
result.writeDecimalLong(readVariableLengthLong())
}
return result.readUtf8()
}
fun readRelativeObjectIdentifier(): String {
val result = Buffer()
val dot = '.'.toByte().toInt()
while (byteCount < limit) {
if (result.size > 0) {
result.writeByte(dot)
}
result.writeDecimalLong(readVariableLengthLong())
}
return result.readUtf8()
}
/** Used for tags and subidentifiers. */
private fun readVariableLengthLong(): Long {
// TODO(jwilson): detect overflow.
var result = 0L
while (true) {
val byteN = source.readByte().toLong() and 0xff
if ((byteN and 0b1000_0000L) == 0b1000_0000L) {
result = (result + (byteN and 0b0111_1111)) shl 7
} else {
return result + byteN
}
}
}
override fun toString() = path.joinToString(separator = " / ")
companion object {
/**
* A synthetic value that indicates there's no more bytes. Values with equivalent data may also
* show up in ASN.1 streams to also indicate the end of SEQUENCE, SET or other constructed
* value.
*/
private val END_OF_DATA = DerHeader(
tagClass = DerHeader.TAG_CLASS_UNIVERSAL,
tag = DerHeader.TAG_END_OF_CONTENTS,
constructed = false,
length = -1L
)
}
/** A source that keeps track of how many bytes it's consumed. */
private class CountingSource(source: Source) : ForwardingSource(source) {
var bytesRead = 0L
override fun read(sink: Buffer, byteCount: Long): Long {
val result = delegate.read(sink, byteCount)
if (result == -1L) return -1L
bytesRead += result
return result
}
}
}
| okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt | 1496227621 |
package com.oukingtim.web.vm
import com.oukingtim.domain.SysMenu
import org.springframework.beans.BeanUtils
/**
* Created by oukingtim
*/
class MenuVM() {
var id: String? = null
var parentId: String? = null
var name: String? = null
var stateRef: String? = null
var type: String? = null
var icon: String? = null
var title: String? = null
var level: Int? = null
var order: Int? = null
var subMenu: List<MenuVM>? = null
constructor(sm : SysMenu):this(){
this.stateRef = sm.name
this.name = sm.name
this.type = sm.type
this.icon = sm.icon
this.title = sm.title
this.level = sm.level
this.order = sm.order
this.parentId = sm.parentId
this.id = sm.id
}
} | king-admin-kotlin/src/main/kotlin/com/oukingtim/web/vm/MenuVM.kt | 1390484092 |
package templates
/**
* Created by allen on 5/18/17.
*/
import kotlinx.html.*
import models.Folder
import views.FolderView
object FolderTemplate {
} | src/main/kotlin/templates/FolderTemplate.kt | 3931102036 |
package me.ycdev.android.devtools.sampler.mem
class ProcMemStat(var pid: Int) {
var memPss = 0 // KB
var memPrivate = 0 // RSS (private dirty memory usage), KB
}
| app/src/main/java/me/ycdev/android/devtools/sampler/mem/ProcMemStat.kt | 3008152196 |
package com.christian.common.data
/**
* A generic class that holds a value with its loading status.
* @param <T>
*/
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
object Loading : Result<Nothing>()
override fun toString(): String {
return when (this) {
is Success<*> -> "Success[data=$data]"
is Error -> "Error[exception=$exception]"
Loading -> "Loading"
}
}
}
/**
* `true` if [Result] is of type [Success] & holds non-null [Success.data].
*/
val Result<*>.succeeded
get() = this is Result.Success && data != null | common/src/main/java/com/christian/common/data/Result.kt | 38510242 |
package github.nisrulz.example.accessinggoogledrive
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import github.nisrulz.example.accessinggoogledrive.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
with(binding) {
setContentView(root)
}
}
} | AccessingGoogleDrive/app/src/main/java/github/nisrulz/example/accessinggoogledrive/MainActivity.kt | 3972874045 |
package com.cout970.magneticraft.systems.integration.crafttweaker
import com.cout970.magneticraft.api.internal.registries.machines.gasificationunit.GasificationUnitRecipeManager
import crafttweaker.annotations.ZenRegister
import crafttweaker.api.item.IIngredient
import crafttweaker.api.item.IItemStack
import crafttweaker.api.liquid.ILiquidStack
import net.minecraft.item.ItemStack
import stanhebben.zenscript.annotations.ZenClass
import stanhebben.zenscript.annotations.ZenMethod
@Suppress("UNUSED")
@ZenClass("mods.magneticraft.GasificationUnit")
@ZenRegister
object GasificationUnit {
@ZenMethod
@JvmStatic
fun addRecipe(input: IIngredient, out1: IItemStack?, out2: ILiquidStack?, ticks: Float, minTemp: Float) {
CraftTweakerPlugin.delayExecution {
val inStack = input.items
val outStack1 = out1?.toStack() ?: ItemStack.EMPTY
val outStack2 = out2?.toStack()
if (inStack != null) {
if (inStack.isEmpty()) {
ctLogError("[GasificationUnit] Invalid input stack: EMPTY")
return@delayExecution
}
}
if (outStack1.isEmpty && outStack2 == null) {
ctLogError("[GasificationUnit] Missing output: item: EMPTY, fluid: null, inputItem: $input")
return@delayExecution
}
if (minTemp < 0) {
ctLogError("[GasificationUnit] Invalid min temperature: $minTemp, must be positive")
return@delayExecution
}
if (ticks < 0) {
ctLogError("[GasificationUnit] Invalid processing time: $ticks, must be positive")
return@delayExecution
}
if (inStack != null) {
for (inputItem in inStack) {
val recipe = GasificationUnitRecipeManager.createRecipe(inputItem.toStack(), outStack1, outStack2, ticks, minTemp, false)
applyAction("Adding $recipe") {
GasificationUnitRecipeManager.registerRecipe(recipe)
}
}
}
}
}
@ZenMethod
@JvmStatic
fun removeRecipe(input: IItemStack) {
CraftTweakerPlugin.delayExecution {
val inStack = input.toStack()
inStack.ifEmpty {
ctLogError("[GasificationUnit] Invalid input stack: EMPTY")
return@delayExecution
}
val recipe = GasificationUnitRecipeManager.findRecipe(inStack)
if (recipe == null) {
ctLogError("[GasificationUnit] Cannot remove recipe: No recipe found for $input")
return@delayExecution
}
applyAction("Removing $recipe") {
GasificationUnitRecipeManager.removeRecipe(recipe)
}
}
}
} | src/main/kotlin/com/cout970/magneticraft/systems/integration/crafttweaker/GasificationUnit.kt | 4072281923 |
// Copyright (c) Akop Karapetyan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package org.akop.ararat.io
import org.akop.ararat.core.Crossword
import org.akop.ararat.util.SparseArray
import org.xmlpull.v1.XmlPullParser
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class CrosswordCompilerFormatter : SimpleXmlParser(), CrosswordFormatter {
private var builder: Crossword.Builder? = null
private val wordBuilders = SparseArray<Crossword.Word.Builder>()
private var cells: Array<Array<CCCell?>>? = null
private var currentWordBuilder: Crossword.Word.Builder? = null
override fun setEncoding(encoding: String) { /* Stub */ }
@Throws(IOException::class)
override fun read(builder: Crossword.Builder, inputStream: InputStream) {
// Initialize state
wordBuilders.clear()
cells = null
currentWordBuilder = null
this.builder = builder
parseXml(inputStream)
wordBuilders.forEach { _, v ->
if (v.number == Crossword.Word.Builder.NUMBER_NONE) {
// For any words that don't have numbers, check the cells
val cell = cells!![v.startRow][v.startColumn]!!
if (cell.number != Crossword.Word.Builder.NUMBER_NONE) {
v.number = cell.number
}
}
builder.words += v.build()
}
}
@Throws(IOException::class)
override fun write(crossword: Crossword, outputStream: OutputStream) {
throw UnsupportedOperationException("Writing not supported")
}
override fun canRead(): Boolean = true
override fun canWrite(): Boolean = false
override fun onStartElement(path: SimpleXmlParser.SimpleXmlPath, parser: XmlPullParser) {
super.onStartElement(path, parser)
if (!path.startsWith("?", "rectangular-puzzle")) return
if (path.startsWith("crossword")) {
if (path.startsWith("grid")) {
if (path.isEqualTo("cell")) {
// ?/rectangular-puzzle/crossword/grid/cell
parser.stringValue("solution")?.let { sol ->
val row = parser.intValue("y", 0) - 1
val column = parser.intValue("x", 0) - 1
val number = parser.intValue("number", Crossword.Word.Builder.NUMBER_NONE)
val cell = CCCell(sol, number)
cells!![row][column] = cell
parser.stringValue("background-shape")?.let {
cell.attr = cell.attr or Crossword.Cell.ATTR_CIRCLED
}
}
} else if (path.isDeadEnd) {
// ?/rectangular-puzzle/crossword/grid
val width = parser.intValue("width", -1)
val height = parser.intValue("height", -1)
cells = Array(height) { arrayOfNulls<CCCell?>(width) }
builder!!.width = width
builder!!.height = height
}
} else if (path.isEqualTo("word")) {
// ?/rectangular-puzzle/crossword/word
val id = parser.intValue("id", -1)
val xSpan = parser.stringValue("x")!!
val ySpan = parser.stringValue("y")!!
val xDashIndex = xSpan.indexOf("-")
val wb = Crossword.Word.Builder()
if (xDashIndex != -1) {
val startColumn = xSpan.substring(0, xDashIndex).toInt() - 1
val endColumn = xSpan.substring(xDashIndex + 1).toInt() - 1
val row = ySpan.toInt() - 1
// Across
wb.direction = Crossword.Word.DIR_ACROSS
wb.startRow = row
wb.startColumn = startColumn
// Build the individual characters from the char map
for (column in startColumn..endColumn) {
val cell = cells!![row][column]!!
wb.addCell(cell.chars, cell.attr)
}
} else {
val yDashIndex = ySpan.indexOf("-")
val startRow = ySpan.substring(0, yDashIndex).toInt() - 1
val endRow = ySpan.substring(yDashIndex + 1).toInt() - 1
val column = xSpan.toInt() - 1
// Down
wb.direction = Crossword.Word.DIR_DOWN
wb.startRow = startRow
wb.startColumn = column
// Build the individual characters from the char map
for (row in startRow..endRow) {
val cell = cells!![row][column]!!
wb.addCell(cell.chars, cell.attr)
}
}
wordBuilders.put(id, wb)
} else if (path.isEqualTo("clues", "clue")) {
// ?/rectangular-puzzle/crossword/clues/clue
val wordId = parser.intValue("word", -1)
val number = parser.intValue("number", -1)
currentWordBuilder = wordBuilders[wordId]
currentWordBuilder!!.number = number
currentWordBuilder!!.hintUrl = parser.stringValue("hint-url")
currentWordBuilder!!.citation = parser.stringValue("citation")
}
} else if (path.isDeadEnd) {
// ?/rectangular-puzzle
parser.stringValue("alphabet")?.let {
builder!!.setAlphabet(it.toCharArray().toSet())
}
}
}
override fun onTextContent(path: SimpleXmlParser.SimpleXmlPath, text: String) {
super.onTextContent(path, text)
if (!path.startsWith("?", "rectangular-puzzle")) return
if (path.startsWith("metadata")) {
when {
path.isEqualTo("title") -> // ?/rectangular-puzzle/metadata/title
builder!!.title = text
path.isEqualTo("creator") -> // ?/rectangular-puzzle/metadata/creator
builder!!.author = text
path.isEqualTo("copyright") -> // ?/rectangular-puzzle/metadata/copyright
builder!!.copyright = text
path.isEqualTo("description") -> // ?/rectangular-puzzle/metadata/description
builder!!.description = text
}
} else if (path.isEqualTo("crossword", "clues", "clue")) {
// ?/rectangular-puzzle/crossword/clues/clue
currentWordBuilder!!.hint = text
}
}
private class CCCell(val chars: String,
val number: Int,
var attr: Int = 0)
}
| library/src/main/java/org/akop/ararat/io/CrosswordCompilerFormatter.kt | 3311566680 |
/*******************************************************************************
* Copyright (c) 2013, 2015 Ericsson
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* Contributors:
* Alexandre Montplaisir - Initial API and implementation
*/
package com.efficios.jabberwocky.ctf.trace.event
import com.efficios.jabberwocky.ctf.trace.CtfTrace
import com.efficios.jabberwocky.ctf.trace.ExtractedCtfTestTrace
import com.efficios.jabberwocky.trace.event.TraceLostEvent
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.lttng.scope.ttt.ctf.CtfTestTrace
/**
* Tests to verify that lost events are handled correctly.
* Be wary if you are using Babeltrace to cross-check those values. There could
* be a bug in Babeltrace with regards to lost events. See
* http://bugs.lttng.org/issues/589
* It's not 100% sure at this point which implementation is correct, so for now
* these tests assume the Java implementation is the right one.
* @author Alexandre Montplaisir
*/
class CtfTmfLostEventsTest {
companion object {
private lateinit var HELLO_LOST_TT: ExtractedCtfTestTrace
private lateinit var DYNSCOPE_TT: ExtractedCtfTestTrace
@BeforeAll
@JvmStatic
fun setupClass() {
HELLO_LOST_TT = ExtractedCtfTestTrace(CtfTestTrace.HELLO_LOST)
DYNSCOPE_TT = ExtractedCtfTestTrace(CtfTestTrace.DYNSCOPE)
}
@AfterAll
@JvmStatic
fun teardownClass() {
HELLO_LOST_TT.close()
DYNSCOPE_TT.close()
}
}
/**
* Test that the number of events is reported correctly (a range of lost
* events is counted as one event).
*/
@Test
fun testNbEvents() {
val expectedReal = 32300L
val expectedLost = 562L
val req = EventCountRequest(HELLO_LOST_TT.trace)
assertEquals(expectedReal, req.real)
assertEquals(expectedLost, req.lost)
}
/**
* Test that the number of events is reported correctly (a range of lost
* events is counted as one event). Events could be wrongly counted as lost
* events in certain situations.
*/
@Test
fun testNbEventsBug475007() {
val expectedReal = 100003L
val expectedLost = 1L
val req = EventCountRequest(DYNSCOPE_TT.trace)
assertEquals(expectedReal, req.real)
assertEquals(expectedLost, req.lost)
}
/**
* Test getting the first lost event from the trace.
*/
@Test
fun testFirstLostEvent() {
val trace = HELLO_LOST_TT.trace
val rank = 190L
val start = 1376592664828900165L
val end = start + 502911L
val nbLost = 859L
validateLostEvent(trace, rank, start, end, nbLost)
}
/**
* Test getting the second lost event from the trace.
*/
@Test
fun testSecondLostEvent() {
val trace = HELLO_LOST_TT.trace
val rank = 229L
val start = 1376592664829477058L
val end = start + 347456L
val nbLost = 488L
validateLostEvent(trace, rank, start, end, nbLost)
}
/**
* Test getting one normal event from the trace (lost events should not
* interfere).
*/
@Test
fun testNormalEvent() {
val trace = HELLO_LOST_TT.trace
val rank = 200L
val ts = 1376592664829425780L
val event = getEventAtTimestamp(trace, ts)
/* Make sure seeking by rank yields the same event */
val event2 = getEventAtRank(trace, rank)
assertEquals(event, event2)
assertFalse(event is TraceLostEvent)
assertEquals(ts, event.timestamp)
}
// ------------------------------------------------------------------------
// Event requests
// ------------------------------------------------------------------------
private class EventCountRequest(trace: CtfTrace) {
var real: Long = 0
private set
var lost: Long = 0
private set
init {
trace.iterator().use { iter ->
while (iter.hasNext()) {
val event = iter.next()
if (event is TraceLostEvent) {
lost++
} else {
real++
}
}
}
}
}
private fun validateLostEvent(trace: CtfTrace, rank: Long, start: Long, end: Long, nbLost: Long) {
val ev = getLostEventAtTimestamp(trace, start)
/* Make sure seeking by rank yields the same event */
val ev2 = getEventAtRank(trace, rank)
assertEquals(ev, ev2)
assertTrue(ev is TraceLostEvent)
val event = ev as TraceLostEvent
assertEquals(start, event.timestamp)
assertEquals(start, event.timeRange.startTime)
assertEquals(end, event.timeRange.endTime)
assertEquals(nbLost, event.nbLostEvents)
}
private fun getEventAtTimestamp(trace: CtfTrace, timestamp: Long): CtfTraceEvent {
trace.iterator().use({ iter ->
while (iter.hasNext()) {
val event = iter.next()
if (event.timestamp >= timestamp) {
return event
}
}
})
throw IllegalArgumentException("No event with timestamp $timestamp found.")
}
private fun getLostEventAtTimestamp(trace: CtfTrace, timestamp: Long): CtfTraceEvent {
trace.iterator().use({ iter ->
while (iter.hasNext()) {
val event = iter.next()
if (event.timestamp >= timestamp && event is TraceLostEvent) {
return event
}
}
})
throw IllegalArgumentException("No event with timestamp $timestamp found.")
}
private fun getEventAtRank(trace: CtfTrace, rank: Long): CtfTraceEvent {
trace.iterator().use({ iter ->
for (remaining in rank downTo 1) {
iter.next()
}
return iter.next()
})
}
}
| jabberwocky-ctf/src/test/kotlin/com/efficios/jabberwocky/ctf/trace/event/CtfTmfLostEventsTest.kt | 2040628031 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho
import com.facebook.litho.annotations.Hook
/**
* Declares a state variable within a Component. The initializer will provide the initial value if
* it hasn't already been initialized in a previous render of the Component.
*
* Assignments to the state variables are allowed only in [updateState] block to batch updates and
* trigger a UI layout only once per batch.
*/
@Hook
fun <T> ComponentScope.useState(initializer: () -> T): State<T> {
val globalKey = context.globalKey
val hookIndex = useStateIndex++
val treeState: TreeState =
renderStateContext?.treeState
?: throw IllegalStateException("Cannot create state outside of layout calculation")
val isNestedTreeContext = context.isNestedTreeContext
val kState = treeState.getStateContainer(globalKey, isNestedTreeContext) as KStateContainer?
if (kState == null || kState.mStates.size <= hookIndex) {
// The initial state was not computed yet. let's create it and put it in the state
val state =
treeState.createOrGetInitialHookState(
globalKey, hookIndex, initializer, isNestedTreeContext)
treeState.addStateContainer(globalKey, state, isNestedTreeContext)
context.scopedComponentInfo.stateContainer = state
return State(context, hookIndex, state.mStates[hookIndex] as T)
} else {
context.scopedComponentInfo.stateContainer = kState
}
// Only need to mark this global key as seen once
if (hookIndex == 0) {
treeState.keepStateContainerForGlobalKey(globalKey, isNestedTreeContext)
}
return State(context, hookIndex, kState.mStates[hookIndex] as T)
}
/** Interface with which a component gets the value from a state or updates it. */
class State<T>
internal constructor(
private val context: ComponentContext,
private val hookStateIndex: Int,
val value: T
) {
/**
* Updates this state value and enqueues a new layout calculation reflecting it to execute in the
* background.
*/
fun update(newValue: T) {
if (canSkip(newValue)) {
return
}
context.updateHookStateAsync(context.globalKey, HookUpdaterValue(newValue))
}
/**
* Uses [newValueFunction] to update this state value using the previous state value, and enqueues
* a new layout calculation reflecting it to execute in the background.
*
* [newValueFunction] receives the current state value and can use it to compute the update: this
* is useful when there could be other enqueued updates that may not have been applied yet.
*
* For example, if your state update should increment a counter, using the function version of
* [update] with `count -> count + 1` will allow you to account for updates that are in flight but
* not yet applied (e.g. if the user has tapped a button triggering the update multiple times in
* succession).
*/
fun update(newValueFunction: (T) -> T) {
if (canSkip(newValueFunction)) {
return
}
context.updateHookStateAsync(context.globalKey, HookUpdaterLambda(newValueFunction))
}
/**
* Updates this state value and enqueues a new layout calculation reflecting it to execute on the
* current thread. If called on the main thread, this means that the UI will be updated for the
* current frame.
*
* Note: If [updateSync] is used on the main thread, it can easily cause dropped frames and
* degrade user experience. Therefore it should only be used in exceptional circumstances or when
* it's known to be executed off the main thread.
*/
fun updateSync(newValue: T) {
if (canSkip(newValue)) {
return
}
context.updateHookStateSync(context.globalKey, HookUpdaterValue(newValue))
}
/**
* Uses [newValueFunction] to update this state value using the previous state value, and enqueues
* a new layout calculation reflecting it to execute on the current thread.
*
* [newValueFunction] receives the current state value and can use it to compute the update: this
* is useful when there could be other enqueued updates that may not have been applied yet.
*
* For example, if your state update should increment a counter, using the function version of
* [update] with `count -> count + 1` will allow you to account for updates that are in flight but
* not yet applied (e.g. if the user has tapped a button triggering the update multiple times in
* succession).
*
* Note: If [updateSync] is used on the main thread, it can easily cause dropped frames and
* degrade user experience. Therefore it should only be used in exceptional circumstances or when
* it's known to be executed off the main thread.
*/
fun updateSync(newValueFunction: (T) -> T) {
if (canSkip(newValueFunction)) {
return
}
context.updateHookStateSync(context.globalKey, HookUpdaterLambda(newValueFunction))
}
inner class HookUpdaterValue(val newValue: T) : HookUpdater {
override fun getUpdatedStateContainer(currentState: KStateContainer?): KStateContainer? {
return currentState?.copyAndMutate(hookStateIndex, newValue)
}
}
inner class HookUpdaterLambda(val newValueFunction: (T) -> T) : HookUpdater {
override fun getUpdatedStateContainer(currentState: KStateContainer?): KStateContainer? {
return currentState?.copyAndMutate(
hookStateIndex, newValueFunction(currentState.mStates[hookStateIndex] as T))
}
}
private fun canSkip(newValue: T): Boolean {
return context.componentTree.treeState?.canSkipStateUpdate(
context.globalKey, hookStateIndex, newValue, context.isNestedTreeContext())
?: false
}
private fun canSkip(newValueFunction: (T) -> T): Boolean {
val treeState = context.componentTree.treeState
return treeState?.canSkipStateUpdate(
newValueFunction, context.globalKey, hookStateIndex, context.isNestedTreeContext())
?: false
}
/**
* We consider two state objects equal if they 1) belong to the same ComponentTree, 2) have the
* same global key and hook index, and 3) have the same value (according to its own .equals check)
*/
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is State<*>) {
return false
}
return context.componentTree === other.context.componentTree &&
context.globalKey == other.context.globalKey &&
hookStateIndex == other.hookStateIndex &&
value == other.value
}
override fun hashCode(): Int {
return context.globalKey.hashCode() * 17 + (value?.hashCode() ?: 0) * 11 + hookStateIndex
}
}
| litho-core-kotlin/src/main/kotlin/com/facebook/litho/KState.kt | 3796362136 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.samples.litho.kotlin.documentation
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Style
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.useCached
import com.facebook.litho.useState
import com.facebook.litho.view.onClick
// start_example
class UseCachedWithDependencyComponent : KComponent() {
override fun ComponentScope.render(): Component? {
val number = useState { 1 }
val expensiveValue = useCached(number) { expensiveRepeatFunc("hello", number.value) }
return Column(style = Style.onClick { number.update { n -> n + 1 } }) {
child(Text(text = expensiveValue))
}
}
companion object {
private fun expensiveRepeatFunc(prefix: String, num: Int = 20): String {
return StringBuilder().apply { repeat(num) { append(prefix) } }.toString()
}
}
}
// end_example
| sample/src/main/java/com/facebook/samples/litho/kotlin/documentation/UseCachedWithDependencyComponent.kt | 1753746401 |
// (c) Facebook, Inc. and its affiliates. Confidential and proprietary.
package com.facebook.samples.litho.kotlin.collection
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Style
import com.facebook.litho.flexbox.flex
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.widget.collection.LazyList
class CollectionKComponent : KComponent() {
private val friends = listOf("Ross", "Rachel", "Joey", "Phoebe", "Monica", "Chandler")
override fun ComponentScope.render(): Component =
LazyList(style = Style.flex(grow = 1f)) {
child(Text(text = "Header"))
children(items = friends, id = { it }) { Text(it) }
child(Text(text = "Footer"))
}
}
| sample/src/main/java/com/facebook/samples/litho/kotlin/collection/CollectionKComponent.kt | 349616308 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.sample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.google.android.horologist.sample.di.SampleAppDI
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
SampleAppDI.inject(this)
setContent {
SampleWearApp()
}
}
}
| sample/src/main/java/com/google/android/horologist/sample/MainActivity.kt | 4162638701 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.audio
@RequiresOptIn(
message = "Horologist Audio is experimental. The API may be changed in the future."
)
@Retention(AnnotationRetention.BINARY)
public annotation class ExperimentalHorologistAudioApi
| audio/src/main/java/com/google/android/horologist/audio/ExperimentalHorologistAudioApi.kt | 1115587195 |
package net.xpece.android.json
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
import java.math.BigDecimal
/**
* @author Eugen on 17.10.2016.
*/
object BigDecimalAdapter {
@ToJson
fun toJson(number: BigDecimal): String {
return number.toString()
}
@FromJson
fun fromJson(number: String): BigDecimal {
return BigDecimal(number)
}
}
| commons/src/main/java/net/xpece/android/json/BigDecimalAdapter.kt | 2187224574 |
package todo
import util.PlatformProvider
import util.ProviderDate
import util.ID
import util.Entity
import util.Revision
/**
* The core model classes.
* @author Eric Pabst ([email protected])
* Date: 6/9/16
* Time: 6:27 AM
*/
data class ToDo(
val name: String,
val dueDateString: String? = null,
val notes: String? = null,
val createDateString: String,
val _id: String? = null,
val _rev: String? = null
) : Entity<ToDo> {
constructor(name: String, dueDate: ProviderDate? = null, notes: String? = null, createDate: ProviderDate = PlatformProvider.now(), id: ID<ToDo>? = null, rev: Revision<ToDo>? = null) :
this(name, dueDate?.toIsoTimestampString(), notes, createDate.toIsoTimestampString(), id?._id, rev?._rev)
val dueDate: ProviderDate? get() = dueDateString?.let { PlatformProvider.toDate(it) }
val createDate: ProviderDate? get() = PlatformProvider.toDate(createDateString)
override val id: ID<ToDo>? get() = _id?.let { ID(it) }
override fun withID(id: ID<ToDo>): ToDo = copy(_id = id._id)
override val rev: Revision<ToDo>? get() = _rev?.let { Revision(it) }
override fun withRevision(revision: Revision<ToDo>): ToDo = copy(_rev = revision._rev)
}
| src/commonMain/kotlin/todo/ToDo.kt | 4173226825 |
package com.zhuinden.simplestackbottomnavfragmentexample.features.root.first
import androidx.fragment.app.Fragment
import com.zhuinden.simplestackextensions.fragments.DefaultFragmentKey
import kotlinx.parcelize.Parcelize
@Parcelize
class First2Screen : DefaultFragmentKey() {
override fun instantiateFragment(): Fragment = First2Fragment()
} | samples/multistack-samples/simple-stack-example-multistack-nested-fragment/src/main/java/com/zhuinden/simplestackbottomnavfragmentexample/features/root/first/First2Screen.kt | 1605549907 |
package com.github.kory33.signvote.constants
/**
* Keys in json file which stores information about vote session
* @author Kory
*/
object VoteSessionDataFileKeys {
val NAME = "name"
val IS_OPEN = "isopen"
val VOTE_SCORE_LIMITS = "votelimits"
}
| src/main/kotlin/com/github/kory33/signvote/constants/VoteSessionDataFileKeys.kt | 969535210 |
package test
import org.assertj.core.api.Assertions.assertThat
import org.testng.*
import org.testng.annotations.ITestAnnotation
import org.testng.internal.annotations.AnnotationHelper
import org.testng.internal.annotations.DefaultAnnotationTransformer
import org.testng.internal.annotations.IAnnotationFinder
import org.testng.internal.annotations.JDK15AnnotationFinder
import org.testng.xml.*
import org.testng.xml.internal.Parser
import java.io.*
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import java.util.regex.Pattern
import java.util.stream.Collectors
open class SimpleBaseTest {
companion object {
private const val TEST_RESOURCES_DIR = "test.resources.dir"
@JvmStatic
fun run(vararg testClasses: Class<*>) = run(false, *testClasses)
@JvmStatic
private fun run(skipConfiguration: Boolean, tng: TestNG) =
InvokedMethodNameListener(skipConfiguration).apply {
tng.addListener(this)
tng.run()
}
@JvmStatic
fun run(skipConfiguration: Boolean, vararg testClasses: Class<*>) =
run(skipConfiguration, create(*testClasses))
@JvmStatic
fun create(vararg testClasses: Class<*>) = create().apply {
setTestClasses(testClasses)
}
@JvmStatic
fun create() = TestNG().apply {
setUseDefaultListeners(false)
}
@JvmStatic
fun create(xmlSuite: XmlSuite) = create().apply {
setXmlSuites(listOf(xmlSuite))
}
@JvmStatic
fun run(vararg suites: XmlSuite): InvokedMethodNameListener = run(false, *suites)
@JvmStatic
fun run(skipConfiguration: Boolean, vararg suites: XmlSuite) =
run(skipConfiguration, create(*suites))
@JvmStatic
protected fun create(outputDir: Path, vararg testClasses: Class<*>) =
create(*testClasses).apply {
outputDirectory = outputDir.toAbsolutePath().toString()
}
@JvmStatic
protected fun create(vararg suites: XmlSuite) = create(listOf(*suites))
@JvmStatic
protected fun create(suites: List<XmlSuite>) = create().apply {
setXmlSuites(suites)
}
@JvmStatic
protected fun create(outputDir: Path, vararg suites: XmlSuite) =
create(outputDir, listOf(*suites))
@JvmStatic
protected fun create(outputDir: Path, suites: List<XmlSuite>) = create(suites).apply {
outputDirectory = outputDir.toAbsolutePath().toString()
}
@JvmStatic
protected fun createTests(suiteName: String, vararg testClasses: Class<*>) =
createTests(null, suiteName, *testClasses)
@JvmStatic
protected fun createTests(
outDir: Path?,
suiteName: String,
vararg testClasses: Class<*>
) = createXmlSuite(suiteName).let { suite ->
for ((i, testClass) in testClasses.withIndex()) {
createXmlTest(suite, testClass.name + i, testClass)
}
//if outDir is not null then create suite with outDir, else create suite without it.
outDir?.let { create(it, suite) } ?: create(suite)
}
@JvmStatic
protected fun createDummySuiteWithTestNamesAs(vararg tests: String) =
XmlSuite().apply {
name = "random_suite"
tests.forEach {
XmlTest(this).apply {
name = it
}
}
}
@JvmStatic
protected fun createXmlSuite(name: String) = XmlSuite().apply {
this.name = name
}
@JvmStatic
protected fun createXmlSuite(params: Map<String, String>) =
createXmlSuite(UUID.randomUUID().toString()).apply {
parameters = params
}
@JvmStatic
protected fun createXmlSuite(
suiteName: String,
testName: String,
vararg classes: Class<*>
) = createXmlSuite(suiteName).apply {
createXmlTest(this, testName, *classes)
}
@JvmStatic
protected fun createXmlSuite(suiteName: String, params: Map<String, String>) =
createXmlSuite(suiteName).apply {
parameters = params
}
@JvmStatic
protected fun createXmlTestWithPackages(
suite: XmlSuite, name: String, vararg packageName: String
) = createXmlTest(suite, name).apply {
packages = packageName.map {
XmlPackage().apply {
this.name = it
}
}.toMutableList()
}
@JvmStatic
protected fun createXmlTestWithPackages(
suite: XmlSuite, name: String, vararg packageName: Class<*>
) = createXmlTest(suite, name).apply {
packages = packageName.map {
XmlPackage().apply {
this.name = it.`package`.name
}
}.toMutableList()
}
@JvmStatic
protected fun createXmlTest(suiteName: String, testName: String) =
createXmlTest(createXmlSuite(suiteName), testName)
@JvmStatic
protected fun createXmlTest(
suiteName: String,
testName: String,
vararg classes: Class<*>
) = createXmlTest(createXmlSuite(suiteName), testName).apply {
classes.forEach {
xmlClasses.add(XmlClass(it))
}
}
@JvmStatic
protected fun createXmlTest(suite: XmlSuite, name: String) = XmlTest(suite).apply {
this.name = name
}
@JvmStatic
protected fun createXmlTest(
suite: XmlSuite,
name: String,
params: Map<String, String>
) = XmlTest(suite).apply {
this.name = name
setParameters(params)
}
@JvmStatic
protected fun createXmlTest(
suite: XmlSuite,
name: String,
vararg classes: Class<*>
) = createXmlTest(suite, name).apply {
for ((index, c) in classes.withIndex()) {
val xc = XmlClass(c.name, index, true /* load classes */)
xmlClasses.add(xc)
}
}
@JvmStatic
protected fun createXmlClass(test: XmlTest, testClass: Class<*>) =
XmlClass(testClass).apply {
test.xmlClasses.add(this)
}
@JvmStatic
protected fun createXmlClass(
test: XmlTest, testClass: Class<*>, params: Map<String, String>
) = createXmlClass(test, testClass).apply {
setParameters(params)
}
@JvmStatic
protected fun createXmlInclude(clazz: XmlClass, method: String) = XmlInclude(method).apply {
setXmlClass(clazz)
clazz.includedMethods.add(this)
}
@JvmStatic
protected fun createXmlInclude(
clazz: XmlClass, method: String, params: Map<String, String>
) = createXmlInclude(clazz, method).apply {
setParameters(params)
}
@JvmStatic
protected fun createXmlInclude(
clazz: XmlClass,
method: String,
index: Int, vararg list: Int
) = XmlInclude(method, list.asList(), index).apply {
setXmlClass(clazz)
clazz.includedMethods.add(this)
}
@JvmStatic
protected fun createXmlGroups(
suite: XmlSuite,
vararg includedGroupNames: String
) = createGroupIncluding(*includedGroupNames).apply {
suite.groups = this
}
@JvmStatic
protected fun createXmlGroups(
test: XmlTest,
vararg includedGroupNames: String
) = createGroupIncluding(*includedGroupNames).apply {
test.setGroups(this)
}
@JvmStatic
private fun createGroupIncluding(vararg groupNames: String) = XmlGroups().apply {
run = XmlRun().apply {
groupNames.forEach { onInclude(it) }
}
}
@JvmStatic
protected fun createXmlTest(
suite: XmlSuite,
name: String,
vararg classes: String
) = createXmlTest(suite, name).apply {
for ((index, c) in classes.withIndex()) {
val xc = XmlClass(c, index, true /* load classes */)
xmlClasses.add(xc)
}
}
@JvmStatic
protected fun addMethods(cls: XmlClass, vararg methods: String) {
for ((index, method) in methods.withIndex()) {
cls.includedMethods.add(XmlInclude(method, index))
}
}
@JvmStatic
fun getPathToResource(fileName: String): String {
val result = System.getProperty(TEST_RESOURCES_DIR, "src/test/resources")
?: throw IllegalArgumentException(
"System property $TEST_RESOURCES_DIR was not defined."
)
return result + File.separatorChar + fileName
}
@JvmStatic
fun extractTestNGMethods(vararg classes: Class<*>): List<ITestNGMethod> =
XmlSuite().let { xmlSuite ->
xmlSuite.name = "suite"
val xmlTest = createXmlTest(xmlSuite, "tests", *classes)
val annotationFinder: IAnnotationFinder =
JDK15AnnotationFinder(DefaultAnnotationTransformer())
classes.flatMap { clazz ->
AnnotationHelper.findMethodsWithAnnotation(
object : ITestObjectFactory {},
clazz,
ITestAnnotation::class.java,
annotationFinder,
xmlTest
).toMutableList()
}
}
/** Compare a list of ITestResult with a list of String method names, */
@JvmStatic
protected fun assertTestResultsEqual(results: List<ITestResult>, methods: List<String>) {
results.map { it.method.methodName }
.toList()
.run {
assertThat(this).containsAll(methods)
}
}
/** Deletes all files and subdirectories under dir. */
@JvmStatic
protected fun deleteDir(dir: File): Path =
Files.walkFileTree(dir.toPath(), TestNGFileVisitor())
@JvmStatic
protected fun createDirInTempDir(dir: String): File =
Files.createTempDirectory(dir)
.toFile().apply {
deleteOnExit()
}
/**
* @param fileName The filename to parse
* @param regexp The regular expression
* @param resultLines An out parameter that will contain all the lines that matched the regexp
* @return A List<Integer> containing the lines of all the matches
*
* Note that the size() of the returned valuewill always be equal to result.size() at the
* end of this function.
</Integer> */
@JvmStatic
protected fun grep(
fileName: File,
regexp: String,
resultLines: MutableList<String>
) = grep(FileReader(fileName), regexp, resultLines)
@JvmStatic
protected fun grep(
reader: Reader,
regexp: String,
resultLines: MutableList<String>
): List<Int> {
val resultLineNumbers = mutableListOf<Int>()
val p = Pattern.compile(".*$regexp.*")
val counter = AtomicInteger(-1)
BufferedReader(reader).lines()
.peek { counter.getAndIncrement() }
.filter { line -> p.matcher(line).matches() }
.forEach {
resultLines.add(it)
resultLineNumbers.add(counter.get())
}
return resultLineNumbers
}
@JvmStatic
protected fun getSuites(vararg suiteFiles: String) = suiteFiles.map { Parser(it) }
.flatMap { it.parseToList() }
.toList()
@JvmStatic
protected fun getFailedResultMessage(testResultList: List<ITestResult>): String {
val methods = testResultList.stream()
.map { r: ITestResult ->
AbstractMap.SimpleEntry(
r.method.qualifiedName, r.throwable
)
}
.map { (key, value): AbstractMap.SimpleEntry<String?, Throwable?> ->
"$key: $value"
}
.collect(Collectors.joining("\n"))
return "Failed methods should pass: \n $methods"
}
}
class TestNGFileVisitor : SimpleFileVisitor<Path>() {
@Throws(IOException::class)
override fun visitFile(
file: Path,
attrs: BasicFileAttributes
): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}
@Throws(IOException::class)
override fun postVisitDirectory(
dir: Path,
exc: IOException?
): FileVisitResult {
Files.delete(dir)
return FileVisitResult.CONTINUE
}
}
}
| testng-core/src/test/kotlin/test/SimpleBaseTest.kt | 1363938545 |
package com.lucciola.unitcalculator.calculator
import com.lucciola.unitcalculator.BasePresenter
import com.lucciola.unitcalculator.BaseView
interface CalculatorContract {
interface View : BaseView<Presenter> {
fun showResult(result: String)
fun showFormula(formula: String)
}
interface Presenter : BasePresenter {
fun onEvaluate()
fun onInputNumber(number: String)
fun onInputOperator(operator: String)
fun onInputBrace(brace: String)
fun onInputUnit(unit: String)
fun onInputPrefix(prefix: String)
}
}
| app/src/main/java/com/lucciola/unitcalculator/calculator/CalculatorContract.kt | 4161259782 |
package com.uncmorfi.reservations
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class AlarmReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
context?.let {
AlarmHelper.makeNotification(context)
val calendar = AlarmHelper.getNextAlarm(context)
calendar?.let {
AlarmHelper.scheduleAlarm(context, calendar)
}
}
}
} | app/src/main/java/com/uncmorfi/reservations/AlarmReceiver.kt | 2698932237 |
package com.commit451.gitlab.viewHolder
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.commit451.addendum.recyclerview.bindView
import com.commit451.gitlab.R
import com.commit451.gitlab.model.api.Snippet
/**
* Snippet
*/
class SnippetViewHolder(view: View) : RecyclerView.ViewHolder(view) {
companion object {
fun inflate(parent: ViewGroup): SnippetViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_snippet, parent, false)
return SnippetViewHolder(view)
}
}
private val textTitle: TextView by bindView(R.id.title)
private val textFileName: TextView by bindView(R.id.file_name)
fun bind(snippet: Snippet) {
textTitle.text = snippet.title
if (snippet.fileName != null) {
textFileName.visibility = View.VISIBLE
textFileName.text = snippet.fileName
} else {
textFileName.visibility = View.GONE
}
}
}
| app/src/main/java/com/commit451/gitlab/viewHolder/SnippetViewHolder.kt | 2753188325 |
package com.booboot.vndbandroid.dao
import com.booboot.vndbandroid.extensions.removeRelations
import com.booboot.vndbandroid.model.vndb.UserList
import io.objectbox.BoxStore
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.kotlin.boxFor
import io.objectbox.relation.ToMany
@Entity
class UserListDao() {
@Id(assignable = true) var vn: Long = 0
var added: Long = 0
var lastmod: Long = 0
var voted: Long? = null
var vote: Int? = null
var notes: String? = null
var started: String? = null
var finished: String? = null
lateinit var labels: ToMany<LabelDao>
constructor(userList: UserList, boxStore: BoxStore) : this() {
vn = userList.vn
added = userList.added
lastmod = userList.lastmod
voted = userList.voted
vote = userList.vote
notes = userList.notes
started = userList.started
finished = userList.finished
/**
* attach() is mandatory because of self-assigned IDs, but also retrieves the ToMany relations from the DB.
* If we simply add() new relations, they will be stacking up with the old ones; we don't want that, so we have to remove these relations.
* /!\ Don't call clear() because it removes the related entities! Call remove() to only remove relations.
* See https://docs.objectbox.io/relations#updating-tomany
*/
boxStore.boxFor<UserListDao>().attach(this)
labels.removeRelations()
userList.labels.forEach { labels.add(LabelDao(it)) }
boxStore.boxFor<LabelDao>().put(labels)
}
fun toBo() = UserList(
vn,
added,
lastmod,
voted,
vote,
notes,
started,
finished,
labels.map { it.toBo() }.toSet()
)
} | app/src/main/java/com/booboot/vndbandroid/dao/UserListDao.kt | 4111801453 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.