content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package ca.josephroque.bowlingcompanion.games.lane
/**
* Copyright (C) 2018 Joseph Roque
*
* Alias for an array of pins.
*/
typealias Deck = Array<Pin>
// MARK: Pins
val Deck.left2Pin: Pin
get() = this[0]
val Deck.left3Pin: Pin
get() = this[1]
val Deck.headPin: Pin
get() = this[2]
val Deck.right3Pin: Pin
get() = this[3]
val Deck.right2Pin: Pin
get() = this[4]
// MARK: First Ball
fun Deck.isHeadPin(countH2asH: Boolean): Boolean {
return this.isHeadPin || (countH2asH && this.value(false) == 7 && this.headPin.isDown)
}
val Deck.isHeadPin: Boolean
get() = this.value(false) == 5 && this.headPin.isDown
val Deck.isLeft: Boolean
get() = this.value(false) == 13 && this.left2Pin.onDeck
val Deck.isRight: Boolean
get() = this.value(false) == 13 && this.right2Pin.onDeck
val Deck.isAce: Boolean
get() = this.value(false) == 11
val Deck.isLeftChopOff: Boolean
get() = this.value(false) == 10 && this.left2Pin.isDown && this.left3Pin.isDown && this.headPin.isDown
val Deck.isRightChopOff: Boolean
get() = this.value(false) == 10 && this.right2Pin.isDown && this.right3Pin.isDown && this.headPin.isDown
val Deck.isChopOff: Boolean
get() = this.isLeftChopOff || this.isRightChopOff
fun Deck.isLeftSplit(countS2asS: Boolean): Boolean {
return this.isLeftSplit || (countS2asS && this.value(false) == 10 && this.headPin.isDown && this.left3Pin.isDown && this.right2Pin.isDown)
}
private val Deck.isLeftSplit: Boolean
get() = this.value(false) == 8 && this.headPin.isDown && this.left3Pin.isDown
fun Deck.isRightSplit(countS2asS: Boolean): Boolean {
return this.isRightSplit || (countS2asS && this.value(false) == 10 && this.headPin.isDown && this.left2Pin.isDown && this.right3Pin.isDown)
}
private val Deck.isRightSplit: Boolean
get() = this.value(false) == 8 && this.headPin.isDown && this.right3Pin.isDown
fun Deck.isSplit(countS2asS: Boolean): Boolean {
return isLeftSplit(countS2asS) || isRightSplit(countS2asS)
}
val Deck.isHitLeftOfMiddle: Boolean
get() = this.headPin.onDeck && (this.left2Pin.isDown || this.left3Pin.isDown)
val Deck.isHitRightOfMiddle: Boolean
get() = this.headPin.onDeck && (this.right2Pin.isDown || this.right3Pin.isDown)
val Deck.isMiddleHit: Boolean
get() = this.headPin.isDown
val Deck.isLeftTwelve: Boolean
get() = this.value(false) == 12 && this.left3Pin.isDown
val Deck.isRightTwelve: Boolean
get() = this.value(false) == 12 && this.right3Pin.isDown
val Deck.isTwelve: Boolean
get() = this.isLeftTwelve || this.isRightTwelve
val Deck.arePinsCleared: Boolean
get() = this.all { it.isDown }
// Functions
fun Deck.toBooleanArray(): BooleanArray {
return this.map { it.isDown }.toBooleanArray()
}
fun Deck.deepCopy(): Deck {
return this.map { pin -> Pin(pin.type).apply { isDown = pin.isDown } }.toTypedArray()
}
fun Deck.toInt(): Int {
var ball = 0
for (i in this.indices) {
if (this[i].isDown) {
ball += Math.pow(2.0, (-i + 4).toDouble()).toInt()
}
}
return ball
}
fun Deck.reset() {
this.forEach { it.isDown = false }
}
fun Deck.value(onDeck: Boolean): Int {
return this.filter { it.onDeck == onDeck }.sumBy { it.value }
}
fun Deck.ballValue(ballIdx: Int, returnSymbol: Boolean, afterStrike: Boolean): String {
val ball = when {
isHeadPin(false) -> Ball.HeadPin
isHeadPin(true) -> Ball.HeadPin2
isSplit(false) -> Ball.Split
isSplit(true) -> Ball.Split2
isChopOff -> Ball.ChopOff
isAce -> Ball.Ace
isLeft -> Ball.Left
isRight -> Ball.Right
arePinsCleared -> {
when {
ballIdx == 0 -> Ball.Strike
ballIdx == 1 && !afterStrike -> Ball.Spare
else -> Ball.Cleared
}
}
else -> Ball.None
}
return if (ball == Ball.None) {
val value = this.value(false)
return if (value == 0) {
ball.toString()
} else {
value.toString()
}
} else {
if (ballIdx == 0 || returnSymbol) ball.toString() else ball.numeral
}
}
fun Deck.ballValueDifference(other: Deck, ballIdx: Int, returnSymbol: Boolean, afterStrike: Boolean): String {
val deck = this.deepCopy()
for (i in 0 until other.size) {
if (other[i].isDown) { deck[i].isDown = false }
}
return deck.ballValue(ballIdx, returnSymbol, afterStrike)
}
fun Deck.valueDifference(other: Deck): Int {
return this.filterIndexed { index, pin -> pin.isDown && !other[index].isDown }.sumBy { it.value }
}
| app/src/main/java/ca/josephroque/bowlingcompanion/games/lane/Deck.kt | 3011687515 |
package com.alekseyzhelo.lbm.gui.simple.algs4
import com.alekseyzhelo.lbm.core.lattice.LatticeD2
import com.alekseyzhelo.lbm.util.norm
import com.alekseyzhelo.lbm.util.normalize
import java.awt.Color
import java.util.*
/**
* @author Aleks on 29-05-2016.
*/
internal val colorMemo = HashMap<Int, Color>()
internal fun blueRedGradient(n: Int): Color {
val corrected = when {
n > 255 -> 255
n < 0 -> 0
else -> n
}
var color = colorMemo[corrected]
if (color == null) {
val b = 255 - corrected
val r = 255 - b
val g = 0
// var rgb = r;
// rgb = (rgb shl 8) + g;
// rgb = (rgb shl 8) + b;
color = Color (r, g, b)
colorMemo.put(corrected, color)
}
return color
}
internal fun cellColor(normalized: Double): Color {
return blueRedGradient((normalized * 255).toInt())
}
internal fun drawScalarValue(value: Double, i: Int, j: Int,
minValue: Double, maxValue: Double): Unit {
val color = cellColor(normalize(value, minValue, maxValue))
FasterStdDraw.setPenColor(color)
// TODO: why is j + 1 necessary? j leaves an empty row at the top..
FasterStdDraw.deferredFilledSquareTest((i).toDouble(), (j + 1).toDouble(), 1.0) // double r
}
internal fun drawVectorValue(value: DoubleArray, i: Int, j: Int,
minValue: Double, maxValue: Double): Unit {
val color = cellColor(normalize(norm(value), minValue, maxValue))
val ort = normalize(value)
FasterStdDraw.setPenColor(color)
FasterStdDraw.drawArrowLineTest((i).toDouble(), (j).toDouble(), i + ort[0], j + ort[1], 0.3, 0.2)
}
fun LatticeD2<*>.drawDensityTable(minDensity: Double, maxDensity: Double): Unit {
for (i in cells.indices) {
for (j in cells[0].indices) {
drawScalarValue(cells[i][j].computeRho(), i, j, minDensity, maxDensity)
}
}
}
fun LatticeD2<*>.drawVelocityNormTable(minVelocityNorm: Double, maxVelocityNorm: Double): Unit {
for (i in cells.indices) {
for (j in cells[0].indices) {
drawScalarValue(
norm(cells[i][j].computeRhoU()),
i, j, minVelocityNorm, maxVelocityNorm
)
}
}
}
fun LatticeD2<*>.drawVelocityVectorTable(minVelocityNorm: Double, maxVelocityNorm: Double): Unit {
for (i in cells.indices) {
for (j in cells[0].indices) {
drawVectorValue(
cells[i][j].computeRhoU(),
i, j, minVelocityNorm, maxVelocityNorm
)
}
}
} | SimpleGUIApp/src/main/kotlin/com/alekseyzhelo/lbm/gui/simple/algs4/Algs4Util.kt | 2233013591 |
/*
* Copyright (C) 2019. Uber Technologies
*
* 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 autodispose2.sample
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider
import autodispose2.autoDispose
import autodispose2.recipes.subscribeBy
import io.reactivex.rxjava3.core.Observable
import java.util.concurrent.TimeUnit
/**
* Demo Fragment showing both conventional lifecycle management as well as the new
* [getViewLifecycleOwner] API.
*
* This leverages the Architecture Components support for the demo
*/
class KotlinFragment : Fragment() {
// Can be reused
private val scopeProvider by lazy { AndroidLifecycleScopeProvider.from(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate()")
// Using automatic disposal, this should determine that the correct time to
// dispose is onDestroy (the opposite of onCreate).
Observable.interval(1, TimeUnit.SECONDS)
.doOnDispose { Log.i(TAG, "Disposing subscription from onCreate()") }
.autoDispose(scopeProvider)
.subscribeBy { num -> Log.i(TAG, "Started in onCreate(), running until onDestroy(): $num") }
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Log.d(TAG, "onCreateView()")
return inflater.inflate(R.layout.content_main, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.d(TAG, "onViewCreated()")
// Using automatic disposal, this should determine that the correct time to
// dispose is onDestroyView (the opposite of onCreateView).
// Note we do this in onViewCreated to defer until after the view is created
Observable.interval(1, TimeUnit.SECONDS)
.doOnDispose { Log.i(TAG, "Disposing subscription from onViewCreated()") }
.autoDispose(AndroidLifecycleScopeProvider.from(viewLifecycleOwner))
.subscribeBy { num ->
Log.i(TAG, "Started in onViewCreated(), running until onDestroyView(): $num")
}
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart()")
// Using automatic disposal, this should determine that the correct time to
// dispose is onStop (the opposite of onStart).
Observable.interval(1, TimeUnit.SECONDS)
.doOnDispose { Log.i(TAG, "Disposing subscription from onStart()") }
.autoDispose(scopeProvider)
.subscribeBy { num -> Log.i(TAG, "Started in onStart(), running until in onStop(): $num") }
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume()")
// Using automatic disposal, this should determine that the correct time to
// dispose is onPause (the opposite of onResume).
Observable.interval(1, TimeUnit.SECONDS)
.doOnDispose { Log.i(TAG, "Disposing subscription from onResume()") }
.autoDispose(scopeProvider)
.subscribeBy { num ->
Log.i(TAG, "Started in onResume(), running until in onPause(): $num")
}
// Setting a specific untilEvent, this should dispose in onDestroy.
Observable.interval(1, TimeUnit.SECONDS)
.doOnDispose {
Log.i(TAG, "Disposing subscription from onResume() with untilEvent ON_DESTROY")
}
.autoDispose(
AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)
)
.subscribeBy { num ->
Log.i(TAG, "Started in onResume(), running until in onDestroy(): $num")
}
}
override fun onPause() {
Log.d(TAG, "onPause()")
super.onPause()
}
override fun onStop() {
Log.d(TAG, "onStop()")
super.onStop()
}
override fun onDestroyView() {
Log.d(TAG, "onDestroyView()")
super.onDestroyView()
}
override fun onDestroy() {
Log.d(TAG, "onDestroy()")
super.onDestroy()
}
companion object {
private const val TAG = "KotlinFragment"
}
}
| sample/src/main/kotlin/autodispose2/sample/KotlinFragment.kt | 877443119 |
package fr.free.nrw.commons.profile.achievements
import fr.free.nrw.commons.R
/**
* calculates the level of the user
*/
class LevelController {
var level: LevelInfo? = null
enum class LevelInfo(val levelNumber: Int,
val levelStyle: Int,
val maxUniqueImages: Int,
val maxUploadCount: Int,
val minNonRevertPercentage: Int) {
LEVEL_1(1, R.style.LevelOne, 5, 20, 85), LEVEL_2(2, R.style.LevelTwo, 10, 30, 86), LEVEL_3(3, R.style.LevelThree, 15, 40, 87), LEVEL_4(4, R.style.LevelFour, 20, 50, 88), LEVEL_5(5, R.style.LevelFive, 25, 60, 89), LEVEL_6(6, R.style.LevelOne, 30, 70, 90), LEVEL_7(7, R.style.LevelTwo, 40, 80, 90), LEVEL_8(8, R.style.LevelThree, 45, 90, 90), LEVEL_9(9, R.style.LevelFour, 50, 100, 90), LEVEL_10(10, R.style.LevelFive, 55, 110, 90), LEVEL_11(11, R.style.LevelOne, 60, 120, 90), LEVEL_12(12, R.style.LevelTwo, 65, 130, 90), LEVEL_13(13, R.style.LevelThree, 70, 140, 90), LEVEL_14(14, R.style.LevelFour, 75, 150, 90), LEVEL_15(15, R.style.LevelFive, 80, 160, 90), LEVEL_16(16, R.style.LevelOne, 160, 320, 91), LEVEL_17(17, R.style.LevelTwo, 320, 640, 92), LEVEL_18(18, R.style.LevelThree, 640, 1280, 93), LEVEL_19(19, R.style.LevelFour, 1280, 2560, 94), LEVEL_20(20, R.style.LevelFive, 2560, 5120, 95), LEVEL_21(21, R.style.LevelOne, 5120, 10240, 96), LEVEL_22(22, R.style.LevelTwo, 10240, 20480, 97), LEVEL_23(23, R.style.LevelThree, 20480, 40960, 98), LEVEL_24(24, R.style.LevelFour, 40960, 81920, 98), LEVEL_25(25, R.style.LevelFive, 81920, 163840, 98), LEVEL_26(26, R.style.LevelOne, 163840, 327680, 98), LEVEL_27(27, R.style.LevelTwo, 327680, 655360, 98);
companion object {
@JvmStatic
fun from(imagesUploaded: Int,
uniqueImagesUsed: Int,
nonRevertRate: Int): LevelInfo {
var level = LEVEL_15
for (levelInfo in values()) {
if (imagesUploaded < levelInfo.maxUploadCount || uniqueImagesUsed < levelInfo.maxUniqueImages || nonRevertRate < levelInfo.minNonRevertPercentage) {
level = levelInfo
return level
}
}
return level
}
}
}
} | app/src/main/java/fr/free/nrw/commons/profile/achievements/LevelController.kt | 2376456530 |
@file:JvmName("-Utils")
@file:Suppress("NOTHING_TO_INLINE")
package coil.util
import android.app.ActivityManager
import android.content.ContentResolver.SCHEME_FILE
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.ColorSpace
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.VectorDrawable
import android.net.Uri
import android.os.Build.VERSION.SDK_INT
import android.os.Looper
import android.view.View
import android.webkit.MimeTypeMap
import android.widget.ImageView
import android.widget.ImageView.ScaleType.CENTER_INSIDE
import android.widget.ImageView.ScaleType.FIT_CENTER
import android.widget.ImageView.ScaleType.FIT_END
import android.widget.ImageView.ScaleType.FIT_START
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import coil.ComponentRegistry
import coil.EventListener
import coil.ImageLoader
import coil.base.R
import coil.decode.DataSource
import coil.decode.Decoder
import coil.disk.DiskCache
import coil.fetch.Fetcher
import coil.intercept.Interceptor
import coil.intercept.RealInterceptorChain
import coil.memory.MemoryCache
import coil.request.Parameters
import coil.request.Tags
import coil.request.ViewTargetRequestManager
import coil.size.Dimension
import coil.size.Scale
import coil.size.Size
import coil.size.isOriginal
import coil.size.pxOrElse
import coil.transform.Transformation
import java.io.Closeable
import java.io.File
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import okhttp3.Headers
internal val View.requestManager: ViewTargetRequestManager
get() {
var manager = getTag(R.id.coil_request_manager) as? ViewTargetRequestManager
if (manager == null) {
manager = synchronized(this) {
// Check again in case coil_request_manager was just set.
(getTag(R.id.coil_request_manager) as? ViewTargetRequestManager)
?.let { return@synchronized it }
ViewTargetRequestManager(this).apply {
addOnAttachStateChangeListener(this)
setTag(R.id.coil_request_manager, this)
}
}
}
return manager
}
internal val DataSource.emoji: String
get() = when (this) {
DataSource.MEMORY_CACHE,
DataSource.MEMORY -> Emoji.BRAIN
DataSource.DISK -> Emoji.FLOPPY
DataSource.NETWORK -> Emoji.CLOUD
}
internal val Drawable.width: Int
get() = (this as? BitmapDrawable)?.bitmap?.width ?: intrinsicWidth
internal val Drawable.height: Int
get() = (this as? BitmapDrawable)?.bitmap?.height ?: intrinsicHeight
internal val Drawable.isVector: Boolean
get() = this is VectorDrawable || this is VectorDrawableCompat
internal fun Closeable.closeQuietly() {
try {
close()
} catch (e: RuntimeException) {
throw e
} catch (_: Exception) {}
}
internal val ImageView.scale: Scale
get() = when (scaleType) {
FIT_START, FIT_CENTER, FIT_END, CENTER_INSIDE -> Scale.FIT
else -> Scale.FILL
}
/**
* Modified from [MimeTypeMap.getFileExtensionFromUrl] to be more permissive
* with special characters.
*/
internal fun MimeTypeMap.getMimeTypeFromUrl(url: String?): String? {
if (url.isNullOrBlank()) {
return null
}
val extension = url
.substringBeforeLast('#') // Strip the fragment.
.substringBeforeLast('?') // Strip the query.
.substringAfterLast('/') // Get the last path segment.
.substringAfterLast('.', missingDelimiterValue = "") // Get the file extension.
return getMimeTypeFromExtension(extension)
}
internal val Uri.firstPathSegment: String?
get() = pathSegments.firstOrNull()
internal val Configuration.nightMode: Int
get() = uiMode and Configuration.UI_MODE_NIGHT_MASK
/**
* An allowlist of valid bitmap configs for the input and output bitmaps of
* [Transformation.transform].
*/
internal val VALID_TRANSFORMATION_CONFIGS = if (SDK_INT >= 26) {
arrayOf(Bitmap.Config.ARGB_8888, Bitmap.Config.RGBA_F16)
} else {
arrayOf(Bitmap.Config.ARGB_8888)
}
/**
* Prefer hardware bitmaps on API 26 and above since they are optimized for drawing without
* transformations.
*/
internal val DEFAULT_BITMAP_CONFIG = if (SDK_INT >= 26) {
Bitmap.Config.HARDWARE
} else {
Bitmap.Config.ARGB_8888
}
/** Required for compatibility with API 25 and below. */
internal val NULL_COLOR_SPACE: ColorSpace? = null
internal val EMPTY_HEADERS = Headers.Builder().build()
internal fun Headers?.orEmpty() = this ?: EMPTY_HEADERS
internal fun Tags?.orEmpty() = this ?: Tags.EMPTY
internal fun Parameters?.orEmpty() = this ?: Parameters.EMPTY
internal fun isMainThread() = Looper.myLooper() == Looper.getMainLooper()
internal inline val Any.identityHashCode: Int
get() = System.identityHashCode(this)
@OptIn(ExperimentalCoroutinesApi::class)
internal fun <T> Deferred<T>.getCompletedOrNull(): T? {
return try {
getCompleted()
} catch (_: Throwable) {
null
}
}
internal inline operator fun MemoryCache.get(key: MemoryCache.Key?) = key?.let(::get)
/** https://github.com/coil-kt/coil/issues/675 */
internal val Context.safeCacheDir: File get() = cacheDir.apply { mkdirs() }
internal inline fun ComponentRegistry.Builder.addFirst(
pair: Pair<Fetcher.Factory<*>, Class<*>>?
) = apply { if (pair != null) fetcherFactories.add(0, pair) }
internal inline fun ComponentRegistry.Builder.addFirst(
factory: Decoder.Factory?
) = apply { if (factory != null) decoderFactories.add(0, factory) }
internal fun String.toNonNegativeInt(defaultValue: Int): Int {
val value = toLongOrNull() ?: return defaultValue
return when {
value > Int.MAX_VALUE -> Int.MAX_VALUE
value < 0 -> 0
else -> value.toInt()
}
}
internal fun DiskCache.Editor.abortQuietly() {
try {
abort()
} catch (_: Exception) {}
}
internal const val MIME_TYPE_JPEG = "image/jpeg"
internal const val MIME_TYPE_WEBP = "image/webp"
internal const val MIME_TYPE_HEIC = "image/heic"
internal const val MIME_TYPE_HEIF = "image/heif"
internal val Interceptor.Chain.isPlaceholderCached: Boolean
get() = this is RealInterceptorChain && isPlaceholderCached
internal val Interceptor.Chain.eventListener: EventListener
get() = if (this is RealInterceptorChain) eventListener else EventListener.NONE
internal fun Int.isMinOrMax() = this == Int.MIN_VALUE || this == Int.MAX_VALUE
internal inline fun Size.widthPx(scale: Scale, original: () -> Int): Int {
return if (isOriginal) original() else width.toPx(scale)
}
internal inline fun Size.heightPx(scale: Scale, original: () -> Int): Int {
return if (isOriginal) original() else height.toPx(scale)
}
internal fun Dimension.toPx(scale: Scale) = pxOrElse {
when (scale) {
Scale.FILL -> Int.MIN_VALUE
Scale.FIT -> Int.MAX_VALUE
}
}
internal fun unsupported(): Nothing = error("Unsupported")
internal const val ASSET_FILE_PATH_ROOT = "android_asset"
internal fun isAssetUri(uri: Uri): Boolean {
return uri.scheme == SCHEME_FILE && uri.firstPathSegment == ASSET_FILE_PATH_ROOT
}
/** Modified from [Headers.Builder.add] */
internal fun Headers.Builder.addUnsafeNonAscii(line: String) = apply {
val index = line.indexOf(':')
require(index != -1) { "Unexpected header: $line" }
addUnsafeNonAscii(line.substring(0, index).trim(), line.substring(index + 1))
}
private const val STANDARD_MEMORY_MULTIPLIER = 0.2
private const val LOW_MEMORY_MULTIPLIER = 0.15
/** Return the default percent of the application's total memory to use for the memory cache. */
internal fun defaultMemoryCacheSizePercent(context: Context): Double {
return try {
val activityManager: ActivityManager = context.requireSystemService()
if (activityManager.isLowRamDevice) LOW_MEMORY_MULTIPLIER else STANDARD_MEMORY_MULTIPLIER
} catch (_: Exception) {
STANDARD_MEMORY_MULTIPLIER
}
}
private const val DEFAULT_MEMORY_CLASS_MEGABYTES = 256
/** Return a [percent] of the application's total memory in bytes. */
internal fun calculateMemoryCacheSize(context: Context, percent: Double): Int {
val memoryClassMegabytes = try {
val activityManager: ActivityManager = context.requireSystemService()
val isLargeHeap = (context.applicationInfo.flags and ApplicationInfo.FLAG_LARGE_HEAP) != 0
if (isLargeHeap) activityManager.largeMemoryClass else activityManager.memoryClass
} catch (_: Exception) {
DEFAULT_MEMORY_CLASS_MEGABYTES
}
return (percent * memoryClassMegabytes * 1024 * 1024).toInt()
}
/**
* Holds the singleton instance of the disk cache. We need to have a singleton disk cache
* instance to support creating multiple [ImageLoader]s without specifying the disk cache
* directory.
*
* @see DiskCache.Builder.directory
*/
internal object SingletonDiskCache {
private const val FOLDER_NAME = "image_cache"
private var instance: DiskCache? = null
@Synchronized
fun get(context: Context): DiskCache {
return instance ?: run {
// Create the singleton disk cache instance.
DiskCache.Builder()
.directory(context.safeCacheDir.resolve(FOLDER_NAME))
.build()
.also { instance = it }
}
}
}
| coil-base/src/main/java/coil/util/Utils.kt | 3527212099 |
package com.zj.example.kotlin.basicsknowledge
/**
* 构造函数example
* CreateTime: 17/9/7 13:38
* @author 郑炯
*/
fun main(args: Array<String>) {
val a = Customer("jinjin");
println(a.name)
}
/**
* 1.标准构造函数写法
*/
private class Person constructor(val name: String) {
fun sayHello() {
println("hello $name")
}
}
private data class Person2(val name:String?=null)
/**
* 2.构造函数简写
*/
private class Animal(val name: String) {
fun sayHello() {
println("hello $name")
}
}
/**
* 3.在构造函数中声明的参数,它们默认属于类的公有字段,可以直接使用,
* 如果你不希望别的类访问到这个变量,可以用private修饰。
*/
private class Cat(private val name: String) {
fun miao() {
println("$name 喵")
}
}
/**
* 在主构造函数中不能有任何代码实现,如果有额外的代码需要在构造方法中执行,
* 你需要放到init代码块中执行。同时,在本示例中由于需要更改 name 参数的值,
* 我们将 val 改为 var,表明 name 参数是一个可改变的参数。
*/
private class Dog(var name: String) {
init {
name = "金金"
}
}
/**
* 注意主构造函数的参数可以用在初始化块内,也可以用在类的属性初始化声明处:
*/
class Customer(val name: String) {
val upperCaseName = name.toUpperCase()
}
/**
* 类也可以有二级构造函数,需要加前缀 constructor:
*/
class SecondConstructorClass1 {
constructor(parent: String) {
println(parent)
}
}
/**
* 如果类有主构造函数,每个二级构造函数都要,或直接或间接通过另一个二级构造函数代理主构造函数。
* 在同一个类中代理另一个构造函数使用 this 关键字:
*/
class SecondConstructorClass2(val name: String) {
constructor(name: String, age: Int) : this(name) {
}
}
/**
* 如果一个非抽象类没有声明构造函数(主构造函数或二级构造函数),它会产生一个没有参数的构造函数。该构造函数的可见
* 性是 public 。如果你不想你的类有公共的构造函数,你就得声明一个拥有非默认可见性的空主构造函数:
*/
class ConstructorClass {
}
class PrivateConstructorClass private constructor() {
}
/**
* 注意:在 JVM 虚拟机中,如果主构造函数的所有参数都有默认值,编译器会生成一个附加的无参的构造函数,
* 这个构造函数会直接使用默认值。这使得 Kotlin 可以更简单的使用像 Jackson 或者 JPA
* 这样使用无参构造函数来创建类实例的库。
*/
class DefaultValueConstructorClass(name: String = "ZhengJiong") {
}
fun main2(args: Array<String>) {
val b = SecondaryConstructorClass2("zj")
println(b.name)
}
fun main3(args: Array<String>) {
var obj = SecondaryConstructorClass1("zhengjiong", 32)
println("${obj.name} ${obj.age}")
}
/**
* 如果声明了主构造函数, 二级构造函数必须通过this调用主构造函数
* 由于次级构造函数不能直接将参数转换为字段,所以需要手动声明一个 age 字段,并为 age 字段赋值。
*/
class SecondaryConstructorClass1(val name: String) {
var age: Int? = 0;
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
/**
* 由于次级构造函数不能直接将参数转换为字段,所以需要手动声明一个 name 字段,并为 name 字段赋值。
*/
class SecondaryConstructorClass2 {
var name: String? = null
constructor(name: String) {
this.name = name
}
}
fun main4(args: Array<String>) {
var obj = ConstructorPrivateClass("zj")
}
/**
* 如果一个非抽象类没有声明构造函数(主构造函数或二级构造函数),它会产生一个没有参数的构造函数。该
* 构造函数的可见性是 public 。如果你不想你的类有公共的构造函数,你就得声明一个拥有非默认可见性的空主构造函数:
*/
class ConstructorPrivateClass private constructor() {
var name: String? = null
/**
* 默认构造参数是private的不能通过其创建对象, 但是这个有参构造函数创建对象,
* 如果声明了主构造函数, 二级构造函数必须通过this调用主构造函数
*/
constructor(name: String) : this() {
}
/**
* 可以通过这个构造函数调用上面那个构造函数
*/
constructor(age: Int) : this("zhengjiong") {
}
} | src/main/kotlin/com/zj/example/kotlin/basicsknowledge/1.ConstructorExample构造函数.kt | 1659017247 |
package siosio.jsr352.jsl
data class Property(val name: String, val value: String) {
fun build(): String = "<property name='${name}' value='${value}' />"
}
| src/main/kotlin/siosio/jsr352/jsl/Property.kt | 3184349584 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.text.styling
import android.content.Context
import androidx.annotation.ColorRes
import androidx.annotation.FontRes
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
fun Context.getColorCompat(@ColorRes colorRes: Int) = ContextCompat.getColor(this, colorRes)
fun Context.getFontCompat(@FontRes fontRes: Int) = ResourcesCompat.getFont(this, fontRes) | TextStyling/app/src/main/java/com/android/example/text/styling/Extensions.kt | 1582264750 |
package org.rust.ide.intentions
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RustBlockExprElement
import org.rust.lang.core.psi.RustExprElement
import org.rust.lang.core.psi.util.getNextNonCommentSibling
import org.rust.lang.core.psi.util.parentOfType
class UnwrapSingleExprIntention : PsiElementBaseIntentionAction() {
override fun getText() = "Remove braces from single expression"
override fun getFamilyName() = text
override fun startInWriteAction() = true
private data class Context(
val blockExpr: RustBlockExprElement
)
private fun findContext(element: PsiElement): Context? {
if (!element.isWritable) return null
val blockExpr = element.parentOfType<RustBlockExprElement>() as? RustBlockExprElement ?: return null
val block = blockExpr.block ?: return null
if (block.expr != null
&& block.lbrace.getNextNonCommentSibling() == block.expr) {
return Context(blockExpr)
}
return null
}
override fun invoke(project: Project, editor: Editor, element: PsiElement) {
val ctx = findContext(element) ?: return
val block = ctx.blockExpr
val blockBody = ctx.blockExpr.block?.expr ?: return
val relativeCaretPosition = editor.caretModel.offset - blockBody.textOffset
val offset = (block.replace(blockBody) as RustExprElement).textOffset
editor.caretModel.moveToOffset(offset + relativeCaretPosition)
}
override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean {
return findContext(element) != null
}
}
| src/main/kotlin/org/rust/ide/intentions/UnwrapSingleExprIntention.kt | 102295562 |
package tutorial.coroutine.select
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.selects.select
suspend fun CoroutineScope.produceNumbers(side: SendChannel<Int>) = produce<Int> {
for (num in 1..10) {
// 生产从 1 到 10 的 10 个数值
delay(100) // 延迟 100 毫秒
select<Unit> {
onSend(num) {} // 发送到主通道
side.onSend(num) {} // 或者发送到 side 通道
}
}
}
fun main() = runBlocking {
val side = Channel<Int>() // 分配 side 通道
launch {
// 对于 side 通道来说,这是一个很快的消费者
side.consumeEach {
println("Side channel has $it")
}
}
produceNumbers(side).consumeEach {
println("Consuming $it")
delay(250) // 不要着急,让我们正确消化消耗被发送来的数字
}
println("Done consuming")
coroutineContext.cancelChildren()
}
| src/kotlin/src/tutorial/coroutine/select/SelectOnSend.kt | 2445050730 |
/*
* 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.example.viewbasedfeedlayoutsample.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.example.viewbasedfeedlayoutsample.data.Sweets
import com.example.viewbasedfeedlayoutsample.databinding.FragmentSweetsFeedItemBinding
/**
* [RecyclerView.Adapter] that can display a [Sweets].
*/
class MySweetsRecyclerViewAdapter(
private val values: List<Sweets>,
private val onSweetsSelected: (Sweets) -> Unit = {}
) : RecyclerView.Adapter<MySweetsRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
FragmentSweetsFeedItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = values[position]
holder.descriptionView.text =
holder.descriptionView.context.getString(item.description)
holder.thumbnailView.load(item.imageUrl)
holder.setClickListener { onSweetsSelected(item) }
}
override fun getItemCount(): Int = values.size
inner class ViewHolder(binding: FragmentSweetsFeedItemBinding) : RecyclerView.ViewHolder(binding.root) {
val descriptionView: TextView = binding.description
val thumbnailView: ImageView = binding.thumbnail
private val root = binding.root
fun setClickListener(listener: (View) -> Unit) {
root.setOnClickListener(listener)
}
override fun toString(): String {
return super.toString() + " '" + descriptionView.text + "'"
}
}
}
| CanonicalLayouts/feed-view/app/src/main/java/com/example/viewbasedfeedlayoutsample/ui/MySweetsRecyclerViewAdapter.kt | 596820349 |
package org.rust.cargo.runconfig
import com.intellij.execution.filters.RegexpFilter
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
/**
* Detects source code locations in rustc output and adds links to them.
*/
class RustConsoleFilter(
project: Project,
cargoProjectDir: VirtualFile
) : RegexpFileLinkFilter(
project,
cargoProjectDir,
"(?: --> )?${RegexpFilter.FILE_PATH_MACROS}:${RegexpFilter.LINE_MACROS}:${RegexpFilter.COLUMN_MACROS}") {
}
| src/main/kotlin/org/rust/cargo/runconfig/RustConsoleFilter.kt | 3859517418 |
package me.proxer.app.settings.status
import android.app.Activity
import android.os.Bundle
import androidx.fragment.app.commitNow
import me.proxer.app.R
import me.proxer.app.base.DrawerActivity
import me.proxer.app.util.extension.startActivity
/**
* @author Ruben Gees
*/
class ServerStatusActivity : DrawerActivity() {
companion object {
fun navigateTo(context: Activity) = context.startActivity<ServerStatusActivity>()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = getString(R.string.section_server_status)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (savedInstanceState == null) {
supportFragmentManager.commitNow {
replace(R.id.container, ServerStatusFragment.newInstance())
}
}
}
}
| src/main/kotlin/me/proxer/app/settings/status/ServerStatusActivity.kt | 859925658 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.rebase
import com.intellij.dvcs.DvcsUtil
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.util.LineSeparator
import git4idea.branch.GitBranchUiHandler
import git4idea.branch.GitBranchWorker
import git4idea.branch.GitRebaseParams
import git4idea.repo.GitRepository
import git4idea.test.*
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import kotlin.properties.Delegates
import kotlin.test.assertFailsWith
class GitSingleRepoRebaseTest : GitRebaseBaseTest() {
protected var myRepo: GitRepository by Delegates.notNull()
override fun setUp() {
super.setUp()
myRepo = createRepository(myProjectPath)
}
fun `test simple case`() {
myRepo.`diverge feature and master`()
rebaseOnMaster()
assertSuccessfulRebaseNotification("Rebased feature on master")
myRepo.`assert feature rebased on master`()
assertNoRebaseInProgress(myRepo)
}
fun `test up-to-date`() {
myRepo.`place feature above master`()
rebaseOnMaster()
assertSuccessfulRebaseNotification("feature is up-to-date with master")
myRepo.`assert feature rebased on master`()
assertNoRebaseInProgress(myRepo)
}
fun test_ff() {
myRepo.`place feature below master`()
rebaseOnMaster()
assertSuccessfulRebaseNotification("Fast-forwarded feature to master")
myRepo.`assert feature rebased on master`()
assertNoRebaseInProgress(myRepo)
}
fun `test conflict resolver is shown`() {
myRepo.`prepare simple conflict`()
`do nothing on merge`()
rebaseOnMaster()
`assert merge dialog was shown`()
}
fun `test fail on 2nd commit should show notification with proposal to abort`() {
myRepo.`make rebase fail on 2nd commit`()
rebaseOnMaster()
`assert unknown error notification with link to abort`()
}
fun `test multiple conflicts`() {
build {
master {
0("c.txt")
1("c.txt")
}
feature(0) {
2("c.txt")
3("c.txt")
}
}
var conflicts = 0
vcsHelper.onMerge {
conflicts++
myRepo.assertConflict("c.txt")
resolveConflicts(myRepo)
}
rebaseOnMaster()
assertEquals("Incorrect number of conflicting patches", 2, conflicts)
myRepo.`assert feature rebased on master`()
assertSuccessfulRebaseNotification("Rebased feature on master")
}
fun `test continue rebase after resolving all conflicts`() {
myRepo.`prepare simple conflict`()
vcsHelper.onMerge {
resolveConflicts(myRepo)
}
rebaseOnMaster()
assertSuccessfulRebaseNotification("Rebased feature on master")
myRepo.`assert feature rebased on master`()
assertNoRebaseInProgress(myRepo)
}
fun `test warning notification if conflicts were not resolved`() {
myRepo.`prepare simple conflict`()
`do nothing on merge`()
rebaseOnMaster()
`assert conflict not resolved notification`()
myRepo.assertRebaseInProgress()
}
fun `test skip if user decides to skip`() {
myRepo.`prepare simple conflict`()
`do nothing on merge`()
rebaseOnMaster()
GitRebaseUtils.skipRebase(myProject)
assertSuccessfulRebaseNotification("Rebased feature on master")
myRepo.`assert feature rebased on master`()
assertNoRebaseInProgress(myRepo)
}
fun `test rebase failed for unknown reason`() {
myRepo.`diverge feature and master`()
myGit.setShouldRebaseFail { true }
rebaseOnMaster()
`assert unknown error notification`()
}
fun `test propose to abort when rebase failed after continue`() {
myRepo.`prepare simple conflict`()
`do nothing on merge`()
rebaseOnMaster()
myRepo.`assert feature not rebased on master`()
myRepo.assertRebaseInProgress()
resolveConflicts(myRepo)
myGit.setShouldRebaseFail { true }
GitRebaseUtils.continueRebase(myProject)
`assert unknown error notification with link to abort`(true)
myRepo.`assert feature not rebased on master`()
myRepo.assertRebaseInProgress()
}
fun `test local changes auto-saved initially`() {
myRepo.`diverge feature and master`()
val localChange = LocalChange(myRepo, "new.txt").generate()
object : GitTestingRebaseProcess(myProject, simpleParams("master"), myRepo) {
override fun getDirtyRoots(repositories: Collection<GitRepository>): Collection<GitRepository> {
return listOf(myRepo)
}
}.rebase()
assertSuccessfulRebaseNotification("Rebased feature on master")
assertRebased(myRepo, "feature", "master")
assertNoRebaseInProgress(myRepo)
localChange.verify()
}
fun `test local changes are saved even if not detected initially`() {
myRepo.`diverge feature and master`()
val localChange = LocalChange(myRepo, "new.txt").generate()
object : GitTestingRebaseProcess(myProject, simpleParams("master"), myRepo) {
override fun getDirtyRoots(repositories: Collection<GitRepository>): Collection<GitRepository> {
return emptyList()
}
}.rebase()
assertSuccessfulRebaseNotification("Rebased feature on master")
assertRebased(myRepo, "feature", "master")
assertNoRebaseInProgress(myRepo)
localChange.verify()
}
fun `test local changes are not restored in case of error even if nothing was rebased`() {
myRepo.`diverge feature and master`()
LocalChange(myRepo, "new.txt", "content").generate()
myGit.setShouldRebaseFail { true }
rebaseOnMaster()
assertErrorNotification("Rebase Failed",
"""
$UNKNOWN_ERROR_TEXT<br/>
<a>Retry.</a><br/>
Note that some local changes were <a>stashed</a> before rebase.
""")
assertNoRebaseInProgress(myRepo)
myRepo.assertNoLocalChanges()
assertFalse(file("new.txt").exists())
}
fun `test critical error should show notification and not restore local changes`() {
myRepo.`diverge feature and master`()
LocalChange(myRepo, "new.txt", "content").generate()
myGit.setShouldRebaseFail { true }
rebaseOnMaster()
`assert unknown error notification with link to stash`()
myRepo.assertNoLocalChanges()
}
fun `test successful retry from notification on critical error restores local changes`() {
myRepo.`diverge feature and master`()
val localChange = LocalChange(myRepo, "new.txt", "content").generate()
var attempt = 0
myGit.setShouldRebaseFail { attempt == 0 }
rebaseOnMaster()
attempt++
myVcsNotifier.lastNotification
GitRebaseUtils.continueRebase(myProject)
assertNoRebaseInProgress(myRepo)
myRepo.`assert feature rebased on master`()
localChange.verify()
}
fun `test local changes are restored after successful abort`() {
myRepo.`prepare simple conflict`()
val localChange = LocalChange(myRepo, "new.txt", "content").generate()
`do nothing on merge`()
myDialogManager.onMessage { Messages.YES }
rebaseOnMaster()
`assert conflict not resolved notification with link to stash`()
GitRebaseUtils.abort(myProject, EmptyProgressIndicator())
assertNoRebaseInProgress(myRepo)
myRepo.`assert feature not rebased on master`()
localChange.verify()
}
fun `test local changes are not restored after failed abort`() {
myRepo.`prepare simple conflict`()
LocalChange(myRepo, "new.txt", "content").generate()
`do nothing on merge`()
myDialogManager.onMessage { Messages.YES }
rebaseOnMaster()
`assert conflict not resolved notification with link to stash`()
myGit.setShouldRebaseFail { true }
GitRebaseUtils.abort(myProject, EmptyProgressIndicator())
myRepo.assertRebaseInProgress()
myRepo.`assert feature not rebased on master`()
myRepo.assertConflict("c.txt")
assertErrorNotification("Rebase Abort Failed",
"""
unknown error<br/>
$LOCAL_CHANGES_WARNING
""")
}
// git rebase --continue should be either called from a commit dialog, either from the GitRebaseProcess.
// both should prepare the working tree themselves by adding all necessary changes to the index.
fun `test local changes in the conflicting file should lead to error on continue rebase`() {
myRepo.`prepare simple conflict`()
`do nothing on merge`()
rebaseOnMaster()
myRepo.assertConflict("c.txt")
//manually resolve conflicts
resolveConflicts(myRepo)
file("c.txt").append("more changes after resolving")
// forget to git add afterwards
GitRebaseUtils.continueRebase(myProject)
`assert error about unstaged file before continue rebase`("c.txt")
myRepo.`assert feature not rebased on master`()
myRepo.assertRebaseInProgress()
}
fun `test local changes in some other file should lead to error on continue rebase`() {
build {
master {
0("d.txt")
1("c.txt")
2("c.txt")
}
feature(1) {
3("c.txt")
}
}
`do nothing on merge`()
rebaseOnMaster()
myRepo.assertConflict("c.txt")
//manually resolve conflicts
resolveConflicts(myRepo)
// add more changes to some other file
file("d.txt").append("more changes after resolving")
GitRebaseUtils.continueRebase(myProject)
`assert error about unstaged file before continue rebase`("d.txt")
myRepo.`assert feature not rebased on master`()
myRepo.assertRebaseInProgress()
}
fun `test unresolved conflict should lead to conflict resolver with continue rebase`() {
myRepo.`prepare simple conflict`()
`do nothing on merge`()
rebaseOnMaster()
myRepo.assertConflict("c.txt")
vcsHelper.onMerge {
resolveConflicts(myRepo)
}
GitRebaseUtils.continueRebase(myProject)
assertSuccessfulRebaseNotification("Rebased feature on master")
myRepo.`assert feature rebased on master`()
assertNoRebaseInProgress(myRepo)
}
fun `test skipped commit`() {
build {
master {
0("c.txt", "base")
1("c.txt", "\nmaster")
}
feature(0) {
2("c.txt", "feature", "commit to be skipped")
3()
}
}
val hash2skip = DvcsUtil.getShortHash(git("log -2 --pretty=%H").lines()[1])
vcsHelper.onMerge {
file("c.txt").write("base\nmaster")
resolveConflicts(myRepo)
}
rebaseOnMaster()
assertRebased(myRepo, "feature", "master")
assertNoRebaseInProgress(myRepo)
assertSuccessfulRebaseNotification(
"""
Rebased feature on master<br/>
The following commit was skipped during rebase:<br/>
<a>$hash2skip</a> commit to be skipped
""")
}
fun `test interactive rebase stopped for editing`() {
build {
master {
0()
1()
}
feature(1) {
2()
3()
}
}
myGit.setInteractiveRebaseEditor {
it.lines().mapIndexed { i, s ->
if (i != 0) s
else s.replace("pick", "edit")
}.joinToString(LineSeparator.getSystemLineSeparator().separatorString)
}
rebaseInteractively()
assertSuccessfulNotification("Rebase Stopped for Editing", "Once you are satisfied with your changes you may <a href='continue'>continue</a>")
assertEquals("The repository must be in the 'SUSPENDED' state", myRepo, myGitRepositoryManager.ongoingRebaseSpec!!.ongoingRebase)
GitRebaseUtils.continueRebase(myProject)
assertSuccessfulRebaseNotification("Rebased feature on master")
myRepo.`assert feature rebased on master`()
assertNoRebaseInProgress(myRepo)
}
fun `test cancel in interactive rebase should show no error notification`() {
myRepo.`diverge feature and master`()
myDialogManager.onDialog(GitRebaseEditor::class.java) { DialogWrapper.CANCEL_EXIT_CODE }
assertFailsWith(ProcessCanceledException::class) { rebaseInteractively() }
assertNoNotification()
assertNoRebaseInProgress(myRepo)
myRepo.`assert feature not rebased on master`()
}
fun `test cancel in noop case should show no error notification`() {
build {
master {
0()
1()
}
feature(0) {}
}
myDialogManager.onMessage { Messages.CANCEL }
assertFailsWith(ProcessCanceledException::class) { rebaseInteractively() }
assertNoNotification()
assertNoRebaseInProgress(myRepo)
myRepo.`assert feature not rebased on master`()
}
private fun rebaseInteractively() {
GitTestingRebaseProcess(myProject, GitRebaseParams(null, null, "master", true, false), myRepo).rebase()
}
fun `test checkout with rebase`() {
myRepo.`diverge feature and master`()
git(myRepo, "checkout master")
val uiHandler = Mockito.mock(GitBranchUiHandler::class.java)
`when`(uiHandler.progressIndicator).thenReturn(EmptyProgressIndicator())
GitBranchWorker(myProject, myGit, uiHandler).rebaseOnCurrent(listOf(myRepo), "feature")
assertSuccessfulRebaseNotification("Checked out feature and rebased it on master")
myRepo.`assert feature rebased on master`()
assertNoRebaseInProgress(myRepo)
}
private fun build(f: RepoBuilder.() -> Unit) {
build(myRepo, f)
}
private fun rebaseOnMaster() {
GitTestingRebaseProcess(myProject, simpleParams("master"), myRepo).rebase()
}
private fun simpleParams(newBase: String): GitRebaseParams {
return GitRebaseParams(newBase)
}
}
| plugins/git4idea/tests/git4idea/rebase/GitSingleRepoRebaseTest.kt | 717530419 |
package appnexus.com.trackertestapp.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import appnexus.com.trackertestapp.R
import appnexus.com.trackertestapp.listener.RecyclerItemClickListener
import kotlinx.android.synthetic.main.layout_recycler.view.*
class AdRecyclerAdapter(
val items: ArrayList<String>,
val context: Context,
val listener: RecyclerItemClickListener
) : RecyclerView.Adapter<AdRecyclerAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(context).inflate(
R.layout.layout_recycler, parent, false
))
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.tvAd.text = items.get(position)
holder.tvAd.setOnClickListener {
listener.onItemClick(position)
}
}
class ViewHolder (view: View) : RecyclerView.ViewHolder(view) {
// Holds the TextView that will add each animal to
val tvAd = view.tvAd
}
} | tests/TrackerTestApp/app/src/main/java/appnexus/com/trackertestapp/adapter/AdRecyclerAdapter.kt | 4211180905 |
package library.enrichment
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import java.time.Clock
@SpringBootApplication(exclude = [
SecurityAutoConfiguration::class,
ErrorMvcAutoConfiguration::class
])
class Application {
@Bean fun utcClock(): Clock = Clock.systemUTC()
@Bean fun objectMapper(): ObjectMapper = ObjectMapper().apply { findAndRegisterModules() }
}
fun main(args: Array<String>) {
runApplication<Application>(*args)
}
| library-enrichment/src/main/kotlin/library/enrichment/Application.kt | 3435355565 |
/**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java.refactor
import org.junit.jupiter.api.Test
import org.openrewrite.java.JavaParser
import org.openrewrite.java.assertRefactored
open class AddImportTest : JavaParser() {
@Test
fun addMultipleImports() {
val a = parse("class A {}")
val fixed = a.refactor()
.visit(AddImport("java.util.List", null, false))
.visit(AddImport("java.util.Set", null, false))
.fix().fixed
assertRefactored(fixed, """
import java.util.List;
import java.util.Set;
class A {}
""")
}
@Test
fun addNamedImport() {
val a = parse("class A {}")
val fixed = a.refactor().visit(AddImport("java.util.List", null, false)).fix().fixed
assertRefactored(fixed, """
import java.util.List;
class A {}
""")
}
@Test
fun addNamedImportByClass() {
val a = parse("class A {}")
val fixed = a.refactor().visit(AddImport("java.util.List", null, false)).fix().fixed
assertRefactored(fixed, """
import java.util.List;
class A {}
""")
}
@Test
fun namedImportAddedAfterPackageDeclaration() {
val a = parse("""
package a;
class A {}
""".trimIndent())
val fixed = a.refactor().visit(AddImport("java.util.List", null, false)).fix().fixed
assertRefactored(fixed, """
package a;
import java.util.List;
class A {}
""")
}
@Test
fun importsAddedInAlphabeticalOrder() {
val otherPackages = listOf("c", "c.c", "c.c.c")
val otherImports = otherPackages.mapIndexed { i, pkg ->
"package $pkg;\npublic class C$i {}"
}
listOf("b" to 0, "c.b" to 1, "c.c.b" to 2).forEach {
val (pkg, order) = it
val b = """
package $pkg;
public class B {}
"""
val cu = parse("""
package a;
import c.C0;
import c.c.C1;
import c.c.c.C2;
class A {}
""".trimIndent(), otherImports.plus(b))
val fixed = cu.refactor().visit(AddImport("$pkg.B", null, false)).fix().fixed
val expectedImports = otherPackages.mapIndexed { i, otherPkg -> "$otherPkg.C$i" }.toMutableList()
expectedImports.add(order, "$pkg.B")
assertRefactored(fixed, "package a;\n\n${expectedImports.joinToString("\n") { fqn -> "import $fqn;" }}\n\nclass A {}")
reset()
}
}
@Test
fun doNotAddImportIfAlreadyExists() {
val a = parse("""
package a;
import java.util.List;
class A {}
""".trimIndent())
val fixed = a.refactor().visit(AddImport("java.util.List", null, false)).fix().fixed
assertRefactored(fixed, """
package a;
import java.util.List;
class A {}
""")
}
@Test
fun doNotAddImportIfCoveredByStarImport() {
val a = parse("""
package a;
import java.util.*;
class A {}
""".trimIndent())
val fixed = a.refactor().visit(AddImport("java.util.List", null, false)).fix().fixed
assertRefactored(fixed, """
package a;
import java.util.*;
class A {}
""")
}
@Test
fun addNamedImportIfStarStaticImportExists() {
val a = parse("""
package a;
import static java.util.List.*;
class A {}
""".trimIndent())
val fixed = a.refactor().visit(AddImport("java.util.List", null, false)).fix().fixed
assertRefactored(fixed, """
package a;
import java.util.List;
import static java.util.List.*;
class A {}
""")
}
@Test
fun addNamedStaticImport() {
val a = parse("""
import java.util.*;
class A {}
""".trimIndent())
val fixed = a.refactor()
.visit(AddImport("java.util.Collections", "emptyList", false))
.fix().fixed
assertRefactored(fixed, """
import java.util.*;
import static java.util.Collections.emptyList;
class A {}
""")
}
@Test
fun dontAddImportWhenClassHasNoPackage() {
val a = parse("class A {}")
val fixed = a.refactor().visit(AddImport("C", null, false)).fix().fixed
assertRefactored(fixed, "class A {}")
}
}
| rewrite-java/src/test/kotlin/org/openrewrite/java/refactor/AddImportTest.kt | 2989080353 |
/*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.vanniktech.emoji.material
import android.content.Context
import android.text.SpannableStringBuilder
import android.util.AttributeSet
import androidx.annotation.AttrRes
import androidx.annotation.CallSuper
import androidx.annotation.DimenRes
import androidx.annotation.Px
import com.google.android.material.radiobutton.MaterialRadioButton
import com.vanniktech.emoji.EmojiDisplayable
import com.vanniktech.emoji.EmojiManager
import com.vanniktech.emoji.init
import com.vanniktech.emoji.replaceWithImages
import kotlin.jvm.JvmOverloads
open class EmojiMaterialRadioButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
@AttrRes defStyleAttr: Int = com.google.android.material.R.attr.radioButtonStyle,
) : MaterialRadioButton(context, attrs, defStyleAttr), EmojiDisplayable {
@Px private var emojiSize: Float
init {
emojiSize = init(attrs, R.styleable.EmojiMaterialRadioButton, R.styleable.EmojiMaterialRadioButton_emojiSize)
}
@CallSuper override fun setText(rawText: CharSequence?, type: BufferType) {
if (isInEditMode) {
super.setText(rawText, type)
return
}
val spannableStringBuilder = SpannableStringBuilder(rawText ?: "")
val fontMetrics = paint.fontMetrics
val defaultEmojiSize = fontMetrics.descent - fontMetrics.ascent
EmojiManager.replaceWithImages(context, spannableStringBuilder, if (emojiSize != 0f) emojiSize else defaultEmojiSize)
super.setText(spannableStringBuilder, type)
}
override fun getEmojiSize() = emojiSize
override fun setEmojiSize(@Px pixels: Int) = setEmojiSize(pixels, true)
override fun setEmojiSize(@Px pixels: Int, shouldInvalidate: Boolean) {
emojiSize = pixels.toFloat()
if (shouldInvalidate) {
text = text
}
}
override fun setEmojiSizeRes(@DimenRes res: Int) = setEmojiSizeRes(res, true)
override fun setEmojiSizeRes(@DimenRes res: Int, shouldInvalidate: Boolean) =
setEmojiSize(resources.getDimensionPixelSize(res), shouldInvalidate)
}
| emoji-material/src/androidMain/kotlin/com/vanniktech/emoji/material/EmojiMaterialRadioButton.kt | 3478336835 |
package io.polymorphicpanda.kspec.engine
import io.polymorphicpanda.kspec.Configuration
import io.polymorphicpanda.kspec.KSpec
import io.polymorphicpanda.kspec.StandardConfiguration
import io.polymorphicpanda.kspec.Utils
import io.polymorphicpanda.kspec.annotation.Configurations
import io.polymorphicpanda.kspec.config.KSpecConfig
import io.polymorphicpanda.kspec.context.Context
import io.polymorphicpanda.kspec.engine.discovery.DiscoveryRequest
import io.polymorphicpanda.kspec.engine.discovery.DiscoveryResult
import io.polymorphicpanda.kspec.engine.execution.ExecutionNotifier
import io.polymorphicpanda.kspec.engine.execution.ExecutionRequest
import io.polymorphicpanda.kspec.engine.execution.ExecutionResult
import io.polymorphicpanda.kspec.engine.filter.FilteringVisitor
import io.polymorphicpanda.kspec.engine.filter.MatchingVisitor
import io.polymorphicpanda.kspec.engine.query.Query
import io.polymorphicpanda.kspec.hook.AroundHook
import io.polymorphicpanda.kspec.hook.Chain
import io.polymorphicpanda.kspec.tag.Tag
import java.util.*
import kotlin.reflect.KClass
/**
* @author Ranie Jade Ramiso
*/
class KSpecEngine(val notifier: ExecutionNotifier) {
fun discover(discoveryRequest: DiscoveryRequest): DiscoveryResult {
val instances = LinkedHashMap<KSpec, KSpecConfig>()
discoveryRequest.specs.forEach {
val instance = Utils.instantiateUsingNoArgConstructor(it)
val config = discover(instance, discoveryRequest)
instances.put(instance, config)
}
return DiscoveryResult(instances)
}
fun execute(discoveryResult: DiscoveryResult) {
execute(ExecutionRequest(discoveryResult))
}
fun execute(executionRequest: ExecutionRequest) {
notifier.notifyExecutionStarted()
executionRequest.discoveryResult.instances.forEach {
execute(it.value, it.key.root)
}
notifier.notifyExecutionFinished()
}
private fun execute(config: KSpecConfig, context: Context) {
if (context.contains(config.filter.ignore)) {
notifyContextIgnored(context)
} else {
config.before.filter { it.handles(context) }
.forEach { it.execute(context) }
val aroundHooks = LinkedList<AroundHook>(
config.around.filter { it.handles(context) }
)
aroundHooks.addLast(AroundHook({ context, chain ->
when(context) {
is Context.Example -> {
notifier.notifyExampleStarted(context)
try {
invokeBeforeEach(context.parent)
// ensures that afterEach is still invoke even if the test fails
try {
context.execute()
notifier.notifyExampleFinished(context, ExecutionResult.success(context))
} catch (e: Throwable) {
notifier.notifyExampleFinished(context, ExecutionResult.failure(context, e))
}
invokeAfterEach(context.parent)
} catch (e: Throwable) {
notifier.notifyExampleFinished(context, ExecutionResult.failure(context, e))
}
}
is Context.ExampleGroup -> {
try {
context.before?.invoke()
notifier.notifyExampleGroupStarted(context)
context.children.forEach {
execute(config, it)
}
context.after?.invoke()
notifier.notifyExampleGroupFinished(context, ExecutionResult.success(context))
} catch(e: Throwable) {
notifier.notifyExampleGroupFinished(context, ExecutionResult.failure(context, e))
}
}
}
}, emptySet()))
val exec = Chain(aroundHooks)
exec.next(context)
config.after.filter { it.handles(context) }
.forEach { it.execute(context) }
}
}
private fun notifyContextIgnored(context: Context) {
when(context) {
is Context.ExampleGroup -> notifier.notifyExampleGroupIgnored(context)
is Context.Example -> notifier.notifyExampleIgnored(context)
}
}
private fun applyMatchFilter(root: Context.ExampleGroup, match: Set<KClass<out Tag<*>>>) {
val predicate: (Context) -> Boolean = {
it.contains(match)
}
val matchingVisitor = MatchingVisitor(predicate)
root.visit(matchingVisitor)
if (matchingVisitor.matches) {
root.visit(FilteringVisitor(predicate))
}
}
private fun applyIncludeFilter(root: Context.ExampleGroup, includes: Set<KClass<out Tag<*>>>) {
root.visit(FilteringVisitor({
it.contains(includes)
}))
}
private fun applyExcludeFilter(root: Context.ExampleGroup, excludes: Set<KClass<out Tag<*>>>) {
root.visit(FilteringVisitor({
!it.contains(excludes)
}))
}
private fun applyQueryFilter(root: Context.ExampleGroup, query: Query) {
root.visit(FilteringVisitor({
query.matches(Query.transform(it))
}))
}
private fun discover(spec: KSpec, discoveryRequest: DiscoveryRequest): KSpecConfig {
spec.spec()
// apply global configuration
val config = KSpecConfig()
config.copy(discoveryRequest.config)
// apply shared configurations
val annotation = Utils.findAnnotation(spec.javaClass.kotlin, Configurations::class)
if (annotation != null) {
val configurations = annotation.configurations
configurations.forEach { it: KClass<out Configuration> ->
val configuration = Utils.instantiateUsingNoArgConstructor(it)
configuration.apply(config)
}
}
// apply spec configuration
spec.configure(config)
// built-in configurations
StandardConfiguration.apply(config)
val filter = config.filter
if (filter.match.isNotEmpty()) {
applyMatchFilter(spec.root, filter.match)
}
if (filter.includes.isNotEmpty()) {
applyIncludeFilter(spec.root, filter.includes)
}
if (filter.excludes.isNotEmpty()) {
applyExcludeFilter(spec.root, filter.excludes)
}
if (discoveryRequest.query != null) {
applyQueryFilter(spec.root, discoveryRequest.query)
}
spec.lock()
return config
}
private fun invokeBeforeEach(context: Context.ExampleGroup) {
if (context.parent != null) {
invokeBeforeEach(context.parent!!)
}
context.beforeEach?.invoke()
}
private fun invokeAfterEach(context: Context.ExampleGroup) {
context.afterEach?.invoke()
if (context.parent != null) {
invokeAfterEach(context.parent!!)
}
}
}
| kspec-engine/src/main/kotlin/io/polymorphicpanda/kspec/engine/KSpecEngine.kt | 2928674772 |
package se.ansman.kotshi
@JsonSerializable
@Polymorphic(labelKey = "type")
sealed class SealedClassWithDefaultWithType {
@JsonSerializable
@PolymorphicLabel("type1")
data class Subclass1(val foo: String) : SealedClassWithDefaultWithType()
@JsonSerializable
@PolymorphicLabel("type2")
data class Subclass2(val bar: String) : SealedClassWithDefaultWithType()
@JsonSerializable
@PolymorphicLabel("type3")
data class Subclass3(val baz: String) : SealedClassWithDefaultWithType()
@JsonSerializable
@JsonDefaultValue
@PolymorphicLabel("type4")
object Default : SealedClassWithDefaultWithType()
} | tests/src/main/kotlin/se/ansman/kotshi/SealedClassWithDefaultWithType.kt | 3175462852 |
package de.brlo.hopfen.feature.data
data class Profile(
val uuid: String,
val image: String,
val name: String,
val locations: List<Location>) {
data class Location(
val uuid: String,
val name: String,
val address: String) {
override fun toString(): String {
return name
}
}
companion object {
fun empty() = Profile("", "", "", emptyList())
}
}
| feature/src/main/kotlin/de/brlo/hopfen/feature/data/Profile.kt | 922435555 |
/**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.gs.obevo.impl.reader
import com.gs.obevo.api.appdata.ChangeInput
import com.gs.obevo.api.appdata.doc.TextMarkupDocumentSection
import com.gs.obevo.api.platform.ChangeType
import com.gs.obevo.api.platform.DeployMetrics
import com.gs.obevo.api.platform.FileSourceContext
import com.gs.obevo.api.platform.FileSourceParams
import com.gs.obevo.impl.DeployMetricsCollector
import com.gs.obevo.impl.DeployMetricsCollectorImpl
import com.gs.obevo.impl.OnboardingStrategy
import com.gs.obevo.util.VisibleForTesting
import com.gs.obevo.util.hash.OldWhitespaceAgnosticDbChangeHashStrategy
import com.gs.obevo.util.vfs.*
import com.gs.obevo.util.vfs.FileFilterUtils.*
import org.apache.commons.lang3.Validate
import org.apache.commons.vfs2.FileFilter
import org.eclipse.collections.api.block.function.Function
import org.eclipse.collections.api.block.function.Function0
import org.eclipse.collections.api.list.ImmutableList
import org.eclipse.collections.api.set.ImmutableSet
import org.eclipse.collections.impl.factory.Lists
import org.eclipse.collections.impl.factory.Sets
import org.eclipse.collections.impl.map.mutable.ConcurrentHashMap
import org.slf4j.LoggerFactory
class DbDirectoryChangesetReader : FileSourceContext {
private val convertDbObjectName: Function<String, String>
private val packageMetadataReader: PackageMetadataReader
private val packageMetadataCache = ConcurrentHashMap<FileObject, PackageMetadata>()
private val tableChangeParser: DbChangeFileParser
private val baselineTableChangeParser: DbChangeFileParser
private val rerunnableChangeParser: DbChangeFileParser
private val deployMetricsCollector: DeployMetricsCollector
constructor(convertDbObjectName: Function<String, String>, deployMetricsCollector: DeployMetricsCollector, backwardsCompatibleMode: Boolean, textMarkupDocumentReader: TextMarkupDocumentReader, baselineTableChangeParser: DbChangeFileParser, getChangeType: GetChangeType) {
this.packageMetadataReader = PackageMetadataReader(textMarkupDocumentReader)
this.convertDbObjectName = convertDbObjectName
this.tableChangeParser = TableChangeParser(OldWhitespaceAgnosticDbChangeHashStrategy(), backwardsCompatibleMode, deployMetricsCollector, textMarkupDocumentReader, getChangeType)
this.baselineTableChangeParser = baselineTableChangeParser
this.rerunnableChangeParser = RerunnableChangeParser(backwardsCompatibleMode, deployMetricsCollector, textMarkupDocumentReader)
this.deployMetricsCollector = deployMetricsCollector
}
@VisibleForTesting
constructor(convertDbObjectName: Function<String, String>, tableChangeParser: DbChangeFileParser,
baselineTableChangeParser: DbChangeFileParser, rerunnableChangeParser: DbChangeFileParser) {
this.packageMetadataReader = PackageMetadataReader(TextMarkupDocumentReader(false))
this.convertDbObjectName = convertDbObjectName
this.tableChangeParser = tableChangeParser
this.baselineTableChangeParser = baselineTableChangeParser
this.rerunnableChangeParser = rerunnableChangeParser
this.deployMetricsCollector = DeployMetricsCollectorImpl()
}
/*
* (non-Javadoc)
*
* @see com.gs.obevo.db.newdb.DbChangeReader#readChanges(java.io.File)
*/
override fun readChanges(fileSourceParams: FileSourceParams): ImmutableList<ChangeInput> {
if (fileSourceParams.isBaseline && baselineTableChangeParser == null) {
throw IllegalArgumentException("Cannot invoke readChanges with useBaseline == true if baselineTableChangeParser hasn't been set; baseline reading may not be enabled in your Platform type")
}
val allChanges = mutableListOf<ChangeInput>()
val envSchemas = fileSourceParams.schemaNames.collect(this.convertDbObjectName)
Validate.notEmpty(envSchemas.castToSet(), "Environment must have schemas populated")
for (sourceDir in fileSourceParams.files) {
for (schemaDir in sourceDir.findFiles(BasicFileSelector(and(vcsAware(), directory()), false))) {
val schema = schemaDir.name.baseName
if (envSchemas.contains(this.convertDbObjectName.valueOf(schema))) {
val schemaChanges = fileSourceParams.changeTypes.flatMap { changeType ->
val changeTypeDir = this.findDirectoryForChangeType(schemaDir, changeType, fileSourceParams.isLegacyDirectoryStructureEnabled)
if (changeTypeDir != null) {
if (changeType.isRerunnable) {
findChanges(changeType, changeTypeDir, this.rerunnableChangeParser, TrueFileFilter.INSTANCE, schema, fileSourceParams.acceptedExtensions, fileSourceParams.defaultSourceEncoding)
} else {
findTableChanges(changeType, changeTypeDir, schema, fileSourceParams.isBaseline, fileSourceParams.acceptedExtensions, fileSourceParams.defaultSourceEncoding)
}
} else {
emptyList<ChangeInput>()
}
}
val tableChangeMap = schemaChanges
.filter { Sets.immutable.of(ChangeType.TABLE_STR, ChangeType.FOREIGN_KEY_STR).contains(it.changeTypeName) }
.groupBy(ChangeInput::getDbObjectKey)
val staticDataChanges = schemaChanges.filter { it.changeTypeName.equals(ChangeType.STATICDATA_STR)}
// now enrich the staticData objects w/ the information from the tables to facilitate the
// deployment order calculation.
staticDataChanges.forEach { staticDataChange ->
val relatedTableChanges = tableChangeMap.get(staticDataChange.getDbObjectKey()) ?: emptyList()
val foreignKeys = relatedTableChanges.filter { it.changeTypeName == ChangeType.FOREIGN_KEY_STR }
val fkContent = foreignKeys.map { it.content }.joinToString("\n\n")
staticDataChange.setContentForDependencyCalculation(fkContent)
}
allChanges.addAll(schemaChanges)
} else {
LOG.info("Skipping schema directory [{}] as it was not defined among the schemas in your system-config.xml file: {}", schema, envSchemas)
continue
}
}
}
return Lists.immutable.ofAll(allChanges);
}
/**
* We have this here to look for directories in the various places we had specified it in the code before (i.e.
* for backwards-compatibility).
*/
private fun findDirectoryForChangeType(schemaDir: FileObject, changeType: ChangeType, legacyDirectoryStructureEnabled: Boolean): FileObject? {
var dir = schemaDir.getChild(changeType.directoryName)
if (dir != null && dir.exists()) {
return dir
}
dir = schemaDir.getChild(changeType.directoryName.toUpperCase())
if (dir != null && dir.exists()) {
return dir
}
if (legacyDirectoryStructureEnabled && changeType.directoryNameOld != null) {
// for backwards-compatibility
dir = schemaDir.getChild(changeType.directoryNameOld)
if (dir != null && dir.exists()) {
deployMetricsCollector.addMetric("oldDirectoryNameUsed", true)
return dir
}
}
return null
}
private fun findTableChanges(changeType: ChangeType, tableDir: FileObject, schema: String, useBaseline: Boolean, acceptedExtensions: ImmutableSet<String>, sourceEncoding: String): List<ChangeInput> {
val baselineFilter = WildcardFileFilter("*.baseline.*")
val nonBaselineFiles = findFiles(tableDir,
if (this.isUsingChangesConvention(tableDir)) CHANGES_WILDCARD_FILTER else NotFileFilter(baselineFilter), acceptedExtensions)
var nonBaselineChanges = parseChanges(changeType, nonBaselineFiles, this.tableChangeParser, schema, sourceEncoding)
val nonBaselineChangeMap = nonBaselineChanges.groupBy { it.dbObjectKey }
if (useBaseline) {
LOG.info("Using the 'useBaseline' mode to read in the db changes")
val baselineFiles = findFiles(tableDir,
if (this.isUsingChangesConvention(tableDir)) CHANGES_WILDCARD_FILTER else baselineFilter, acceptedExtensions)
val baselineChanges = parseChanges(changeType, baselineFiles, this.baselineTableChangeParser, schema, sourceEncoding)
for (baselineChange in baselineChanges) {
val regularChanges = nonBaselineChangeMap.get(baselineChange.dbObjectKey)!!
if (regularChanges.isEmpty()) {
throw IllegalArgumentException("Invalid state - expecting a change here for this object key: " + baselineChange.dbObjectKey)
}
val regularChange = regularChanges.get(0)
this.copyDbObjectMetadataOverToBaseline(regularChange, baselineChange)
}
val baselineDbObjectKeys = baselineChanges.map { it.dbObjectKey }.toSet()
LOG.info("Found the following baseline changes: will try to deploy via baseline for these db objects: " + baselineDbObjectKeys.joinToString(","))
nonBaselineChanges = nonBaselineChanges
.filterNot { baselineDbObjectKeys.contains(it.dbObjectKey) }
.plus(baselineChanges)
}
return nonBaselineChanges
}
/**
* This is for stuff in the METADATA tag that would be in the changes file but not the baseline file
*/
private fun copyDbObjectMetadataOverToBaseline(regularChange: ChangeInput, baselineChange: ChangeInput) {
baselineChange.setRestrictions(regularChange.getRestrictions())
baselineChange.permissionScheme = regularChange.permissionScheme
}
private fun findFiles(dir: FileObject, fileFilter: FileFilter, acceptedExtensions: ImmutableSet<String>): List<FileObject> {
val positiveSelector = BasicFileSelector(
and(
fileFilter,
not(directory()),
not(
or(
WildcardFileFilter("package-info*"),
WildcardFileFilter("*." + OnboardingStrategy.exceptionExtension)
)
)
),
vcsAware()
)
val candidateFiles = listOf(*dir.findFiles(positiveSelector))
val extensionPartition = candidateFiles.partition { acceptedExtensions.contains(it.name.extension.toLowerCase()) }
if (extensionPartition.second.isNotEmpty()) {
val message = "Found unexpected file extensions (these will not be deployed!) in directory " + dir + "; expects extensions [" + acceptedExtensions + "], found: " + extensionPartition.second
LOG.warn(message)
deployMetricsCollector.addListMetric(DeployMetrics.UNEXPECTED_FILE_EXTENSIONS, message)
}
return extensionPartition.first
}
private fun parseChanges(changeType: ChangeType, files: List<FileObject>,
changeParser: DbChangeFileParser, schema: String, sourceEncoding: String): List<ChangeInput> {
return files.flatMap { file ->
val packageMetadata = getPackageMetadata(file, sourceEncoding)
var encoding: String? = null
var metadataSection: TextMarkupDocumentSection? = null
if (packageMetadata != null) {
encoding = packageMetadata.fileToEncodingMap.get(file.name.baseName)
metadataSection = packageMetadata.metadataSection
}
val charsetStrategy = CharsetStrategyFactory.getCharsetStrategy(encoding ?: sourceEncoding)
val objectName = file.name.baseName.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
try {
LOG.debug("Attempting to read file {}", file)
changeParser.value(changeType, file, file.getStringContent(charsetStrategy), objectName, schema, metadataSection).castToList()
} catch (e: RuntimeException) {
throw IllegalArgumentException("Error while parsing file " + file + " of change type " + changeType.name + "; please see the cause in the stack trace below: " + e.message, e)
}
}
}
private fun getPackageMetadata(file: FileObject, sourceEncoding: String): PackageMetadata? {
return packageMetadataCache.getIfAbsentPut(file.parent, Function0<PackageMetadata> {
val packageMetadataFile = file.parent!!.getChild("package-info.txt")
// we check for containsKey, as we may end up persisting null as the value in the map
if (packageMetadataFile == null || !packageMetadataFile.isReadable) {
null
} else {
packageMetadataReader.getPackageMetadata(packageMetadataFile.getStringContent(CharsetStrategyFactory.getCharsetStrategy(sourceEncoding)))
}
})
}
private fun findChanges(changeType: ChangeType, dir: FileObject, changeParser: DbChangeFileParser,
fileFilter: FileFilter, schema: String, acceptedExtensions: ImmutableSet<String>, sourceEncoding: String): List<ChangeInput> {
return parseChanges(changeType, findFiles(dir, fileFilter, acceptedExtensions), changeParser, schema, sourceEncoding)
}
/**
* We have this check here for backwards-compatibility
* Originally, we required the db files to end in .changes.*, but we now want to have the convention of the stard
* file name being the
* file that you edit, much like the other ones
*
* Originally, we wanted to regular name to be for the baseline, but given this is not yet implemented and won't
* drive the changes, this was a wrong idea from the start. Eventually, we will have the baseline files in
* .baseline.*
*/
private fun isUsingChangesConvention(dir: FileObject): Boolean {
val files = dir.findFiles(BasicFileSelector(CHANGES_WILDCARD_FILTER, false))
val changesConventionUsed = files.size > 0
if (changesConventionUsed) {
deployMetricsCollector.addMetric("changesConventionUsed", true)
}
return changesConventionUsed
}
companion object {
private val LOG = LoggerFactory.getLogger(DbDirectoryChangesetReader::class.java)
@VisibleForTesting
@JvmStatic
val CHANGES_WILDCARD_FILTER: FileFilter = WildcardFileFilter("*.changes.*")
}
}
| obevo-core/src/main/java/com/gs/obevo/impl/reader/DbDirectoryChangesetReader.kt | 3323681557 |
package com.izeni.rapidosqlite.util
import android.content.ContentValues
import android.database.Cursor
import com.izeni.rapidosqlite.DataConnection
import com.izeni.rapidosqlite.addAll
import com.izeni.rapidosqlite.get
import com.izeni.rapidosqlite.item_builder.ItemBuilder
import com.izeni.rapidosqlite.query.QueryBuilder
import com.izeni.rapidosqlite.table.Column
import com.izeni.rapidosqlite.table.ParentDataTable
/**
* Created by ner on 2/8/17.
*/
data class Person(val uuid: String, val name: String, val age: Int, val pets: List<Pet>) : ParentDataTable {
companion object {
val TABLE_NAME = "Person"
val UUID = Column(String::class.java, "Uuid", notNull = true, unique = true)
val NAME = Column(String::class.java, "Name", notNull = true)
val AGE = Column(Int::class.java, "Age", notNull = true)
val COLUMNS = arrayOf(UUID, NAME, AGE)
val BUILDER = Builder()
}
override fun tableName() = TABLE_NAME
override fun id() = uuid
override fun idColumn() = UUID
override fun contentValues() = ContentValues().addAll(COLUMNS, uuid, name, age)
override fun getChildren() = pets
class Builder : ItemBuilder<Person> {
override fun buildItem(cursor: Cursor, dataConnection: DataConnection): Person {
val uuid = cursor.get<String>(UUID)
val petQuery = QueryBuilder
.with(Pet.TABLE_NAME)
.whereEquals(Pet.PERSON_UUID, uuid)
.build()
val pets = dataConnection.findAll(Pet.BUILDER, petQuery)
return Person(uuid, cursor.get(NAME), cursor.get(AGE), pets)
}
}
} | rapidosqlite/src/androidTest/java/com/izeni/rapidosqlite/util/Person.kt | 839558106 |
package furhatos.app.quiz.questions
/**
* The questions are structured like
* -The question
* -The correct answer, followed by alternative pronounciations
* -A list of other answers followed by their alternatives
*/
val questionsEnglish = mutableListOf(
Question("How many wives did Henry VIII have?",
answer = listOf("6"),
alternatives = listOf(listOf("5"), listOf("8"), listOf("4"))),
Question("Which country won the 2016 Eurovision Song competition?",
answer = listOf("Ukraine"),
alternatives = listOf(listOf("Sweden"), listOf("France"), listOf("Finland"))),
Question("When was the first circumnavigation of the world completed?",
answer = listOf("15 22", "1522"),
alternatives = listOf(listOf("14 99", "1499"), listOf("16 32", "1632"), listOf("15 78", "1578"))),
Question("Which language is Afrikaans derived from?",
answer = listOf("Dutch", "touch"),
alternatives = listOf(listOf("German"), listOf("Spanish"), listOf("English"))),
Question("The Strip is a famous street in which American city?",
answer = listOf("Las Vegas", "vegas"),
alternatives = listOf(listOf("Washington DC", "washington"), listOf("Los Angeles", "hollywood", "angeles", "la"), listOf("New York", "York", "New"))),
Question("During which decade did Elvis Presley die?",
answer = listOf("70s", "seventies", "70"),
alternatives = listOf(listOf("50s", "fifties", "50"), listOf("60s", "sixties", "60"), listOf("80s", "eighties", "hades", "80"))),
Question("As of 2016, which athlete had won the most Olympic medals?",
answer = listOf("Michael Phelps", "Phelps", "Michael"),
alternatives = listOf(listOf("Usain Bolt", "Bolt", "Usain"))),
Question("Who is the author of the Game of Thrones books?",
answer = listOf("George RR Martin", "George Martin", "George", "martin"),
alternatives = listOf(listOf("JK Rowling", "Rowling", "Rolling"), listOf("Suzanne Collins", "Collins", "Suzanne"), listOf("JRR Tolkien", "Tolkien", "Talking"))),
Question("Which nation won the most gold medals at the 2014 Olympics in Brazil?",
answer = listOf("USA", "America"),
alternatives = listOf(listOf("Great Britain", "United Kingdom", "Britain"), listOf("China"), listOf("Russia"))),
Question("What is the largest freshwater lake in the world?",
answer = listOf("Lake Superior", "Superior"),
alternatives = listOf(listOf("Lake Victoria", "Victoria"), listOf("Lake Michigan", "Michigan"), listOf("Great Bear Lake", "Great Bear"), listOf("Lake Ontario", "Ontario"))),
Question("Where can you find the Sea of Tranquility?",
answer = listOf("The moon", "moon"),
alternatives = listOf(listOf("Turkey"), listOf("Germany"), listOf("The united states", "united states", "states"))),
Question("What is the seventh planet from the Sun?",
answer = listOf("Uranus", "anus"),
alternatives = listOf(listOf("Pluto"), listOf("Neptune", "tune"), listOf("Saturn"))),
Question("In what year did, ABBA, win the Eurovision songfestival?",
answer = listOf("19 74", "1974", "74"),
alternatives = listOf(listOf("19 78", "1978", "78"), listOf("19 76", "1976", "76"), listOf("19 72", "1972", "72"))),
Question("What is the title of the famous novel by George Orwell?",
answer = listOf("19 84", "1984"),
alternatives = listOf(listOf("The lord of the rings", "lord of the rings", "the rings"), listOf("The Great Gatsby", "great gatsby", "the great", "gatsby"), listOf("Of mice and men", "mice and men"))),
Question("Chardonnay. Malaga. and Merlot. are all types of which fruit?",
answer = listOf("Grape", "grapes"),
alternatives = listOf(listOf("Berry", "berries"), listOf("Melon", "Melons"), listOf("Stone fruit", "stone"))),
Question("What did the Wright Brothers invent in 19 02?",
answer = listOf("Airplane", "aeroplane", "plane"),
alternatives = listOf(listOf("car", "cars", "automobile"), listOf("motorbike", "motor", "bike"), listOf("Fighter jet", "jet", "fighter"))),
Question("Who was the first man on the moon?",
answer = listOf("Neil Armstrong", "Armstrong", "Neil"),
alternatives = listOf(listOf("Buzz Aldrin", "Buzz", "Aldrin"), listOf("Michael Collins", "Michael", "Collins"), listOf("Yuri Gagarin", "Yuri", "Gagarin"))),
Question("Which country has more inhabitants?",
answer = listOf("Sweden", "Swedish"),
alternatives = listOf(listOf("Switzerland", "Swiss"))),
Question("Which volcano erupted in 1906 and devastated Naples?",
answer = listOf("Mount Vesuvius", "Vesuvius"),
alternatives = listOf(listOf("Etna"), listOf("Fuji"), listOf("Krakatoa"))),
Question("Which famous tennis player is from Sweden?",
answer = listOf("Bjorn Borg", "Borg", "Bjorn"),
alternatives = listOf(listOf("Roger Federer", "Federer", "Roger"), listOf("Novak Djokovic", "Novak", "Djokovic"), listOf("Andy Murray", "Andy", "Murray")))
) | Quiz/src/main/kotlin/furhatos/app/quiz/questions/questionlist.kt | 2852434851 |
package de.maxvogler.learningspaces.fragments
import android.support.test.InstrumentationRegistry
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.assertion.ViewAssertions.doesNotExist
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.withText
import android.support.test.runner.AndroidJUnit4
import android.test.ActivityInstrumentationTestCase2
import com.google.android.gms.maps.model.LatLng
import com.squareup.otto.Bus
import com.squareup.otto.Subscribe
import com.squareup.otto.ThreadEnforcer
import de.maxvogler.learningspaces.activities.MainActivity
import de.maxvogler.learningspaces.events.LocationFocusChangeEvent
import de.maxvogler.learningspaces.events.RequestLocationsEvent
import de.maxvogler.learningspaces.events.UpdateLocationsEvent
import de.maxvogler.learningspaces.models.FreeSeatMeasurement
import de.maxvogler.learningspaces.models.Location
import de.maxvogler.learningspaces.models.OpeningHourPair
import de.maxvogler.learningspaces.models.Weekday
import de.maxvogler.learningspaces.services.BusProvider
import de.maxvogler.learningspaces.services.LocationService
import de.maxvogler.learningspaces.services.RememberSelectedLocationService
import org.hamcrest.Matchers.notNullValue
import org.joda.time.LocalDateTime
import org.joda.time.LocalTime
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
public class InfoFragmentTest : ActivityInstrumentationTestCase2<MainActivity>(MainActivity::class.java) {
val locationService = object : LocationService() {
init {
val location = makeLocation()
lastResults = mapOf(location.id to location)
}
@Subscribe
override public fun onRequestLocations(e: RequestLocationsEvent)
= bus.post(UpdateLocationsEvent(lastResults))
override fun getLocations(): Map<String, Location>
= lastResults
override fun getLocations(json: String): Map<String, Location>
= lastResults
}
@Before
public override fun setUp() {
super.setUp()
injectInstrumentation(InstrumentationRegistry.getInstrumentation())
BusProvider.instance = Bus(ThreadEnforcer.ANY)
BusProvider.instance.register(locationService)
BusProvider.instance.register(RememberSelectedLocationService())
activity
}
@Test
public fun showsData() {
runOnMainSync {
BusProvider.instance.post(LocationFocusChangeEvent(makeLocation()))
}
assertTextDisplayed("Testgebäude")
assertTextDisplayed("100 Lernplätze insgesamt")
assertTextDisplayed("42 frei")
assertTextDisplayed("58 besetzt")
}
@Test
public fun updatesData() {
showsData()
setLocationFreeSeats("TEST", 43)
runOnMainSync {
BusProvider.instance.post(UpdateLocationsEvent(locationService.getLocations()))
}
assertTextDisplayed("100 Lernplätze insgesamt")
onView(withText("42 frei")) check doesNotExist()
assertTextDisplayed("43 frei")
assertTextDisplayed("57 besetzt")
}
@Test
public fun updatesDataWhenReloaded() {
showsData()
setLocationFreeSeats("TEST", 43)
runOnMainSync {
instrumentation.callActivityOnPause(activity);
instrumentation.callActivityOnStop(activity);
instrumentation.callActivityOnRestart(activity);
instrumentation.callActivityOnStart(activity);
instrumentation.callActivityOnResume(activity);
}
instrumentation.waitForIdleSync()
assertTextDisplayed("Testgebäude")
assertTextDisplayed("100 Lernplätze insgesamt")
assertTextDisplayed("43 frei")
assertTextDisplayed("57 besetzt")
}
protected fun assertTextDisplayed(text: String) {
onView(withText(text)) check matches(notNullValue())
}
protected fun runOnMainSync(task: () -> Unit) {
InstrumentationRegistry.getInstrumentation().runOnMainSync(task)
}
protected fun makeLocation(): Location {
val location = Location("TEST")
location.name = "Testgebäude"
location.coordinates = LatLng(0.0, 0.0)
location.measurements.add(FreeSeatMeasurement(LocalDateTime.now(), 42))
location.totalSeats = 100
location.openingHours.add(OpeningHourPair(Weekday.MONDAY, LocalTime(0, 0, 0), LocalTime(23, 59, 59)))
return location
}
protected fun setLocationFreeSeats(id: String, freeSeats: Int) {
val testLocation = locationService.getLocations().get(id)!!
testLocation.measurements.clear()
testLocation.measurements.add(FreeSeatMeasurement(LocalDateTime.now(), freeSeats))
}
} | app/src/androidTest/java/de/maxvogler/learningspaces/fragments/InfoFragmentTest.kt | 419253443 |
package com.sampsonjoliver.firestarter.views.dialogs
import android.app.DatePickerDialog
import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.support.v4.app.DialogFragment
import java.util.*
class DatePickerDialogFragment : DialogFragment() {
companion object {
const val ARG_YEAR = "ARG_YEAR"
const val ARG_MONTH = "ARG_MONTH"
const val ARG_DAY = "ARG_DAY"
const val ARG_MIN_DATE = "ARG_MIN_DATE"
fun newInstance(year: Int, month: Int, day: Int): DatePickerDialogFragment {
return DatePickerDialogFragment().apply {
arguments = Bundle(3)
arguments.putInt(ARG_YEAR, year)
arguments.putInt(ARG_MONTH, month)
arguments.putInt(ARG_DAY, day)
}
}
fun newInstance(year: Int, month: Int, day: Int, minDate: Date): DatePickerDialogFragment {
return DatePickerDialogFragment().apply {
arguments = Bundle(4)
arguments.putInt(ARG_YEAR, year)
arguments.putInt(ARG_MONTH, month)
arguments.putInt(ARG_DAY, day)
arguments.putSerializable(ARG_MIN_DATE, minDate)
}
}
}
var listener: DatePickerDialog.OnDateSetListener? = null
private val year by lazy { arguments.getInt(ARG_YEAR) }
private val month by lazy { arguments.getInt(ARG_MONTH) }
private val day by lazy { arguments.getInt(ARG_DAY) }
private val minDate by lazy { arguments.getSerializable(ARG_MIN_DATE) as Date? }
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val picker = DatePickerDialog(activity, listener, year, month, day)
if (minDate != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
picker.datePicker.minDate = minDate?.time ?: 0L
return picker
}
} | app/src/main/java/com/sampsonjoliver/firestarter/views/dialogs/DatePickerDialogFragment.kt | 2067891374 |
package com.baulsupp.okurl.util
import com.baulsupp.oksocial.output.UsageException
import com.baulsupp.okurl.util.FileUtil.expectedFile
import java.io.File
import java.io.IOException
// TODO handle duplicate header keys
object HeaderUtil {
fun headerMap(headers: List<String>?): Map<String, String> {
val headerMap = mutableMapOf<String, String>()
headers?.forEach {
if (it.startsWith("@")) {
headerMap.putAll(headerFileMap(it))
} else {
val parts = it.split(":".toRegex(), 2).toTypedArray()
// TODO: consider better strategy than simple trim
val name = parts[0].trim { it <= ' ' }
val value = stringValue(parts[1].trim { it <= ' ' })
headerMap[name] = value
}
}
return headerMap.toMap()
}
private fun headerFileMap(input: String): Map<out String, String> {
return try {
headerMap(inputFile(input).readLines())
} catch (ioe: IOException) {
throw UsageException("failed to read header file", ioe)
}
}
fun stringValue(source: String): String {
return if (source.startsWith("@")) {
try {
inputFile(source).readText()
} catch (e: IOException) {
throw UsageException(e.toString())
}
} else {
source
}
}
fun inputFile(path: String): File {
return expectedFile(path.substring(1))
}
}
| src/main/kotlin/com/baulsupp/okurl/util/HeaderUtil.kt | 1678679454 |
package com.baulsupp.okurl.services.coinbase
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor
import com.baulsupp.okurl.authenticator.ValidatedCredentials
import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.completion.ApiCompleter
import com.baulsupp.okurl.completion.BaseUrlCompleter
import com.baulsupp.okurl.completion.CompletionVariableCache
import com.baulsupp.okurl.completion.UrlList
import com.baulsupp.okurl.credentials.CredentialsStore
import com.baulsupp.okurl.credentials.Token
import com.baulsupp.okurl.credentials.TokenValue
import com.baulsupp.okurl.kotlin.query
import com.baulsupp.okurl.kotlin.queryMap
import com.baulsupp.okurl.kotlin.queryMapValue
import com.baulsupp.okurl.kotlin.requestBuilder
import com.baulsupp.okurl.secrets.Secrets
import com.baulsupp.okurl.services.coinbase.model.AccountList
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
class CoinbaseAuthInterceptor : Oauth2AuthInterceptor() {
override val serviceDefinition = Oauth2ServiceDefinition(
"api.coinbase.com", "Coinbase API", "coinbase", "https://developers.coinbase.com/api/v2/",
"https://www.coinbase.com/settings/api"
)
override suspend fun intercept(chain: Interceptor.Chain, credentials: Oauth2Token): Response {
var request = chain.request()
request = request.newBuilder().header("Authorization", "Bearer ${credentials.accessToken}")
.header("CB-VERSION", "2017-12-17").build()
return chain.proceed(request)
}
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): Oauth2Token {
val clientId = Secrets.prompt("Coinbase Client Id", "coinbase.clientId", "", false)
val clientSecret = Secrets.prompt("Coinbase Client Secret", "coinbase.clientSecret", "", true)
val scopes = Secrets.promptArray(
"Scopes", "coinbase.scopes", listOf(
"wallet:accounts:read",
"wallet:addresses:read",
"wallet:buys:read",
"wallet:checkouts:read",
"wallet:deposits:read",
"wallet:notifications:read",
"wallet:orders:read",
"wallet:payment-methods:read",
"wallet:payment-methods:limits",
"wallet:sells:read",
"wallet:transactions:read",
"wallet:user:read",
"wallet:withdrawals:read"
// "wallet:accounts:update",
// "wallet:accounts:create",
// "wallet:accounts:delete",
// "wallet:addresses:create",
// "wallet:buys:create",
// "wallet:checkouts:create",
// "wallet:deposits:create",
// "wallet:orders:create",
// "wallet:orders:refund",
// "wallet:payment-methods:delete",
// "wallet:sells:create",
// "wallet:transactions:send",
// "wallet:transactions:request",
// "wallet:transactions:transfer",
// "wallet:user:update",
// "wallet:user:email",
// "wallet:withdrawals:create"
)
)
return CoinbaseAuthFlow.login(client, outputHandler, clientId, clientSecret, scopes)
}
override suspend fun renew(client: OkHttpClient, credentials: Oauth2Token): Oauth2Token? {
val body = FormBody.Builder()
.add("client_id", credentials.clientId!!)
.add("client_secret", credentials.clientSecret!!)
.add("refresh_token", credentials.refreshToken!!)
.add("grant_type", "refresh_token")
.build()
val request = requestBuilder(
"https://api.coinbase.com/oauth/token",
TokenValue(credentials)
)
.post(body)
.build()
val responseMap = client.queryMap<Any>(request)
// TODO check if refresh token in response?
return Oauth2Token(
responseMap["access_token"] as String,
credentials.refreshToken, credentials.clientId,
credentials.clientSecret
)
}
override suspend fun apiCompleter(
prefix: String,
client: OkHttpClient,
credentialsStore: CredentialsStore,
completionVariableCache: CompletionVariableCache,
tokenSet: Token
): ApiCompleter {
val urlList = UrlList.fromResource(name())
val completer = BaseUrlCompleter(urlList!!, hosts(credentialsStore), completionVariableCache)
completer.withCachedVariable(name(), "account_id") {
credentialsStore.get(serviceDefinition, tokenSet)?.let {
client.query<AccountList>(
"https://api.coinbase.com/v2/accounts",
tokenSet
).data.map { it.id }
}
}
return completer
}
override suspend fun validate(
client: OkHttpClient,
credentials: Oauth2Token
): ValidatedCredentials =
ValidatedCredentials(
client.queryMapValue<String>(
"https://api.coinbase.com/v2/user",
TokenValue(credentials), "data", "name"
)
)
}
| src/main/kotlin/com/baulsupp/okurl/services/coinbase/CoinbaseAuthInterceptor.kt | 384916668 |
package com.koenv.adventofcode
class Day19(input: CharSequence) {
private val replacements: Map<String, List<String>>
private val lexer: Lexer
init {
this.replacements = input.lines().map {
val parts = it.split(" => ")
parts[0] to parts[1]
}.groupBy { it.first }.mapValues {
it.value.map {
it.second
}
}
this.lexer = Lexer(replacements.keys.distinct().toList())
}
public fun parse(input: String): List<Lexer.Token> {
return lexer.parse(input)
}
public fun getPossibilities(input: String): List<String> {
val tokens = parse(input)
val possibilities = arrayListOf<String>()
tokens.filter { it.type == Lexer.TokenType.REPLACEMENT }.forEach { token ->
replacements[token.text]!!.forEach { replacement ->
val text = StringBuilder()
tokens.forEach {
if (it == token) {
text.append(replacement)
} else {
text.append(it.text)
}
}
possibilities.add(text.toString())
}
}
return possibilities.distinct()
}
public fun fromElectronTo(input: String): Int {
var target = input
var steps = 0
while (target != "e") {
replacements.forEach { entry ->
entry.value.forEach {
if (target.contains(it)) {
target = target.substring(0, target.lastIndexOf(it)) + entry.key + target.substring(target.lastIndexOf(it) + it.length)
steps++
}
}
}
}
return steps
}
class Lexer(private val replacementPossibilities: List<String>) {
private var replacementMaxLength: Int
init {
this.replacementMaxLength = replacementPossibilities.map { it.length }.max()!!
}
public fun parse(input: String): List<Token> {
val tokens = arrayListOf<Token>()
var position = 0
while (position < input.length) {
var nowPosition = position
val it = StringBuilder()
it.append(input[position])
nowPosition++
while (!replacementPossibilities.contains(it.toString()) && it.length < replacementMaxLength && nowPosition < input.length) {
it.append(input[nowPosition])
nowPosition++
}
if (replacementPossibilities.contains(it.toString())) {
tokens.add(Token(position, TokenType.REPLACEMENT, it.toString()))
position = nowPosition
} else {
tokens.add(Token(position, TokenType.TEXT, input[position].toString()))
position++
}
}
return tokens
}
data class Token(val position: Int, val type: TokenType, val text: String)
enum class TokenType {
TEXT,
REPLACEMENT
}
}
} | 2015/src/main/kotlin/com/koenv/adventofcode/Day19.kt | 750675230 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Looker Data Sciences, Inc.
*
* 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.looker.rtl
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
@Suppress("UNCHECKED_CAST")
open class APIMethods(val authSession: AuthSession) {
val authRequest = authSession::authenticate
fun <T> ok(response: SDKResponse): T {
when (response) {
is SDKResponse.SDKErrorResponse<*> -> throw Error(response.value.toString())
is SDKResponse.SDKSuccessResponse<*> -> return response.value as T
else -> throw Error("Fail!!")
}
}
inline fun <reified T> get(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse {
return authSession.transport.request<T>(HttpMethod.GET, path, queryParams, body, authRequest)
}
inline fun <reified T> head(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse {
return authSession.transport.request<T>(HttpMethod.HEAD, path, queryParams, body, authRequest)
}
inline fun <reified T> delete(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse {
return authSession.transport.request<T>(HttpMethod.DELETE, path, queryParams, body, authRequest)
}
inline fun <reified T> post(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse {
return authSession.transport.request<T>(HttpMethod.POST, path, queryParams, body, authRequest)
}
inline fun <reified T> put(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse {
return authSession.transport.request<T>(HttpMethod.PUT, path, queryParams, body, authRequest)
}
inline fun <reified T> patch(path: String, queryParams: Values = mapOf(), body: Any? = null): SDKResponse {
return authSession.transport.request<T>(HttpMethod.PATCH, path, queryParams, body, authRequest)
}
fun encodeURI(value: String): String {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.toString())
} catch (ex: UnsupportedEncodingException) {
throw RuntimeException(ex.cause)
}
}
}
| kotlin/src/main/com/looker/rtl/APIMethods.kt | 1695533072 |
package me.gurpreetsk.rxoperators.ui.filtering
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_filtering_operators.*
import me.gurpreetsk.rxoperators.R
class FilteringOperatorsActivity : AppCompatActivity() {
private val TAG = FilteringOperatorsActivity::class.java.simpleName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_filtering_operators)
title = TAG
setupButtons()
}
private fun setupButtons() {
buttonDistinct.setOnClickListener({
startActivity(Intent(FilteringOperatorsActivity@this, DistinctOperatorActivity::class.java))
})
// buttonDistinctUntilChanged.setOnClickListener({
// startActivity(Intent(FilteringOperatorsActivity@this, DistinctUntilChangedOperatorActivity::class.java))
// })
// buttonDebounce.setOnClickListener({
// startActivity(Intent(FilteringOperatorsActivity@this, DistinctOperatorActivity::class.java))
// })
// buttonThrottle.setOnClickListener({
// startActivity(Intent(FilteringOperatorsActivity@this, DistinctOperatorActivity::class.java))
// })
// buttonTakeUntil.setOnClickListener({
// startActivity(Intent(FilteringOperatorsActivity@this, DistinctOperatorActivity::class.java))
// })
// buttonFilter.setOnClickListener({
// startActivity(Intent(FilteringOperatorsActivity@this, DistinctOperatorActivity::class.java))
// })
// buttonFirst.setOnClickListener({
// startActivity(Intent(FilteringOperatorsActivity@this, DistinctOperatorActivity::class.java))
// })
}
}
| RxOperators/app/src/main/kotlin/me/gurpreetsk/rxoperators/ui/filtering/FilteringOperatorsActivity.kt | 4211590040 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza
*
* 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.mallowigi.icons.patchers
import com.intellij.util.xmlb.annotations.Property
import com.thoughtworks.xstream.annotations.XStreamAsAttribute
/** External icons patcher. */
@Suppress("UnusedPrivateMember")
open class ExternalIconsPatcher : AbstractIconPatcher() {
@Property
@XStreamAsAttribute
private val append: String = ""
@Property
@XStreamAsAttribute
private val name: String = ""
@Property
@XStreamAsAttribute
private val remove: String = ""
override val pathToAppend: String
get() = append
override val pathToRemove: String
get() = remove
}
| common/src/main/java/com/mallowigi/icons/patchers/ExternalIconsPatcher.kt | 3498489965 |
package net.halawata.artich.model.mute
import android.database.sqlite.SQLiteOpenHelper
import net.halawata.artich.enum.Media
class MediaMuteFactory {
companion object {
fun create(mediaType: Media, helper: SQLiteOpenHelper): MediaMuteInterface =
when (mediaType) {
Media.COMMON -> CommonMute(helper)
Media.HATENA -> HatenaMute(helper)
Media.QIITA -> QiitaMute(helper)
Media.GNEWS -> GNewsMute(helper)
}
}
}
| app/src/main/java/net/halawata/artich/model/mute/MediaMuteFactory.kt | 250692357 |
package elite.oa.road
/**
*
* @author CFerg (Elite)
*/
class Road
/**
*
* @param type
*/
(internal var type: Roads) | ObjectAvoidance/kotlin/src/elite/oa/road/Road.kt | 1901916188 |
package com.wenhaiz.himusic.data
import android.content.Context
import com.wenhaiz.himusic.data.bean.Album
import com.wenhaiz.himusic.data.bean.Artist
import com.wenhaiz.himusic.data.bean.Collect
import com.wenhaiz.himusic.data.bean.Song
import com.wenhaiz.himusic.data.onlineprovider.Xiami
import com.wenhaiz.himusic.http.data.RankList
internal class MusicRepository(context: Context) : MusicSource {
private var musicSource: MusicSource
private var curProvider: MusicProvider
companion object {
@JvmStatic
var INSTANCE: MusicRepository? = null
@JvmStatic
fun getInstance(context: Context): MusicRepository {
if (INSTANCE == null) {
synchronized(MusicRepository::class.java) {
if (INSTANCE == null) {
INSTANCE = MusicRepository(context)
}
}
}
return INSTANCE!!
}
}
init {
//default
curProvider = MusicProvider.XIAMI
musicSource = Xiami(context)
}
constructor(sourceProvider: MusicProvider, context: Context) : this(context) {
curProvider = sourceProvider
when (sourceProvider) {
MusicProvider.XIAMI -> {
musicSource = Xiami(context)
}
MusicProvider.QQMUSIC -> {
// musicSource = QQ()
}
MusicProvider.NETEASE -> {
// musicSource = NetEase()
}
}
}
fun changeMusicSource(provider: MusicProvider, context: Context) {
if (provider != curProvider) {
when (provider) {
MusicProvider.XIAMI -> {
musicSource = Xiami(context)
}
MusicProvider.QQMUSIC -> {
// musicSource = QQ()
}
MusicProvider.NETEASE -> {
// musicSource = NetEase()
}
}
}
}
override fun loadSearchTips(keyword: String, callback: LoadSearchTipsCallback) {
musicSource.loadSearchTips(keyword, callback)
}
override fun searchByKeyword(keyword: String, callback: LoadSearchResultCallback) {
musicSource.searchByKeyword(keyword, callback)
}
override fun loadCollectDetail(collect: Collect, callback: LoadCollectDetailCallback) {
musicSource.loadCollectDetail(collect, callback)
}
override fun loadAlbumDetail(album: Album, callback: LoadAlbumDetailCallback) {
musicSource.loadAlbumDetail(album, callback)
}
override fun loadSongDetail(song: Song, callback: LoadSongDetailCallback) {
musicSource.loadSongDetail(song, callback)
}
override fun loadHotCollect(page: Int, callback: LoadCollectCallback) {
musicSource.loadHotCollect(page, callback)
}
override fun loadNewAlbum(page: Int, callback: LoadAlbumCallback) {
musicSource.loadNewAlbum(page, callback)
}
override fun loadArtistDetail(artist: Artist, callback: LoadArtistDetailCallback) {
musicSource.loadArtistDetail(artist, callback)
}
override fun loadArtistHotSongs(artist: Artist, page: Int, callback: LoadArtistHotSongsCallback) {
musicSource.loadArtistHotSongs(artist, page, callback)
}
override fun loadArtistAlbums(artist: Artist, page: Int, callback: LoadArtistAlbumsCallback) {
musicSource.loadArtistAlbums(artist, page, callback)
}
override fun loadCollectByCategory(category: String, page: Int, callback: LoadCollectByCategoryCallback) {
musicSource.loadCollectByCategory(category, page, callback)
}
override fun loadRankingList(callback: LoadRankingCallback) {
musicSource.loadRankingList(callback)
}
override fun loadRankingDetail(rank: RankList.Rank, callback: LoadRankingDetailCallback) {
musicSource.loadRankingDetail(rank, callback)
}
}
| app/src/main/java/com/wenhaiz/himusic/data/MusicRepository.kt | 3906278221 |
package com.senorsen.wukong.store
import android.content.Context
import com.senorsen.wukong.model.Configuration
class ConfigurationLocalStore(context: Context) : PrefLocalStore(context) {
fun save(configuration: Configuration?) {
if (configuration != null) {
pref.edit()
.putString(KEY_PREF_COOKIES, configuration.cookies)
.putString(KEY_PREF_SYNC_PLAYLISTS, configuration.syncPlaylists)
.apply()
}
}
fun load(): Configuration {
return Configuration(
cookies = pref.getString(KEY_PREF_COOKIES, ""),
syncPlaylists = pref.getString(KEY_PREF_SYNC_PLAYLISTS, ""))
}
companion object {
private val KEY_PREF_COOKIES = "pref_cookies"
private val KEY_PREF_SYNC_PLAYLISTS = "pref_syncPlaylists"
}
} | wukong/src/main/java/com/senorsen/wukong/store/ConfigurationLocalStore.kt | 647720020 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsFormatMacroArgument
import org.rust.lang.core.psi.RsMacroCall
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.macroName
/**
* Replace `println!("")` with `println!()` available since Rust 1.14.0
*/
class RsSimplifyPrintInspection : RsLocalInspectionTool() {
override fun getDisplayName() = "println!(\"\") usage"
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() {
override fun visitMacroCall(o: RsMacroCall) {
val macroName = o.macroName
val formatMacroArg = o.formatMacroArgument ?: return
if (!(macroName.endsWith("println"))) return
if (emptyStringArg(formatMacroArg) == null) return
holder.registerProblem(
o,
"println! macro invocation can be simplified",
object : LocalQuickFix {
override fun getName() = "Remove unnecessary argument"
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val macro = descriptor.psiElement as RsMacroCall
val arg = emptyStringArg(macro.formatMacroArgument!!) ?: return
arg.delete()
}
}
)
}
}
private fun emptyStringArg(arg: RsFormatMacroArgument): PsiElement? {
val singeArg = arg.formatMacroArgList.singleOrNull() ?: return null
if (singeArg.text != "\"\"") return null
return singeArg
}
}
| src/main/kotlin/org/rust/ide/inspections/RsSimplifyPrintInspection.kt | 1852382874 |
package com.zhuinden.simplestackbottomnavfragmentexample.features.root.second
import androidx.fragment.app.Fragment
import com.zhuinden.simplestackextensions.fragments.DefaultFragmentKey
import kotlinx.parcelize.Parcelize
@Parcelize
class SecondScreen : DefaultFragmentKey() {
override fun instantiateFragment(): Fragment = SecondFragment()
} | samples/multistack-samples/simple-stack-example-multistack-nested-fragment/src/main/java/com/zhuinden/simplestackbottomnavfragmentexample/features/root/second/SecondScreen.kt | 21563516 |
package com.inverse.unofficial.proxertv.model
import com.google.gson.annotations.SerializedName
import nz.bradcampbell.paperparcel.PaperParcel
import nz.bradcampbell.paperparcel.PaperParcelable
@PaperParcel
data class Episode(
@SerializedName("no")
val episodeNum: Int,
@SerializedName("typ")
val languageType: String) : PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelable.Creator(Episode::class.java)
}
} | app/src/main/java/com/inverse/unofficial/proxertv/model/Episode.kt | 810653806 |
package com.eden.orchid.javadoc.menu
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.theme.menus.OrchidMenuFactory
import com.eden.orchid.api.theme.menus.MenuItem
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.javadoc.models.JavadocModel
import java.util.ArrayList
import javax.inject.Inject
@Description("All Javadoc class pages.", name = "Javadoc Classes")
class AllClassesMenuItemType
@Inject
constructor(
context: OrchidContext,
private val model: JavadocModel
) : OrchidMenuFactory(context, "javadocClasses", 100) {
@Option
@StringDefault("All Classes")
lateinit var title: String
override fun getMenuItems(): List<MenuItem> {
val items = ArrayList<MenuItem>()
val pages = ArrayList<OrchidPage>(model.allClasses)
pages.sortBy { it.title }
items.add(MenuItem.Builder(context)
.title(title)
.pages(pages)
.build()
)
return items
}
}
| plugins/OrchidJavadoc/src/main/kotlin/com/eden/orchid/javadoc/menu/AllClassesMenuItemType.kt | 342951779 |
package com.artfable.telegram.api
/**
* @author aveselov
* @since 05/08/2020
*/
class TelegramServerException: RuntimeException {
constructor() : super()
constructor(message: String?) : super(message)
constructor(message: String?, cause: Throwable?) : super(message, cause)
constructor(cause: Throwable?) : super(cause)
} | src/main/kotlin/com/artfable/telegram/api/TelegramServerException.kt | 3774871081 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.ide.highlighter.WorkspaceFileType
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.impl.ServiceManagerImpl
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ModuleManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCoreUtil
import com.intellij.openapi.project.ex.ProjectNameProvider
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification
import com.intellij.openapi.project.impl.ProjectStoreClassProvider
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.ReadonlyStatusHandler
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtilRt
import com.intellij.util.SmartList
import com.intellij.util.attribute
import com.intellij.util.containers.computeIfAny
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.io.*
import com.intellij.util.isEmpty
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.text.nullize
import gnu.trove.THashSet
import org.jdom.Element
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
const val PROJECT_FILE = "\$PROJECT_FILE$"
const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$"
val IProjectStore.nameFile: Path
get() = Paths.get(directoryStorePath, ProjectImpl.NAME_FILE)
internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false)
internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true)
abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreImpl(), IProjectStore {
// protected setter used in upsource
// Zelix KlassMaster - ERROR: Could not find method 'getScheme()'
var scheme = StorageScheme.DEFAULT
override final var loadPolicy = StateLoadPolicy.LOAD
override final fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD
override final fun getStorageScheme() = scheme
override abstract val storageManager: StateStorageManagerImpl
protected val isDirectoryBased: Boolean
get() = scheme == StorageScheme.DIRECTORY_BASED
override final fun setOptimiseTestLoadSpeed(value: Boolean) {
// we don't load default state in tests as app store does because
// 1) we should not do it
// 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations)
loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD
}
override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE)
override final fun getWorkspaceFilePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE)
override final fun clearStorages() {
storageManager.clearStorages()
}
override final fun loadProjectFromTemplate(defaultProject: Project) {
defaultProject.save()
val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return
LOG.runAndLogException {
normalizeDefaultProjectElement(defaultProject, element, if (isDirectoryBased) Paths.get(storageManager.expandMacro(PROJECT_CONFIG_DIR)) else null)
}
(storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element)
}
override final fun getProjectBasePath(): String {
if (isDirectoryBased) {
val path = PathUtilRt.getParentPath(storageManager.expandMacro(PROJECT_CONFIG_DIR))
if (Registry.`is`("store.basedir.parent.detection", true) && PathUtilRt.getFileName(path).startsWith("${Project.DIRECTORY_STORE_FOLDER}.")) {
return PathUtilRt.getParentPath(PathUtilRt.getParentPath(path))
}
return path
}
else {
return PathUtilRt.getParentPath(projectFilePath)
}
}
// used in upsource
protected fun setPath(filePath: String, refreshVfs: Boolean, useOldWorkspaceContentIfExists: Boolean) {
val storageManager = storageManager
val fs = LocalFileSystem.getInstance()
if (filePath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
scheme = StorageScheme.DEFAULT
storageManager.addMacro(PROJECT_FILE, filePath)
val workspacePath = composeWsPath(filePath)
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath)
if (refreshVfs) {
invokeAndWaitIfNeed {
VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath))
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !File(filePath).exists()
}
}
else {
scheme = StorageScheme.DIRECTORY_BASED
// if useOldWorkspaceContentIfExists false, so, file path is expected to be correct (we must avoid file io operations)
val isDir = !useOldWorkspaceContentIfExists || Paths.get(filePath).isDirectory()
val configDir = "${(if (isDir) filePath else PathUtilRt.getParentPath(filePath))}/${Project.DIRECTORY_STORE_FOLDER}"
storageManager.addMacro(PROJECT_CONFIG_DIR, configDir)
storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml")
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml")
if (!isDir) {
val workspace = File(workspaceFilePath)
if (!workspace.exists()) {
useOldWorkspaceContent(filePath, workspace)
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !Paths.get(filePath).exists()
}
if (refreshVfs) {
invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) }
}
}
}
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
if (storages.isEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
if (isDirectoryBased) {
var result: MutableList<Storage>? = null
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path != PROJECT_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
result!!.sortWith(deprecatedComparator)
// if we create project from default, component state written not to own storage file, but to project file,
// we don't have time to fix it properly, so, ancient hack restored
result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION)
return result
}
}
else {
var result: MutableList<Storage>? = null
// FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry
var hasOnlyDeprecatedStorages = true
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
if (!storage.deprecated) {
hasOnlyDeprecatedStorages = false
}
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
if (hasOnlyDeprecatedStorages) {
result!!.add(PROJECT_FILE_STORAGE_ANNOTATION)
}
result!!.sortWith(deprecatedComparator)
return result
}
}
}
override fun isProjectFile(file: VirtualFile): Boolean {
if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file, file.fileType)) {
return false
}
val filePath = file.path
if (!isDirectoryBased) {
return filePath == projectFilePath || filePath == workspaceFilePath
}
return FileUtil.isAncestor(PathUtilRt.getParentPath(projectFilePath), filePath, false)
}
override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = if (!ignoreProjectStorageScheme && !isDirectoryBased) null else PathUtilRt.getParentPath(projectFilePath).nullize()
override fun getDirectoryStoreFile() = directoryStorePath?.let { LocalFileSystem.getInstance().findFileByPath(it) }
override fun getDirectoryStorePathOrBase() = PathUtilRt.getParentPath(projectFilePath)
}
private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) {
private var lastSavedProjectName: String? = null
init {
assert(!project.isDefault)
}
override final fun getPathMacroManagerForDefaults() = pathMacroManager
override val storageManager = ProjectStateStorageManager(pathMacroManager.createTrackingSubstitutor(), project)
override fun setPath(filePath: String) {
setPath(filePath, true, true)
}
override fun getProjectName(): String {
if (!isDirectoryBased) {
return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
val baseDir = projectBasePath
val nameFile = nameFile
if (nameFile.exists()) {
LOG.runAndLogException {
nameFile.inputStream().reader().useLines { it.firstOrNull { !it.isEmpty() }?.trim() }?.let {
lastSavedProjectName = it
return it
}
}
}
return ProjectNameProvider.EP_NAME.extensions.computeIfAny {
LOG.runAndLogException { it.getDefaultName(project) }
} ?: PathUtilRt.getFileName(baseDir).replace(":", "")
}
private fun saveProjectName() {
if (!isDirectoryBased) {
return
}
val currentProjectName = project.name
if (lastSavedProjectName == currentProjectName) {
return
}
lastSavedProjectName = currentProjectName
val basePath = projectBasePath
if (currentProjectName == PathUtilRt.getFileName(basePath)) {
// name equals to base path name - just remove name
nameFile.delete()
}
else {
if (Paths.get(basePath).isDirectory()) {
nameFile.write(currentProjectName.toByteArray())
}
}
}
override fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<Pair<SaveSession, VirtualFile>>, prevErrors: MutableList<Throwable>?): MutableList<Throwable>? {
try {
saveProjectName()
}
catch (e: Throwable) {
LOG.error("Unable to store project name", e)
}
var errors = prevErrors
beforeSave(readonlyFiles)
errors = super.doSave(saveSessions, readonlyFiles, errors)
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (readonlyFiles.isEmpty()) {
for (notification in notifications) {
notification.expire()
}
return errors
}
if (!notifications.isEmpty()) {
throw IComponentStore.SaveCancelledException()
}
val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) }
if (status.hasReadonlyFiles()) {
dropUnableToSaveProjectNotification(project, status.readonlyFiles)
throw IComponentStore.SaveCancelledException()
}
val oldList = readonlyFiles.toTypedArray()
readonlyFiles.clear()
for (entry in oldList) {
errors = executeSave(entry.first, readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
if (!readonlyFiles.isEmpty()) {
dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles))
throw IComponentStore.SaveCancelledException()
}
return errors
}
protected open fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
}
}
private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) {
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (notifications.isEmpty()) {
Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project)
}
else {
notifications[0].myFiles = readOnlyFiles
}
}
private fun getFilesList(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) = Array(readonlyFiles.size) { readonlyFiles[it].second }
private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) {
override fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
super.beforeSave(readonlyFiles)
for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) {
module.stateStore.save(readonlyFiles)
}
}
}
// used in upsource
class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java
}
}
private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java
}
}
private fun composeWsPath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}"
private fun useOldWorkspaceContent(filePath: String, ws: File) {
val oldWs = File(composeWsPath(filePath))
if (!oldWs.exists()) {
return
}
try {
FileUtil.copyContent(oldWs, ws)
}
catch (e: IOException) {
LOG.error(e)
}
}
private fun removeWorkspaceComponentConfiguration(defaultProject: Project, element: Element) {
val componentElements = element.getChildren("component")
if (componentElements.isEmpty()) {
return
}
val workspaceComponentNames = THashSet(listOf("GradleLocalSettings"))
@Suppress("DEPRECATION")
val projectComponents = defaultProject.getComponents(PersistentStateComponent::class.java)
projectComponents.forEachGuaranteed {
getNameIfWorkspaceStorage(it.javaClass)?.let {
workspaceComponentNames.add(it)
}
}
ServiceManagerImpl.processAllImplementationClasses(defaultProject as ProjectImpl) { aClass, pluginDescriptor ->
getNameIfWorkspaceStorage(aClass)?.let {
workspaceComponentNames.add(it)
}
true
}
val iterator = componentElements.iterator()
for (componentElement in iterator) {
val name = componentElement.getAttributeValue("name") ?: continue
if (workspaceComponentNames.contains(name)) {
iterator.remove()
}
}
return
}
// public only to test
fun normalizeDefaultProjectElement(defaultProject: Project, element: Element, projectConfigDir: Path?) {
LOG.runAndLogException {
removeWorkspaceComponentConfiguration(defaultProject, element)
}
if (projectConfigDir == null) {
return
}
LOG.runAndLogException {
val iterator = element.getChildren("component").iterator()
for (component in iterator) {
val componentName = component.getAttributeValue("name")
fun writeProfileSettings(schemeDir: Path) {
component.removeAttribute("name")
if (!component.isEmpty()) {
val wrapper = Element("component").attribute("name", componentName)
component.name = "settings"
wrapper.addContent(component)
JDOMUtil.write(wrapper, schemeDir.resolve("profiles_settings.xml").outputStream(), "\n")
}
}
when (componentName) {
"InspectionProjectProfileManager" -> {
iterator.remove()
val schemeDir = projectConfigDir.resolve("inspectionProfiles")
convertProfiles(component.getChildren("profile").iterator(), componentName, schemeDir)
component.removeChild("version")
writeProfileSettings(schemeDir)
}
"CopyrightManager" -> {
iterator.remove()
val schemeDir = projectConfigDir.resolve("copyright")
convertProfiles(component.getChildren("copyright").iterator(), componentName, schemeDir)
writeProfileSettings(schemeDir)
}
ModuleManagerImpl.COMPONENT_NAME -> {
iterator.remove()
}
}
}
}
}
private fun convertProfiles(profileIterator: MutableIterator<Element>, componentName: String, schemeDir: Path) {
for (profile in profileIterator) {
val schemeName = profile.getChildren("option").find { it.getAttributeValue("name") == "myName" }?.getAttributeValue("value") ?: continue
profileIterator.remove()
val wrapper = Element("component").attribute("name", componentName)
wrapper.addContent(profile)
val path = schemeDir.resolve("${FileUtil.sanitizeFileName(schemeName, true)}.xml")
JDOMUtil.write(wrapper, path.outputStream(), "\n")
}
}
private fun getNameIfWorkspaceStorage(aClass: Class<*>): String? {
val stateAnnotation = StoreUtil.getStateSpec(aClass)
if (stateAnnotation == null || stateAnnotation.name.isNullOrEmpty()) {
return null
}
val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return null
return if (storage.path == StoragePathMacros.WORKSPACE_FILE) stateAnnotation.name else null
} | platform/configuration-store-impl/src/ProjectStoreImpl.kt | 1222770946 |
/*
* MIT License
*
* Copyright (c) 2019 emufog contributors
*
* 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 emufog.graph
import emufog.container.DeviceContainer
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNotEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
internal class ASTest {
private val defaultSystem = AS(0)
@Test
fun `test the default init`() {
assertEquals(0, defaultSystem.id)
assertEquals(0, defaultSystem.backboneNodes.size)
assertEquals(0, defaultSystem.edgeDeviceNodes.size)
assertEquals(0, defaultSystem.edgeNodes.size)
}
@Test
fun `getNode should return the respective node`() {
val system = AS(0)
assertNull(system.getNode(1))
val node = system.createBackboneNode(1)
assertEquals(node, system.getNode(1))
}
@Test
fun `hashCode function should return id`() {
assertEquals(0, defaultSystem.hashCode())
}
@Test
fun `toString function should include the id`() {
assertEquals("AS: 0", defaultSystem.toString())
}
@Test
fun `equals with different system with same id`() {
val system = AS(0)
assertEquals(system, defaultSystem)
assertFalse(system === defaultSystem)
}
@Test
fun `equals with different system with different id`() {
val system = AS(1)
assertNotEquals(system, defaultSystem)
assertFalse(system === defaultSystem)
}
@Test
fun `equals with same object`() {
assertEquals(defaultSystem, defaultSystem)
}
@Test
fun `equals with null`() {
assertNotEquals(defaultSystem, null)
}
@Test
fun `create an edge node`() {
val system = AS(1)
val edgeNode = system.createEdgeNode(42)
assertEquals(42, edgeNode.id)
val actual = system.getEdgeNode(42)
assertNotNull(actual)
assertEquals(42, actual!!.id)
assertTrue(system.containsNode(edgeNode))
assertTrue(system.edgeNodes.contains(edgeNode))
}
@Test
fun `create a backbone node`() {
val system = AS(1)
val backboneNode = system.createBackboneNode(42)
assertEquals(42, backboneNode.id)
val actual = system.getBackboneNode(42)
assertNotNull(actual)
assertEquals(42, actual!!.id)
assertTrue(system.containsNode(backboneNode))
assertTrue(system.backboneNodes.contains(backboneNode))
}
@Test
fun `create an edge device node`() {
val system = AS(1)
val container = DeviceContainer("docker", "tag", 1, 1F, 1, 1F)
val edgeDeviceNode = system.createEdgeDeviceNode(42, EdgeEmulationNode("1.2.3.4", container))
assertEquals(42, edgeDeviceNode.id)
val actual = system.getEdgeDeviceNode(42)
assertNotNull(actual)
assertEquals(42, actual!!.id)
assertTrue(system.containsNode(edgeDeviceNode))
assertTrue(system.edgeDeviceNodes.contains(edgeDeviceNode))
}
@Test
fun `containsNode on empty AS should return false`() {
assertFalse(defaultSystem.containsNode(BackboneNode(1, defaultSystem)))
}
@Test
fun `getBackboneNode that does not exist should return null`() {
assertNull(defaultSystem.getBackboneNode(42))
}
@Test
fun `getEdgeNode that does not exist should return null`() {
assertNull(defaultSystem.getEdgeNode(42))
}
@Test
fun `getEdgeDeviceNode that does not exist should return null`() {
assertNull(defaultSystem.getEdgeDeviceNode(42))
}
@Test
fun `replace a backbone node with an edge node`() {
val system = AS(1)
val backboneNode = system.createBackboneNode(42)
val edgeNode = system.replaceByEdgeNode(backboneNode)
assertEquals(backboneNode, edgeNode)
assertEquals(42, edgeNode.id)
assertEquals(system, edgeNode.system)
assertNull(system.getBackboneNode(42))
assertNull(system.backboneNodes.firstOrNull { it === backboneNode })
assertEquals(edgeNode, system.getEdgeNode(42))
assertTrue(system.edgeNodes.contains(edgeNode))
}
@Test
fun `replace a backbone node with an edge device node`() {
val system = AS(1)
val backboneNode = system.createBackboneNode(42)
val container = DeviceContainer("abc", "tag", 1024, 1F, 1, 1.5F)
val emulationNode = EdgeEmulationNode("1.2.3.4", container)
val edgeDeviceNode = system.replaceByEdgeDeviceNode(backboneNode, emulationNode)
assertEquals(backboneNode, edgeDeviceNode)
assertEquals(42, edgeDeviceNode.id)
assertEquals(system, edgeDeviceNode.system)
assertEquals(emulationNode, edgeDeviceNode.emulationNode)
assertNull(system.getBackboneNode(42))
assertNull(system.backboneNodes.firstOrNull { it === backboneNode })
assertEquals(edgeDeviceNode, system.getEdgeDeviceNode(42))
assertTrue(system.edgeDeviceNodes.contains(edgeDeviceNode))
}
@Test
fun `replace an edge node with a backbone node`() {
val system = AS(1)
val edgeNode = system.createEdgeNode(42)
val backboneNode = system.replaceByBackboneNode(edgeNode)
assertEquals(edgeNode, backboneNode)
assertEquals(42, backboneNode.id)
assertEquals(system, backboneNode.system)
assertNull(system.getEdgeNode(42))
assertNull(system.edgeNodes.firstOrNull { it === edgeNode })
assertEquals(backboneNode, system.getBackboneNode(42))
assertTrue(system.backboneNodes.contains(backboneNode))
}
@Test
fun `replacement call should fail with an exception of node is not part of the AS`() {
val node = AS(1024).createBackboneNode(1)
assertThrows<IllegalArgumentException> { defaultSystem.replaceByEdgeNode(node) }
}
@Test
fun `replacement call should fail with an exception if node cannot be removed from the AS`() {
val system1 = AS(0)
val system2 = AS(0)
val node = system1.createBackboneNode(1)
assertThrows<IllegalStateException> { system2.replaceByEdgeNode(node) }
}
} | src/test/kotlin/emufog/graph/ASTest.kt | 157454267 |
/*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.symbol
/**
* An application/reference to a type declared somewhere else.
*
* KSReferenceElement can specify, for example, a class, interface, or function, etc.
*/
interface KSReferenceElement : KSNode {
/**
* Type arguments in the type reference.
*/
val typeArguments: List<KSTypeArgument>
}
| api/src/main/kotlin/com/google/devtools/ksp/symbol/KSReferenceElement.kt | 2986683545 |
/*********************************************************************************
* Copyright 2017-present trivago GmbH
*
* 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.trivago.reportoire.rxV2.sources
import com.trivago.reportoire.core.sources.Source
import io.reactivex.Observable
/**
* Abstract RxSource source that will use the specified observable or resubscribe to the previous
* one if possible.
*/
abstract class CachedObservableSource<TModel, in TInput> : RxSource<TModel, TInput> {
// Members
private var mLatestInput: TInput? = null
private var mResultObservable: Observable<Source.Result<TModel>>? = null
// Abstract API
/**
* Override this method and supply a new observable that will be used to fetch the result.
*/
abstract fun onCreateResultObservable(input: TInput?): Observable<Source.Result<TModel>>
// RxSource
override fun resultObservable(input: TInput?): Observable<Source.Result<TModel>> {
if (mResultObservable == null || input?.equals(mLatestInput) == false) {
mLatestInput = input
mResultObservable = onCreateResultObservable(input).cache()
}
return mResultObservable!!
}
override fun isGettingResult(): Boolean {
return mResultObservable != null
}
override fun reset() {
mLatestInput = null
mResultObservable = null
}
override fun cancel() {
reset()
}
}
| rxV2/src/main/kotlin/com/trivago/reportoire/rxV2/sources/CachedObservableSource.kt | 1098345981 |
package cz.softdeluxe.jlib.io
import cz.petrbalat.utils.datetime.toLocalDateTime
import cz.softdeluxe.jlib.GIGA
import cz.softdeluxe.jlib.randomString
import cz.softdeluxe.jlib.removeDiakritiku
import org.imgscalr.Scalr
import org.springframework.web.multipart.MultipartFile
import java.awt.image.BufferedImage
import java.io.*
import java.net.URLConnection
import java.nio.charset.Charset
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
import java.time.LocalDateTime
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import javax.imageio.ImageIO
/**
* zkopíruje do adresáře s path.
* odstraní z názvu diakritiku, mezery apod a přidá do názvu random string
*/
fun MultipartFile.copyTo(path: String, pathPrepend: String = ""): String {
return inputStream.use {
it.copyTo(originalFilename, path, pathPrepend)
}
}
/**
* zkopíruje do adresáře s path.
* odstraní z názvu diakritiku, mezery apod a přidá do názvu random string
*/
fun InputStream.copyTo(originalFilename:String, path: String, pathPrepend: String = ""): String {
val origName = originalFilename.removeDiakritiku().replace(" ".toRegex(), "")
val before = if (pathPrepend.isEmpty()) randomString(4) else pathPrepend
val filename = "$before-${randomString(4).toLowerCase()}-$origName"
val uploadFile = File(path, filename)
assert(uploadFile.createNewFile())
FileOutputStream(uploadFile, false).use {
this.use { inputStream ->
inputStream.copyTo(it)
}
}
return filename
}
fun File.createThumbnail(targetSize: Int, mode: Scalr.Mode = Scalr.Mode.FIT_TO_WIDTH, pathAppend: String = "thumb"): File {
val image: BufferedImage = ImageIO.read(File(path))
val resizeImage: BufferedImage = Scalr.resize(image, Scalr.Method.QUALITY, mode, targetSize)
val file = File("$directory/$nameWithoutExtension-$pathAppend.$extension")
ImageIO.write(resizeImage, extension, file)
return file
}
fun ZipInputStream.entrySequence(): Sequence<ZipEntry> {
return generateSequence { nextEntry }
}
fun ZipInputStream.contentSequence(charsets: Charset = Charsets.UTF_8): Sequence<Pair<ZipEntry, String>> {
return entrySequence().map { zipEntry ->
val ous = ByteArrayOutputStream()
this.writeTo(ous)
val content = String(ous.toByteArray(), charsets)
Pair(zipEntry, content)
}
}
fun ZipInputStream.writeTo(outputStream: OutputStream): Unit {
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
outputStream.use { fos ->
while (true) {
val len = this.read(buffer)
if (len <= 0) {
break
}
fos.write(buffer, 0, len)
}
}
}
fun classPath(clazz: Class<Any>): Path {
val classPath = Paths.get(clazz.protectionDomain.codeSource.location.toURI())
return Paths.get("$classPath").toRealPath()
}
val File.directory: File
get() = if (isDirectory) this else parentFile!!
val File.probeContentType: String?
get() = Files.probeContentType(toPath()) ?: URLConnection.guessContentTypeFromName(name)
fun File.lastModifiedTime(): LocalDateTime {
val path = this.toPath()
return Files.readAttributes(path, BasicFileAttributes::class.java).lastModifiedTime().toInstant().toLocalDateTime()
}
const val IMAGE_TYPE: String = "image"
val File.typeByExtension: String
get() = when (extension.toLowerCase()) {
"pdf" -> "pdf"
"avi", "mkv", "mp4", "vob", "wmv", "mpg", "mpeg", "3gp", "flv" -> "video"
"jpg", "jpeg", "gif", "png" -> IMAGE_TYPE
"doc", "docx", "odt" -> "doc"
"mp3" -> "audio"
else -> "unknown"
}
fun File.fileSystemSpace(unit: Double = GIGA): FileSystemSpaceDto {
val dto = FileSystemSpaceDto()
dto.freeSpace = freeSpace / unit
dto.usableSpace = usableSpace / unit
dto.totalSpace = totalSpace / unit
return dto
}
fun File.loadAsProperties(): Properties {
return inputStream().use {
Properties().apply {
this.load(it)
}
}
}
/**
* zkopíruje do souboru
*/
fun InputStream.toFile(file:File): Long = this.use { ins ->
file.outputStream().use {
ins.copyTo(it)
}
}
class FileSystemSpaceDto {
var freeSpace: Double = 0.0
var usableSpace: Double = 0.0
var totalSpace: Double = 0.0
}
fun File.asFileSystem(): FileSystem = FileSystems.newFileSystem(this.toPath(), null) | src/main/java/cz/softdeluxe/jlib/io/IOHelpers.kt | 1724489010 |
/*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.settings.color
import android.graphics.Color
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.util.Random
/**
* @author toastkidjp
*/
class RandomColorInsertion(private val repository: SavedColorRepository) {
private val random = Random()
/**
* Insert random colors.
*
* @param context
*/
operator fun invoke(afterInserted: () -> Unit): Job {
val bg = makeRandomColor()
val font = makeRandomColor()
return CoroutineScope(Dispatchers.IO).launch {
repository.add(SavedColor.make(bg, font))
afterInserted()
}
}
private fun makeRandomColor(): Int {
return Color.argb(
random.nextInt(COLOR_CODE_MAX),
random.nextInt(COLOR_CODE_MAX),
random.nextInt(COLOR_CODE_MAX),
random.nextInt(COLOR_CODE_MAX)
)
}
companion object {
private const val COLOR_CODE_MAX = 255
}
} | app/src/main/java/jp/toastkid/yobidashi/settings/color/RandomColorInsertion.kt | 3378310993 |
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor.util
class InjectCssUrl(htmlPlacement: HtmlPlacement, isByScript: Boolean, val resourceURL: String) : InjectHtmlResource(htmlPlacement, isByScript) {
override fun htmlText(resourceUrl: String?): String = "<link rel=\"stylesheet\" href=\"${resourceUrl ?: resourceURL}\">\n"
override fun resourceURL(): String? = resourceURL
}
| src/main/java/com/vladsch/md/nav/editor/util/InjectCssUrl.kt | 3575319028 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.domain.observers
import app.tivi.data.daos.PopularDao
import app.tivi.data.resultentities.PopularEntryWithShow
import app.tivi.domain.SubjectInteractor
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class ObservePopularShows @Inject constructor(
private val popularShowsRepository: PopularDao
) : SubjectInteractor<ObservePopularShows.Params, List<PopularEntryWithShow>>() {
override fun createObservable(
params: Params
): Flow<List<PopularEntryWithShow>> {
return popularShowsRepository.entriesObservable(params.count, 0)
}
data class Params(val count: Int = 20)
}
| domain/src/main/java/app/tivi/domain/observers/ObservePopularShows.kt | 441855443 |
package net.tlalka.fiszki.model.types
enum class StorageType {
LANGUAGE, TRANSLATION, WELCOME_VIEW
}
| app/src/main/kotlin/net/tlalka/fiszki/model/types/StorageType.kt | 4068387738 |
package com.booboot.vndbandroid.model.vnstat
data class SimilarNovel(
var novelId: Int = 0,
var similarity: Float = 0f,
var title: String = "",
var votecount: String? = null,
var popularity: String? = null,
var bayesianRating: String? = null,
var meanRating: String? = null,
var released: String? = null,
var image: String? = null,
var predictedRating: Float = 0f
) {
fun imageLink(): String = IMAGE_LINK + image
fun similarityPercentage(): Double = Math.floor(similarity * 1000 + 0.5) / 10
fun predictedRatingPercentage(): Double = Math.round(predictedRating * 10 * 100.0).toDouble() / 100.0
fun setNovelId(novelId: String) {
this.novelId = novelId.toInt()
}
fun setSimilarity(similarity: String) {
this.similarity = similarity.toFloat()
}
companion object {
const val IMAGE_LINK = "http://i.vnstat.net/"
}
}
| app/src/main/java/com/booboot/vndbandroid/model/vnstat/SimilarNovel.kt | 2598138765 |
package link.kotlin.scripts.model
import link.kotlin.scripts.utils.logger
import java.lang.System.getenv
interface ApplicationConfiguration {
val ghToken: String
val siteUrl: String
val cacheEnabled: Boolean
val dryRun: Boolean
companion object
}
data class DataApplicationConfiguration(
override val ghToken: String = env("GH_TOKEN", ""),
override val siteUrl: String = "https://kotlin.link/",
override val cacheEnabled: Boolean = env("AWESOME_KOTLIN_CACHE", "true").toBoolean(),
override val dryRun: Boolean = false
): ApplicationConfiguration
fun ApplicationConfiguration.Companion.default(): ApplicationConfiguration {
val configuration = DataApplicationConfiguration()
return if (configuration.ghToken.isEmpty()) {
logger<DataApplicationConfiguration>().info("GH_TOKEN is not defined, dry run...")
configuration.copy(dryRun = true)
} else configuration
}
private fun env(key: String, default: String): String {
return getenv(key) ?: default
}
| src/main/kotlin/link/kotlin/scripts/model/ApplicationConfiguration.kt | 3726979975 |
/*
* Copyright (c) 2016-2019 PSPDFKit GmbH. All rights reserved.
*
* THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW
* AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT.
* UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES.
* This notice may not be removed from this file
*/
package com.pspdfkit.labs.quickdemo.service
import android.content.Intent
import android.graphics.drawable.Icon
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import com.pspdfkit.labs.quickdemo.DemoMode
import com.pspdfkit.labs.quickdemo.R
import com.pspdfkit.labs.quickdemo.activity.SetupGuideActivity
class DemoModeTileService : TileService() {
private lateinit var demoMode: DemoMode
override fun onCreate() {
super.onCreate()
demoMode = DemoMode.get(this)
}
override fun onStartListening() {
qsTile.icon = Icon.createWithResource(this, R.drawable.ic_demo_mode)
qsTile.label = "Demo mode"
updateIcon()
}
override fun onClick() {
if (!demoMode.requiredPermissionsGranted || !demoMode.demoModeAllowed) {
startActivityAndCollapse(SetupGuideActivity.intent(this))
return
}
demoMode.enabled = !demoMode.enabled
updateIcon()
val it = Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
sendBroadcast(it)
}
private fun updateIcon() {
qsTile.state = if (demoMode.enabled) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
qsTile.updateTile()
}
} | app/src/main/kotlin/com/pspdfkit/labs/quickdemo/service/DemoModeTileService.kt | 2853218249 |
package de.tutao.tutanota.data
import androidx.room.Dao
import androidx.room.Query
@Dao
interface KeyValueDao {
@Query("SELECT value FROM KeyValue WHERE key = :key LIMIT 1")
fun getString(key: String): String?
@Query("INSERT OR REPLACE INTO KeyValue (key, value) VALUES (:key, :value)")
fun putString(key: String, value: String?)
@Query("SELECT CAST(value as INT) FROM KeyValue WHERE key = :key LIMIT 1")
fun getLong(key: String): Long
@Query("INSERT OR REPLACE INTO KeyValue (key, value) VALUES (:key, :value)")
fun putLong(key: String, value: Long)
} | app-android/app/src/main/java/de/tutao/tutanota/data/KeyValueDao.kt | 3293084960 |
package fr.jcgay.gradle.notifier
import fr.jcgay.gradle.notifier.Status.FAILURE
import fr.jcgay.gradle.notifier.Status.SUCCESS
import fr.jcgay.gradle.notifier.extension.TimeThreshold
import fr.jcgay.notification.Notification
import fr.jcgay.notification.Notifier
import fr.jcgay.notification.SendNotificationException
import org.gradle.BuildAdapter
import org.gradle.BuildResult
import org.slf4j.LoggerFactory
class NotifierListener(val notifier: Notifier, private val timer: Clock, private val threshold: TimeThreshold): BuildAdapter() {
private val logger = LoggerFactory.getLogger(NotifierListener::class.java)
init {
logger.debug("Will send notification with: {} if execution last more than {}", notifier, threshold)
}
override fun buildFinished(result: BuildResult) {
try {
if (TimeThreshold(timer) >= threshold || notifier.isPersistent) {
val status = status(result)
val notification = Notification.builder()
.title(result.gradle?.rootProject?.name)
.message(message(result))
.icon(status.icon)
.subtitle(status.message)
.level(status.level)
.build()
logger.debug("Sending notification: {}", notification)
notifier.send(notification)
}
} catch (e: SendNotificationException) {
logger.warn("Error while sending notification.", e)
} finally {
notifier.close()
}
}
private fun message(result: BuildResult): String? {
return if (hasSucceeded(result)) {
"Done in: ${timer.getTime()}."
} else {
result.failure?.message ?: "Build Failed."
}
}
private fun status(result: BuildResult): Status = if (hasSucceeded(result)) SUCCESS else FAILURE
private fun hasSucceeded(result: BuildResult): Boolean = result.failure == null
}
| src/main/kotlin/fr/jcgay/gradle/notifier/NotifierListener.kt | 329438182 |
/*
* Copyright (c) 2020. Rei Matsushita
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hyakuninisshu.state.question.action
import me.rei_m.hyakuninisshu.state.core.Action
import me.rei_m.hyakuninisshu.state.question.model.QuestionState
/**
* 問題の回答を開始するアクション.
*/
sealed class StartAnswerQuestionAction(override val error: Throwable? = null) : Action {
class Success(val state: QuestionState.InAnswer) : StartAnswerQuestionAction() {
override fun toString() = "$name(state=$state)"
}
class Failure(error: Throwable) : StartAnswerQuestionAction(error) {
override fun toString() = "$name(error=$error)"
}
override val name = "StartAnswerQuestionAction"
}
| state/src/main/java/me/rei_m/hyakuninisshu/state/question/action/StartAnswerQuestionAction.kt | 2007946699 |
package com.sangcomz.fishbun
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.net.Uri
import androidx.activity.result.ActivityResultLauncher
import com.sangcomz.fishbun.ui.album.ui.AlbumActivity
import com.sangcomz.fishbun.ui.picker.PickerActivity
import kotlin.collections.ArrayList
/**
* Created by sangcomz on 17/05/2017.
*/
class FishBunCreator(private val fishBun: FishBun, private val fishton: Fishton) : BaseProperty,
CustomizationProperty {
private var requestCode = FishBun.FISHBUN_REQUEST_CODE
override fun setSelectedImages(selectedImages: ArrayList<Uri>): FishBunCreator = this.apply {
fishton.selectedImages.addAll(selectedImages)
}
override fun setAlbumThumbnailSize(size: Int): FishBunCreator = apply {
fishton.albumThumbnailSize = size
}
override fun setPickerSpanCount(spanCount: Int): FishBunCreator = this.apply {
fishton.photoSpanCount = if (spanCount <= 0) 3 else spanCount
}
@Deprecated("instead setMaxCount(count)", ReplaceWith("setMaxCount(count)"))
override fun setPickerCount(count: Int): FishBunCreator = this.apply {
setMaxCount(count)
}
override fun setMaxCount(count: Int): FishBunCreator = this.apply {
fishton.maxCount = if (count <= 0) 1 else count
}
override fun setMinCount(count: Int): FishBunCreator = this.apply {
fishton.minCount = if (count <= 0) 1 else count
}
override fun setActionBarTitleColor(actionbarTitleColor: Int): FishBunCreator = this.apply {
fishton.colorActionBarTitle = actionbarTitleColor
}
override fun setActionBarColor(actionbarColor: Int): FishBunCreator = this.apply {
fishton.colorActionBar = actionbarColor
}
override fun setActionBarColor(actionbarColor: Int, statusBarColor: Int): FishBunCreator =
this.apply {
fishton.colorActionBar = actionbarColor
fishton.colorStatusBar = statusBarColor
}
override fun setActionBarColor(
actionbarColor: Int,
statusBarColor: Int,
isStatusBarLight: Boolean
): FishBunCreator = this.apply {
fishton.colorActionBar = actionbarColor
fishton.colorStatusBar = statusBarColor
fishton.isStatusBarLight = isStatusBarLight
}
@Deprecated("instead setCamera(count)", ReplaceWith("hasCameraInPickerPage(mimeType)"))
override fun setCamera(isCamera: Boolean): FishBunCreator = this.apply {
fishton.hasCameraInPickerPage = isCamera
}
override fun hasCameraInPickerPage(hasCamera: Boolean): FishBunCreator = this.apply {
fishton.hasCameraInPickerPage = hasCamera
}
@Deprecated("To be deleted along with the startAlbum function")
override fun setRequestCode(requestCode: Int): FishBunCreator = this.apply {
this.requestCode = requestCode
}
override fun textOnNothingSelected(message: String): FishBunCreator = this.apply {
fishton.messageNothingSelected = message
}
override fun textOnImagesSelectionLimitReached(message: String): FishBunCreator = this.apply {
fishton.messageLimitReached = message
}
override fun setButtonInAlbumActivity(isButton: Boolean): FishBunCreator = this.apply {
fishton.hasButtonInAlbumActivity = isButton
}
override fun setReachLimitAutomaticClose(isAutomaticClose: Boolean): FishBunCreator =
this.apply {
fishton.isAutomaticClose = isAutomaticClose
}
override fun setAlbumSpanCount(
portraitSpanCount: Int,
landscapeSpanCount: Int
): FishBunCreator = this.apply {
fishton.albumPortraitSpanCount = portraitSpanCount
fishton.albumLandscapeSpanCount = landscapeSpanCount
}
override fun setAlbumSpanCountOnlyLandscape(landscapeSpanCount: Int): FishBunCreator =
this.apply {
fishton.albumLandscapeSpanCount = landscapeSpanCount
}
override fun setAlbumSpanCountOnlPortrait(portraitSpanCount: Int): FishBunCreator = this.apply {
fishton.albumPortraitSpanCount = portraitSpanCount
}
override fun setAllViewTitle(allViewTitle: String): FishBunCreator = this.apply {
fishton.titleAlbumAllView = allViewTitle
}
override fun setActionBarTitle(actionBarTitle: String): FishBunCreator = this.apply {
fishton.titleActionBar = actionBarTitle
}
override fun setHomeAsUpIndicatorDrawable(icon: Drawable?): FishBunCreator = this.apply {
fishton.drawableHomeAsUpIndicator = icon
}
override fun setDoneButtonDrawable(icon: Drawable?): FishBunCreator = this.apply {
fishton.drawableDoneButton = icon
}
override fun setAllDoneButtonDrawable(icon: Drawable?): FishBunCreator = this.apply {
fishton.drawableAllDoneButton = icon
}
override fun setIsUseAllDoneButton(isUse: Boolean): FishBunCreator = this.apply {
fishton.isUseAllDoneButton = isUse
}
@Deprecated("instead setMaxCount(count)", ReplaceWith("exceptMimeType(mimeType)"))
override fun exceptGif(isExcept: Boolean): FishBunCreator = this.apply {
fishton.exceptMimeTypeList = arrayListOf(MimeType.GIF)
}
override fun exceptMimeType(exceptMimeTypeList: List<MimeType>) = this.apply {
fishton.exceptMimeTypeList = exceptMimeTypeList
}
override fun setMenuDoneText(text: String?): FishBunCreator = this.apply {
fishton.strDoneMenu = text
}
override fun setMenuAllDoneText(text: String?): FishBunCreator = this.apply {
fishton.strAllDoneMenu = text
}
override fun setMenuTextColor(color: Int): FishBunCreator = this.apply {
fishton.colorTextMenu = color
}
override fun setIsUseDetailView(isUse: Boolean): FishBunCreator = this.apply {
fishton.isUseDetailView = isUse
}
override fun setIsShowCount(isShow: Boolean): FishBunCreator = this.apply {
fishton.isShowCount = isShow
}
override fun setSelectCircleStrokeColor(strokeColor: Int): FishBunCreator = this.apply {
fishton.colorSelectCircleStroke = strokeColor
}
override fun isStartInAllView(isStartInAllView: Boolean): FishBunCreator = this.apply {
fishton.isStartInAllView = isStartInAllView
}
override fun setSpecifyFolderList(specifyFolderList: List<String>) = this.apply {
fishton.specifyFolderList = specifyFolderList
}
private fun prepareStartAlbum(context: Context) {
checkNotNull(fishton.imageAdapter)
exceptionHandling()
setDefaultValue(context)
}
@Deprecated("instead startAlbumWithOnActivityResult(requestCode)", ReplaceWith("startAlbumWithOnActivityResult(requestCode)"))
override fun startAlbum() {
val fishBunContext = fishBun.fishBunContext
val context = fishBunContext.getContext()
prepareStartAlbum(context)
fishBunContext.startActivityForResult(getIntent(context), requestCode)
}
override fun startAlbumWithOnActivityResult(requestCode: Int) {
val fishBunContext = fishBun.fishBunContext
val context = fishBunContext.getContext()
prepareStartAlbum(context)
fishBunContext.startActivityForResult(getIntent(context), requestCode)
}
override fun startAlbumWithActivityResultCallback(activityResultLauncher: ActivityResultLauncher<Intent>) {
val fishBunContext = fishBun.fishBunContext
val context = fishBunContext.getContext()
prepareStartAlbum(context)
fishBunContext.startWithRegisterForActivityResult(activityResultLauncher, getIntent(context))
}
private fun getIntent(context: Context): Intent =
if (fishton.isStartInAllView) {
PickerActivity.getPickerActivityIntent(context, 0L, fishton.titleAlbumAllView, 0)
} else {
Intent(context, AlbumActivity::class.java)
}
private fun setDefaultValue(context: Context) {
with(fishton) {
setDefaultMessage(context)
setMenuTextColor()
setDefaultDimen(context)
}
}
private fun exceptionHandling() {
if (fishton.hasCameraInPickerPage) {
fishton.hasCameraInPickerPage = fishton.specifyFolderList.isEmpty()
}
}
}
| FishBun/src/main/java/com/sangcomz/fishbun/FishBunCreator.kt | 3920150524 |
package pw.janyo.whatanime.utils
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Environment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import pw.janyo.whatanime.context
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.nio.channels.FileChannel
import java.security.MessageDigest
import kotlin.math.max
import kotlin.math.min
private const val CACHE_IMAGE_FILE_NAME = "cacheImage"
/**
* 获取缓存文件
* @return 缓存文件(需要判断是否存在,如果返回为空说明目录权限有问题)
*/
fun File.getCacheFile(): File? {
val saveParent = context.getExternalFilesDir(CACHE_IMAGE_FILE_NAME) ?: return null
if (!saveParent.exists())
saveParent.mkdirs()
if (saveParent.isDirectory || saveParent.delete() && saveParent.mkdirs()) {
val md5Name = absolutePath.md5()
return File(saveParent, md5Name)
}
return null
}
@Throws(IOException::class)
private suspend fun <T : InputStream> T.copyToFile(outputFile: File) {
withContext(Dispatchers.IO) {
if (!outputFile.parentFile!!.exists())
outputFile.parentFile?.mkdirs()
if (outputFile.exists())
outputFile.delete()
FileOutputStream(outputFile).use {
[email protected](it)
}
}
}
/**
* 将Uri的内容克隆到临时文件,然后返回临时文件
*
* @return 临时文件
*/
suspend fun Uri.cloneUriToFile(): File? {
val parent = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) ?: return null
if (!parent.exists())
parent.mkdirs()
if (parent.isDirectory || parent.delete() && parent.mkdirs()) {
val file = File(parent, this.toString().sha1())
context.contentResolver.openInputStream(this)!!.use {
it.copyToFile(file)
}
return file
}
return null
}
private fun File.zoomBitmap(): Bitmap {
val maxHeight = 640
val maxWidth = 640
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(absolutePath, options)
val scaleW = max(maxWidth, options.outWidth) / (min(maxWidth, options.outWidth) * 1.0) - 0.5
val scaleH = max(maxHeight, options.outHeight) / (min(maxHeight, options.outHeight) * 1.0) - 0.5
options.inSampleSize = max(scaleW, scaleH).toInt()
options.inJustDecodeBounds = false
return BitmapFactory.decodeFile(absolutePath, options)
}
@Throws(IOException::class)
suspend fun File.md5(): String {
return withContext(Dispatchers.IO) {
val messageDigest = MessageDigest.getInstance("MD5")
messageDigest.update(
FileInputStream(this@md5).channel.map(
FileChannel.MapMode.READ_ONLY,
0,
length()
)
)
val bytes = messageDigest.digest()
toHex(bytes)
}
} | app/src/main/java/pw/janyo/whatanime/utils/FileUtil.kt | 1728940974 |
/**
* Copyright Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.codelab.friendlychat
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.database.FirebaseRecyclerOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.codelab.friendlychat.databinding.ActivityMainBinding
import com.google.firebase.codelab.friendlychat.model.FriendlyMessage
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.ktx.storage
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var manager: LinearLayoutManager
// Firebase instance variables
private lateinit var auth: FirebaseAuth
private lateinit var db: FirebaseDatabase
private lateinit var adapter: FriendlyMessageAdapter
private val openDocument = registerForActivityResult(MyOpenDocumentContract()) { uri ->
uri?.let { onImageSelected(it) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This codelab uses View Binding
// See: https://developer.android.com/topic/libraries/view-binding
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// When running in debug mode, connect to the Firebase Emulator Suite
// "10.0.2.2" is a special value which allows the Android emulator to
// connect to "localhost" on the host computer. The port values are
// defined in the firebase.json file.
if (BuildConfig.DEBUG) {
Firebase.database.useEmulator("10.0.2.2", 9000)
Firebase.auth.useEmulator("10.0.2.2", 9099)
Firebase.storage.useEmulator("10.0.2.2", 9199)
}
// Initialize Firebase Auth and check if the user is signed in
auth = Firebase.auth
if (auth.currentUser == null) {
// Not signed in, launch the Sign In activity
startActivity(Intent(this, SignInActivity::class.java))
finish()
return
}
// Initialize Realtime Database
db = Firebase.database
val messagesRef = db.reference.child(MESSAGES_CHILD)
// The FirebaseRecyclerAdapter class and options come from the FirebaseUI library
// See: https://github.com/firebase/FirebaseUI-Android
val options = FirebaseRecyclerOptions.Builder<FriendlyMessage>()
.setQuery(messagesRef, FriendlyMessage::class.java)
.build()
adapter = FriendlyMessageAdapter(options, getUserName())
binding.progressBar.visibility = ProgressBar.INVISIBLE
manager = LinearLayoutManager(this)
manager.stackFromEnd = true
binding.messageRecyclerView.layoutManager = manager
binding.messageRecyclerView.adapter = adapter
// Scroll down when a new message arrives
// See MyScrollToBottomObserver for details
adapter.registerAdapterDataObserver(
MyScrollToBottomObserver(binding.messageRecyclerView, adapter, manager)
)
// Disable the send button when there's no text in the input field
// See MyButtonObserver for details
binding.messageEditText.addTextChangedListener(MyButtonObserver(binding.sendButton))
// When the send button is clicked, send a text message
binding.sendButton.setOnClickListener {
val friendlyMessage = FriendlyMessage(
binding.messageEditText.text.toString(),
getUserName(),
getPhotoUrl(),
null
)
db.reference.child(MESSAGES_CHILD).push().setValue(friendlyMessage)
binding.messageEditText.setText("")
}
// When the image button is clicked, launch the image picker
binding.addMessageImageView.setOnClickListener {
openDocument.launch(arrayOf("image/*"))
}
}
public override fun onStart() {
super.onStart()
// Check if user is signed in.
if (auth.currentUser == null) {
// Not signed in, launch the Sign In activity
startActivity(Intent(this, SignInActivity::class.java))
finish()
return
}
}
public override fun onPause() {
adapter.stopListening()
super.onPause()
}
public override fun onResume() {
super.onResume()
adapter.startListening()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.main_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.sign_out_menu -> {
signOut()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun onImageSelected(uri: Uri) {
Log.d(TAG, "Uri: $uri")
val user = auth.currentUser
val tempMessage = FriendlyMessage(null, getUserName(), getPhotoUrl(), LOADING_IMAGE_URL)
db.reference
.child(MESSAGES_CHILD)
.push()
.setValue(
tempMessage,
DatabaseReference.CompletionListener { databaseError, databaseReference ->
if (databaseError != null) {
Log.w(
TAG, "Unable to write message to database.",
databaseError.toException()
)
return@CompletionListener
}
// Build a StorageReference and then upload the file
val key = databaseReference.key
val storageReference = Firebase.storage
.getReference(user!!.uid)
.child(key!!)
.child(uri.lastPathSegment!!)
putImageInStorage(storageReference, uri, key)
})
}
private fun putImageInStorage(storageReference: StorageReference, uri: Uri, key: String?) {
// First upload the image to Cloud Storage
storageReference.putFile(uri)
.addOnSuccessListener(
this
) { taskSnapshot -> // After the image loads, get a public downloadUrl for the image
// and add it to the message.
taskSnapshot.metadata!!.reference!!.downloadUrl
.addOnSuccessListener { uri ->
val friendlyMessage =
FriendlyMessage(null, getUserName(), getPhotoUrl(), uri.toString())
db.reference
.child(MESSAGES_CHILD)
.child(key!!)
.setValue(friendlyMessage)
}
}
.addOnFailureListener(this) { e ->
Log.w(
TAG,
"Image upload task was unsuccessful.",
e
)
}
}
private fun signOut() {
AuthUI.getInstance().signOut(this)
startActivity(Intent(this, SignInActivity::class.java))
finish()
}
private fun getPhotoUrl(): String? {
val user = auth.currentUser
return user?.photoUrl?.toString()
}
private fun getUserName(): String? {
val user = auth.currentUser
return if (user != null) {
user.displayName
} else ANONYMOUS
}
companion object {
private const val TAG = "MainActivity"
const val MESSAGES_CHILD = "messages"
const val ANONYMOUS = "anonymous"
private const val LOADING_IMAGE_URL = "https://www.google.com/images/spin-32.gif"
}
}
| build-android/app/src/main/java/com/google/firebase/codelab/friendlychat/MainActivity.kt | 883962284 |
package cm.aptoide.pt.home.bundles.promotional
import android.view.View
import cm.aptoide.aptoideviews.skeleton.Skeleton
import cm.aptoide.pt.R
import cm.aptoide.pt.app.DownloadModel
import cm.aptoide.pt.home.bundles.base.*
import cm.aptoide.pt.networking.image.ImageLoader
import kotlinx.android.synthetic.main.card_new_app_version.view.*
import kotlinx.android.synthetic.main.card_new_package.view.action_button
import kotlinx.android.synthetic.main.card_new_package.view.action_button_skeleton
import kotlinx.android.synthetic.main.card_new_package.view.app_background_image
import kotlinx.android.synthetic.main.card_new_package.view.app_icon
import kotlinx.android.synthetic.main.card_new_package.view.app_icon_skeletonview
import kotlinx.android.synthetic.main.card_new_package.view.app_name
import kotlinx.android.synthetic.main.card_new_package.view.app_name_skeletonview
import kotlinx.android.synthetic.main.card_new_package.view.card_title_label
import kotlinx.android.synthetic.main.card_new_package.view.card_title_label_skeletonview
import kotlinx.android.synthetic.main.card_new_package.view.card_title_label_text
import rx.subjects.PublishSubject
class NewAppVersionViewHolder(val view: View,
val uiEventsListener: PublishSubject<HomeEvent>) :
AppBundleViewHolder(view) {
private var skeleton: Skeleton? = null
override fun setBundle(homeBundle: HomeBundle?, position: Int) {
if (homeBundle !is VersionPromotionalBundle) {
throw IllegalStateException(
this.javaClass.name + " is getting non PromotionalBundle instance!")
}
(homeBundle as? VersionPromotionalBundle)?.let { bundle ->
if (homeBundle.content == null) {
toggleSkeleton(true)
} else {
toggleSkeleton(false)
ImageLoader.with(itemView.context)
.loadWithRoundCorners(homeBundle.app.icon, 32, itemView.app_icon,
R.attr.placeholder_square)
itemView.card_title_label_text.text = homeBundle.title
ImageLoader.with(itemView.context)
.load(homeBundle.app.featureGraphic, itemView.app_background_image)
itemView.app_name.text = homeBundle.app.name
itemView.version_name.text = homeBundle.versionName
itemView.action_button.setOnClickListener {
fireAppClickEvent(homeBundle)
}
itemView.setOnClickListener {
fireAppClickEvent(homeBundle)
}
setButtonText(homeBundle.downloadModel)
}
}
}
private fun setButtonText(model: DownloadModel) {
when (model.action) {
DownloadModel.Action.UPDATE -> itemView.action_button.text =
itemView.resources.getString(R.string.appview_button_update)
DownloadModel.Action.INSTALL -> itemView.action_button.text =
itemView.resources.getString(R.string.appview_button_install)
DownloadModel.Action.OPEN -> itemView.action_button.text =
itemView.resources.getString(R.string.appview_button_open)
DownloadModel.Action.DOWNGRADE -> itemView.action_button.text =
itemView.resources.getString(R.string.appview_button_downgrade)
DownloadModel.Action.MIGRATE -> itemView.action_button.text =
itemView.resources.getString(R.string.promo_update2appc_appview_update_button)
}
}
private fun fireAppClickEvent(homeBundle: PromotionalBundle) {
uiEventsListener.onNext(
AppHomeEvent(homeBundle.app, 0, homeBundle, adapterPosition,
HomeEvent.Type.INSTALL_PROMOTIONAL))
}
private fun toggleSkeleton(showSkeleton: Boolean) {
if (showSkeleton) {
skeleton?.showSkeleton()
itemView.card_title_label_skeletonview.visibility = View.VISIBLE
itemView.card_title_label.visibility = View.INVISIBLE
itemView.app_icon_skeletonview.visibility = View.VISIBLE
itemView.app_icon.visibility = View.INVISIBLE
itemView.app_name_skeletonview.visibility = View.VISIBLE
itemView.app_name.visibility = View.INVISIBLE
itemView.version_text_skeleton.visibility = View.VISIBLE
itemView.version_name_skeleton.visibility = View.VISIBLE
itemView.version_name.visibility = View.INVISIBLE
itemView.action_button_skeleton.visibility = View.VISIBLE
itemView.action_button.visibility = View.INVISIBLE
} else {
skeleton?.showOriginal()
itemView.card_title_label_skeletonview.visibility = View.INVISIBLE
itemView.card_title_label.visibility = View.VISIBLE
itemView.app_icon_skeletonview.visibility = View.INVISIBLE
itemView.app_icon.visibility = View.VISIBLE
itemView.app_name_skeletonview.visibility = View.INVISIBLE
itemView.app_name.visibility = View.VISIBLE
itemView.version_text_skeleton.visibility = View.INVISIBLE
itemView.version_name_skeleton.visibility = View.INVISIBLE
itemView.version_name.visibility = View.VISIBLE
itemView.action_button_skeleton.visibility = View.INVISIBLE
itemView.action_button.visibility = View.VISIBLE
}
}
} | app/src/main/java/cm/aptoide/pt/home/bundles/promotional/NewAppVersionViewHolder.kt | 2160046992 |
package com.alexfacciorusso.daggerviewmodel
import androidx.lifecycle.ViewModel
import dagger.MapKey
import kotlin.reflect.KClass
/**
* @author alexfacciorusso
*/
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
| daggerviewmodel/src/main/java/com/alexfacciorusso/daggerviewmodel/ViewModelKey.kt | 476958453 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.components.impl.stores
import com.intellij.openapi.components.RoamingType
import java.io.IOException
import java.io.InputStream
public interface StreamProvider {
public open val enabled: Boolean
get() = true
public open fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean = true
/**
* @param fileSpec
* @param content bytes of content, size of array is not actual size of data, you must use `size`
* @param size actual size of data
*/
public fun saveContent(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType)
public fun loadContent(fileSpec: String, roamingType: RoamingType): InputStream?
public open fun listSubFiles(fileSpec: String, roamingType: RoamingType): Collection<String> = emptyList()
/**
* You must close passed input stream.
*/
public open fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) {
for (name in listSubFiles(path, roamingType)) {
if (!filter(name)) {
continue
}
val input: InputStream?
try {
input = loadContent("$path/$name", roamingType)
}
catch (e: IOException) {
StorageUtil.LOG.error(e)
continue
}
if (input != null && !processor(name, input, false)) {
break
}
}
}
/**
* Delete file or directory
*/
public fun delete(fileSpec: String, roamingType: RoamingType)
} | platform/platform-impl/src/com/intellij/openapi/components/impl/stores/StreamProvider.kt | 733245644 |
package io.github.binaryfoo.decoders
import io.github.binaryfoo.decoders.annotator.SignedDataDecoder
import io.github.binaryfoo.EmvTags
import io.github.binaryfoo.DecodedData
import io.github.binaryfoo.findAllForTag
import io.github.binaryfoo.findTlvForTag
/**
* EMV 4.3 Book 2, Table 7: Format of Data Recovered from Signed Static Application Data
*
* Static data auth means CA (scheme) -> Issuer -> data. Chip has no RSA hardware. No replay attack prevention.
*/
public class SignedStaticApplicationDataDecoder : SignedDataDecoder {
override fun decodeSignedData(session: DecodeSession, decoded: List<DecodedData>) {
val issuerPublicKeyCertificate = session.issuerPublicKeyCertificate
val signedStaticData = decoded.findTlvForTag(EmvTags.SIGNED_STATIC_APPLICATION_DATA)
if (signedStaticData != null && issuerPublicKeyCertificate != null) {
for (decodedSSD in decoded.findAllForTag(EmvTags.SIGNED_STATIC_APPLICATION_DATA)) {
recoverSignedData(signedStaticData, decodedSSD, issuerPublicKeyCertificate, ::decodeSignedStaticData)
}
}
}
}
fun decodeSignedStaticData(recovered: ByteArray, startIndexInBytes: Int): List<DecodedData> {
return listOf(
DecodedData.byteRange("Header", recovered, 0, 1, startIndexInBytes),
DecodedData.byteRange("Format", recovered, 1, 1, startIndexInBytes),
DecodedData.byteRange("Hash Algorithm", recovered, 2, 1, startIndexInBytes),
DecodedData.byteRange("Data Auth Code", recovered, 3, 2, startIndexInBytes),
DecodedData.byteRange("Hash", recovered, recovered.size-21, 20, startIndexInBytes),
DecodedData.byteRange("Trailer", recovered, recovered.size-1, 1, startIndexInBytes)
)
}
| src/main/java/io/github/binaryfoo/decoders/SignedStaticApplicationDataDecoder.kt | 3794476710 |
/*
* Copyright (c) 2022 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.servicelayer.scopedstorage
import androidx.annotation.CheckResult
import com.ichi2.anki.RobolectricTest
import com.ichi2.anki.model.DiskFile
import com.ichi2.anki.servicelayer.ScopedStorageService
import com.ichi2.libanki.Media
import org.acra.util.IOUtils
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert.*
import java.io.File
/** Adds a media file to collection.media which [Media] is not aware of */
@CheckResult
internal fun addUntrackedMediaFile(media: Media, content: String, path: List<String>): DiskFile {
val file = convertPathToMediaFile(media, path)
File(file.parent!!).mkdirs()
IOUtils.writeStringToFile(file, content)
return DiskFile.createInstance(file)!!
}
private fun convertPathToMediaFile(media: Media, path: List<String>): File {
val mutablePath = ArrayDeque(path)
var file = File(media.dir())
while (mutablePath.any()) {
file = File(file, mutablePath.removeFirst())
}
return file
}
/** A [File] reference to the AnkiDroid directory of the current collection */
internal fun RobolectricTest.ankiDroidDirectory() = File(col.path).parentFile!!
/** Adds a file to collection.media which [Media] is not aware of */
@CheckResult
internal fun RobolectricTest.addUntrackedMediaFile(content: String, path: List<String>): DiskFile =
addUntrackedMediaFile(col.media, content, path)
fun RobolectricTest.assertMigrationInProgress() {
assertThat("the migration should be in progress", ScopedStorageService.userMigrationIsInProgress(this.targetContext), equalTo(true))
}
fun RobolectricTest.assertMigrationNotInProgress() {
assertThat("the migration should not be in progress", ScopedStorageService.userMigrationIsInProgress(this.targetContext), equalTo(false))
}
| AnkiDroid/src/test/java/com/ichi2/anki/servicelayer/scopedstorage/Utils.kt | 138636651 |
package com.fastaccess.ui.adapter.viewholder
import android.annotation.SuppressLint
import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.text.style.BackgroundColorSpan
import android.view.View
import android.view.ViewGroup
import butterknife.BindView
import com.fastaccess.R
import com.fastaccess.data.dao.timeline.PullRequestTimelineModel
import com.fastaccess.helper.ParseDateFormat
import com.fastaccess.helper.PrefGetter
import com.fastaccess.helper.ViewHelper
import com.fastaccess.provider.scheme.LinkParserHelper
import com.fastaccess.provider.timeline.HtmlHelper
import com.fastaccess.ui.widgets.AvatarLayout
import com.fastaccess.ui.widgets.FontTextView
import com.fastaccess.ui.widgets.ForegroundImageView
import com.fastaccess.ui.widgets.SpannableBuilder
import com.fastaccess.ui.widgets.recyclerview.BaseRecyclerAdapter
import com.fastaccess.ui.widgets.recyclerview.BaseViewHolder
import com.zzhoujay.markdown.style.CodeSpan
import github.PullRequestTimelineQuery
import github.type.StatusState
/**
* Created by kosh on 03/08/2017.
*/
class PullRequestEventViewHolder private constructor(view: View, adapter: BaseRecyclerAdapter<*, *, *>) :
BaseViewHolder<PullRequestTimelineModel>(view, adapter) {
@BindView(R.id.stateImage) lateinit var stateImage: ForegroundImageView
@BindView(R.id.avatarLayout) lateinit var avatarLayout: AvatarLayout
@BindView(R.id.stateText) lateinit var stateText: FontTextView
@BindView(R.id.commitStatus) lateinit var commitStatus: ForegroundImageView
override fun bind(t: PullRequestTimelineModel) {
val node = t.node
commitStatus.visibility = View.GONE
if (node != null) {
when {
node.asAssignedEvent() != null -> assignedEvent(node.asAssignedEvent()!!)
node.asBaseRefForcePushedEvent() != null -> forcePushEvent(node.asBaseRefForcePushedEvent()!!)
node.asClosedEvent() != null -> closedEvent(node.asClosedEvent()!!)
node.asCommit() != null -> commitEvent(node.asCommit()!!)
node.asDemilestonedEvent() != null -> demilestonedEvent(node.asDemilestonedEvent()!!)
node.asDeployedEvent() != null -> deployedEvent(node.asDeployedEvent()!!)
node.asHeadRefDeletedEvent() != null -> refDeletedEvent(node.asHeadRefDeletedEvent()!!)
node.asHeadRefForcePushedEvent() != null -> refForPushedEvent(node.asHeadRefForcePushedEvent()!!)
node.asHeadRefRestoredEvent() != null -> headRefRestoredEvent(node.asHeadRefRestoredEvent()!!)
node.asLabeledEvent() != null -> labeledEvent(node.asLabeledEvent()!!)
node.asLockedEvent() != null -> lockEvent(node.asLockedEvent()!!)
node.asMergedEvent() != null -> mergedEvent(node.asMergedEvent()!!)
node.asMilestonedEvent() != null -> milestoneEvent(node.asMilestonedEvent()!!)
node.asReferencedEvent() != null -> referenceEvent(node.asReferencedEvent()!!)
node.asRenamedTitleEvent() != null -> renamedEvent(node.asRenamedTitleEvent()!!)
node.asReopenedEvent() != null -> reopenedEvent(node.asReopenedEvent()!!)
node.asUnassignedEvent() != null -> unassignedEvent(node.asUnassignedEvent()!!)
node.asUnlabeledEvent() != null -> unlabeledEvent(node.asUnlabeledEvent()!!)
node.asUnlockedEvent() != null -> unlockedEvent(node.asUnlockedEvent()!!)
else -> reset()
}
} else {
reset()
}
}
private fun reset() {
stateText.text = ""
avatarLayout.setUrl(null, null, false, false)
}
@SuppressLint("SetTextI18n")
private fun unlockedEvent(event: PullRequestTimelineQuery.AsUnlockedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("unlocked this conversation")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_lock)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun unlabeledEvent(event: PullRequestTimelineQuery.AsUnlabeledEvent) {
event.actor()?.let {
val color = Color.parseColor("#" + event.label().color())
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("removed")
.append(" ")
.append(event.label().name(), CodeSpan(color, ViewHelper.generateTextColor(color), 5.0f))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_label)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun unassignedEvent(event: PullRequestTimelineQuery.AsUnassignedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("unassigned") //TODO add "removed their assignment" for self
.append(" ")
.append(event.user()?.login())
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_profile)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun reopenedEvent(event: PullRequestTimelineQuery.AsReopenedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("reopened this")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_issue_opened)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun renamedEvent(event: PullRequestTimelineQuery.AsRenamedTitleEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("changed the title from").append(" ").append(event.previousTitle())
.append(" ").append("to").append(" ").bold(event.currentTitle())
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_edit)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun referenceEvent(event: PullRequestTimelineQuery.AsReferencedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("referenced in")
.append(" ")
.append("from").append(" ")
.url(if (event.commit() != null) {
substring(event.commit()?.oid()?.toString())
} else if (event.subject().asIssue() != null) {
if (event.isCrossRepository) {
"${event.commitRepository().nameWithOwner()} ${event.subject().asIssue()?.title()}#${event.subject().asIssue()?.number()}"
} else {
"${event.subject().asIssue()?.title()}#${event.subject().asIssue()?.number()}"
}
} else if (event.subject().asPullRequest() != null) {
if (event.isCrossRepository) {
"${event.commitRepository().nameWithOwner()} ${event.subject().asPullRequest()?.title()}" +
"#${event.subject().asPullRequest()?.number()}"
} else {
"${event.subject().asPullRequest()?.title()}#${event.subject().asPullRequest()?.number()}"
}
} else {
event.commitRepository().nameWithOwner()
})
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun milestoneEvent(event: PullRequestTimelineQuery.AsMilestonedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("added this to the")
.append(" ")
.append(event.milestoneTitle()).append(" ").append("milestone")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_milestone)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun mergedEvent(event: PullRequestTimelineQuery.AsMergedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("merged commit")
.append(" ")
.url(substring(event.commit()?.oid()?.toString()))
.append(" ")
.append("into")
.append(" ")
.append(event.actor())
.append(":")
.append(event.mergeRefName(), BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_merge)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun lockEvent(event: PullRequestTimelineQuery.AsLockedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("locked and limited conversation to collaborators")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_lock)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun labeledEvent(event: PullRequestTimelineQuery.AsLabeledEvent) {
event.actor()?.let {
val color = Color.parseColor("#" + event.label().color())
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("labeled")
.append(" ")
.append(event.label().name(), CodeSpan(color, ViewHelper.generateTextColor(color), 5.0f))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_label)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun headRefRestoredEvent(event: PullRequestTimelineQuery.AsHeadRefRestoredEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("restored the")
.append(" ")
.append(it.login())
.append(":")
.append(event.pullRequest().headRefName(), BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.append("branch")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun refForPushedEvent(event: PullRequestTimelineQuery.AsHeadRefForcePushedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("reference force pushed to", BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.url(substring(event.afterCommit().oid().toString()))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun refDeletedEvent(event: PullRequestTimelineQuery.AsHeadRefDeletedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("deleted the")
.append(" ")
.append(it.login())
.append(":")
.append(substring(event.headRefName()), BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.append("branch")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_trash)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun deployedEvent(event: PullRequestTimelineQuery.AsDeployedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("made a deployment", BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.append(event.deployment().latestStatus()?.state()?.name)
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun demilestonedEvent(event: PullRequestTimelineQuery.AsDemilestonedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("removed this from the")
.append(" ")
.append(event.milestoneTitle()).append(" ").append("milestone")
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_milestone)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun commitEvent(event: PullRequestTimelineQuery.AsCommit) {
event.author()?.let {
stateText.text = SpannableBuilder.builder()//Review[k0shk0sh] We may want to suppress more then 3 or 4 commits. since it will clog the it
.bold(if (it.user() == null) it.name() else it.user()?.login())
.append(" ")
.append("committed")
.append(" ")
.append(event.messageHeadline())
.append(" ")
.url(substring(event.oid().toString()))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.committedDate().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.user()?.avatarUrl().toString(), it.user()?.login(), false,
LinkParserHelper.isEnterprise(it.user()?.url().toString()))
event.status()?.let {
commitStatus.visibility = View.VISIBLE
val context = commitStatus.context
commitStatus.tintDrawableColor(when (it.state()) {
StatusState.ERROR -> ContextCompat.getColor(context, R.color.material_red_700)
StatusState.FAILURE -> ContextCompat.getColor(context, R.color.material_deep_orange_700)
StatusState.SUCCESS -> ContextCompat.getColor(context, R.color.material_green_700)
else -> ContextCompat.getColor(context, R.color.material_yellow_700)
})
}
}
}
private fun closedEvent(event: PullRequestTimelineQuery.AsClosedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("closed this in")
.append(" ")
.url(substring(event.commit()?.oid()?.toString()))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_merge)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun forcePushEvent(event: PullRequestTimelineQuery.AsBaseRefForcePushedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("force pushed to", BackgroundColorSpan(HtmlHelper.getWindowBackground(PrefGetter.getThemeType())))
.append(" ")
.url(substring(event.afterCommit().oid().toString()))
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_push)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun assignedEvent(event: PullRequestTimelineQuery.AsAssignedEvent) {
event.actor()?.let {
stateText.text = SpannableBuilder.builder()
.bold(it.login())
.append(" ")
.append("assigned") //TODO add "self-assigned" for self
.append(" ")
.append(event.user()?.login())
.append(" ")
.append(ParseDateFormat.getTimeAgo((event.createdAt().toString())))
stateImage.setImageResource(R.drawable.ic_profile)
avatarLayout.setUrl(it.avatarUrl().toString(), it.login(), false, LinkParserHelper.isEnterprise(it.url().toString()))
}
}
private fun substring(value: String?): String {
if (value == null) {
return ""
}
return if (value.length <= 7) value
else value.substring(0, 7)
}
companion object {
fun newInstance(parent: ViewGroup, adapter: BaseRecyclerAdapter<*, *, *>): PullRequestEventViewHolder {
return PullRequestEventViewHolder(getView(parent, R.layout.issue_timeline_row_item), adapter)
}
}
} | app/src/main/java/com/fastaccess/ui/adapter/viewholder/PullRequestEventViewHolder.kt | 2849064759 |
package de.gymdon.inf1315.game.tile
data class Tile(val id: Int, val name: String, val groundFactor: Double = 1.0) {
val isWalkable: Boolean
get() = groundFactor != Double.POSITIVE_INFINITY
companion object {
val grass = Tile(0, "grass", 1.0)
val grass2 = Tile(0, "grass", 1.0)
val sand = Tile(1, "sand", 2.0)
val sand2 = Tile(1, "sand", 2.0)
val water = Tile(2, "water", Double.POSITIVE_INFINITY)
val water2 = Tile(2, "water", Double.POSITIVE_INFINITY)
}
}
| Game Commons/src/de/gymdon/inf1315/game/tile/Tile.kt | 479706423 |
package com.infinum.dbinspector.data.models.local.cursor.output
import com.infinum.dbinspector.data.models.local.proto.output.SettingsEntity
internal data class Field(
val type: FieldType,
val text: String? = null,
val blob: ByteArray? = null,
val linesCount: Int = Int.MAX_VALUE,
val truncate: SettingsEntity.TruncateMode = SettingsEntity.TruncateMode.UNRECOGNIZED,
val blobPreview: SettingsEntity.BlobPreviewMode = SettingsEntity.BlobPreviewMode.UNRECOGNIZED
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Field
if (type != other.type) return false
if (text != other.text) return false
if (blob != null) {
if (other.blob == null) return false
if (!blob.contentEquals(other.blob)) return false
} else if (other.blob != null) return false
if (linesCount != other.linesCount) return false
if (truncate != other.truncate) return false
if (blobPreview != other.blobPreview) return false
return true
}
override fun hashCode(): Int {
var result = type.hashCode()
result = 31 * result + (text?.hashCode() ?: 0)
result = 31 * result + (blob?.contentHashCode() ?: 0)
result = 31 * result + linesCount
result = 31 * result + truncate.hashCode()
result = 31 * result + blobPreview.hashCode()
return result
}
}
| dbinspector/src/main/kotlin/com/infinum/dbinspector/data/models/local/cursor/output/Field.kt | 1535398020 |
/*
* Copyright (c) 2020 Arthur Milchior <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.libanki
import android.annotation.SuppressLint
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.RobolectricTest
import com.ichi2.libanki.Decks.Companion.CURRENT_DECK
import com.ichi2.libanki.backend.exception.DeckRenameException
import com.ichi2.testutils.AnkiAssert.assertDoesNotThrow
import com.ichi2.testutils.AnkiAssert.assertEqualsArrayList
import org.apache.http.util.Asserts
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.test.assertNotNull
import kotlin.test.assertNull
@RunWith(AndroidJUnit4::class)
class DecksTest : RobolectricTest() {
@Test
@Suppress("SpellCheckingInspection")
fun ensureDeckList() {
val decks = col.decks
for (deckName in TEST_DECKS) {
addDeck(deckName)
}
val brokenDeck = decks.byName("cmxieunwoogyxsctnjmv::INSBGDS")
Asserts.notNull(brokenDeck, "We should get deck with given name")
// Changing the case. That could exists in an old collection or during sync.
brokenDeck!!.put("name", "CMXIEUNWOOGYXSCTNJMV::INSBGDS")
decks.save(brokenDeck)
decks.childMap()
for (deck in decks.all()) {
val did = deck.getLong("id")
for (parent in decks.parents(did)) {
Asserts.notNull(parent, "Parent should not be null")
}
}
}
@Test
fun trim() {
assertThat(Decks.strip("A\nB C\t D"), equalTo("A\nB C\t D"))
assertThat(Decks.strip("\n A\n\t"), equalTo("A"))
assertThat(Decks.strip("Z::\n A\n\t::Y"), equalTo("Z::A::Y"))
}
/******************
* autogenerated from https://github.com/ankitects/anki/blob/2c73dcb2e547c44d9e02c20a00f3c52419dc277b/pylib/tests/test_cards.py*
*/
@Test
fun test_basic() {
val col = col
val decks = col.decks
// we start with a standard col
assertEquals(1, decks.allSortedNames().size.toLong())
// it should have an id of 1
assertNotNull(decks.name(1))
// create a new col
val parentId = addDeck("new deck")
assertNotEquals(parentId, 0)
assertEquals(2, decks.allSortedNames().size.toLong())
// should get the same id
assertEquals(parentId, addDeck("new deck"))
// we start with the default col selected
assertEquals(1, decks.selected())
assertEqualsArrayList(arrayOf(1L), decks.active())
// we can select a different col
decks.select(parentId)
assertEquals(parentId, decks.selected())
assertEqualsArrayList(arrayOf(parentId), decks.active())
// let's create a child
val childId = addDeck("new deck::child")
col.reset()
// it should have been added to the active list
assertEquals(parentId, decks.selected())
assertEqualsArrayList(arrayOf(parentId, childId), decks.active())
// we can select the child individually too
decks.select(childId)
assertEquals(childId, decks.selected())
assertEqualsArrayList(arrayOf(childId), decks.active())
// parents with a different case should be handled correctly
addDeck("ONE")
val m = col.models.current()
m!!.put("did", addDeck("one::two"))
col.models.save(m, false)
val n = col.newNote()
n.setItem("Front", "abc")
col.addNote(n)
assertEquals(decks.id_for_name("new deck")!!.toLong(), parentId)
assertEquals(decks.id_for_name(" New Deck ")!!.toLong(), parentId)
assertNull(decks.id_for_name("Not existing deck"))
assertNull(decks.id_for_name("new deck::not either"))
}
@Test
fun test_remove() {
val col = col
// create a new col, and add a note/card to it
val deck1 = addDeck("deck1")
val note = col.newNote()
note.setItem("Front", "1")
note.model().put("did", deck1)
col.addNote(note)
val c = note.cards()[0]
assertEquals(deck1, c.did)
assertEquals(1, col.cardCount().toLong())
col.decks.rem(deck1)
assertEquals(0, col.cardCount().toLong())
// if we try to get it, we get the default
assertEquals("[no deck]", col.decks.name(c.did))
}
@Test
@SuppressLint("CheckResult")
@Throws(DeckRenameException::class)
fun test_rename() {
val col = col
var id = addDeck("hello::world")
// should be able to rename into a completely different branch, creating
// parents as necessary
val decks = col.decks
decks.rename(decks.get(id), "foo::bar")
var names: List<String?> = decks.allSortedNames()
assertTrue(names.contains("foo"))
assertTrue(names.contains("foo::bar"))
assertFalse(names.contains("hello::world"))
// create another col
/* TODO: do we want to follow upstream here ?
// automatically adjusted if a duplicate name
decks.rename(decks.get(id), "FOO");
names = decks.allSortedNames();
assertThat(names, containsString("FOO+"));
*/
// when renaming, the children should be renamed too
addDeck("one::two::three")
id = addDeck("one")
col.decks.rename(col.decks.get(id), "yo")
names = col.decks.allSortedNames()
for (n in arrayOf("yo", "yo::two", "yo::two::three")) {
assertTrue(names.contains(n))
}
// over filtered
val filteredId = addDynamicDeck("filtered")
col.decks.get(filteredId)
val childId = addDeck("child")
val child = col.decks.get(childId)
assertThrows(DeckRenameException::class.java) {
col.decks.rename(
child,
"filtered::child"
)
}
assertThrows(DeckRenameException::class.java) {
col.decks.rename(
child,
"FILTERED::child"
)
}
}
/* TODO: maybe implement. We don't drag and drop here anyway, so buggy implementation is okay
@Test public void test_renameForDragAndDrop() throws DeckRenameException {
// TODO: upstream does not return "default", remove it
Collection col = getCol();
long languages_did = addDeck("Languages");
long chinese_did = addDeck("Chinese");
long hsk_did = addDeck("Chinese::HSK");
// Renaming also renames children
col.getDecks().renameForDragAndDrop(chinese_did, languages_did);
assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::Chinese::HSK"}, col.getDecks().allSortedNames());
// Dragging a col onto itself is a no-op
col.getDecks().renameForDragAndDrop(languages_did, languages_did);
assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::Chinese::HSK"}, col.getDecks().allSortedNames());
// Dragging a col onto its parent is a no-op
col.getDecks().renameForDragAndDrop(hsk_did, chinese_did);
assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::Chinese::HSK"}, col.getDecks().allSortedNames());
// Dragging a col onto a descendant is a no-op
col.getDecks().renameForDragAndDrop(languages_did, hsk_did);
// TODO: real problem to correct, even if we don't have drag and drop
// assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::Chinese::HSK"}, col.getDecks().allSortedNames());
// Can drag a grandchild onto its grandparent. It becomes a child
col.getDecks().renameForDragAndDrop(hsk_did, languages_did);
assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::HSK"}, col.getDecks().allSortedNames());
// Can drag a col onto its sibling
col.getDecks().renameForDragAndDrop(hsk_did, chinese_did);
assertEqualsArrayList(new String [] {"Default", "Languages", "Languages::Chinese", "Languages::Chinese::HSK"}, col.getDecks().allSortedNames());
// Can drag a col back to the top level
col.getDecks().renameForDragAndDrop(chinese_did, null);
assertEqualsArrayList(new String [] {"Default", "Chinese", "Chinese::HSK", "Languages"}, col.getDecks().allSortedNames());
// Dragging a top level col to the top level is a no-op
col.getDecks().renameForDragAndDrop(chinese_did, null);
assertEqualsArrayList(new String [] {"Default", "Chinese", "Chinese::HSK", "Languages"}, col.getDecks().allSortedNames());
// decks are renamed if necessary«
long new_hsk_did = addDeck("hsk");
col.getDecks().renameForDragAndDrop(new_hsk_did, chinese_did);
assertEqualsArrayList(new String [] {"Default", "Chinese", "Chinese::HSK", "Chinese::hsk+", "Languages"}, col.getDecks().allSortedNames());
col.getDecks().rem(new_hsk_did);
}
*/
@Test
fun curDeckIsLong() {
// Regression for #8092
val col = col
val decks = col.decks
val id = addDeck("test")
decks.select(id)
assertDoesNotThrow("curDeck should be saved as a long. A deck id.") {
col.get_config_long(
CURRENT_DECK
)
}
}
@Test
fun isDynStd() {
val col = col
val decks = col.decks
val filteredId = addDynamicDeck("filtered")
val filtered = decks.get(filteredId)
val deckId = addDeck("deck")
val deck = decks.get(deckId)
assertThat(deck.isStd, equalTo(true))
assertThat(deck.isDyn, equalTo(false))
assertThat(filtered.isStd, equalTo(false))
assertThat(filtered.isDyn, equalTo(true))
val filteredConfig = decks.confForDid(filteredId)
val deckConfig = decks.confForDid(deckId)
assertThat(deckConfig.isStd, equalTo((true)))
assertThat(deckConfig.isDyn, equalTo((false)))
assertThat(filteredConfig.isStd, equalTo((false)))
assertThat(filteredConfig.isDyn, equalTo((true)))
}
@Test
fun confForDidReturnsDefaultIfNotFound() {
// https://github.com/ankitects/anki/commit/94d369db18c2a6ac3b0614498d8abcc7db538633
val decks = col.decks
val d = decks.all()[0]
d.put("conf", 12L)
decks.save()
val config = decks.confForDid(d.getLong("id"))
assertThat(
"If a config is not found, return the default",
config.getLong("id"),
equalTo(1L)
)
}
companion object {
// Used in other class to populate decks.
@Suppress("SpellCheckingInspection")
val TEST_DECKS = arrayOf(
"scxipjiyozczaaczoawo",
"cmxieunwoogyxsctnjmv::abcdefgh::ZYXW",
"cmxieunwoogyxsctnjmv::INSBGDS",
"::foobar", // Addition test for issue #11026
"A::"
)
}
}
| AnkiDroid/src/test/java/com/ichi2/libanki/DecksTest.kt | 1127853523 |
/*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.ui.components
import android.app.Activity
import android.app.DatePickerDialog
import android.support.annotation.IdRes
import android.support.annotation.StringRes
import android.support.v4.content.ContextCompat
import android.widget.DatePicker
import android.widget.TextView
import co.timetableapp.R
import co.timetableapp.util.DateUtils
import org.threeten.bp.LocalDate
/**
* A helper class for setting up a [TextView] to show and change the date.
*/
class DateSelectorHelper(val activity: Activity, @IdRes val textViewResId: Int) {
private val mTextView = activity.findViewById(textViewResId) as TextView
private var mDate: LocalDate? = null
/**
* Sets up this helper class, displaying the date and preparing actions for when the
* [TextView] is clicked.
*
* @param initialDate the date to initially display on the [TextView]. This can be null, in
* which case a hint text will be initially displayed.
* @param onDateSet a function to be invoked when the date has been changed
*/
fun setup(initialDate: LocalDate?,
onDateSet: (view: DatePicker, date: LocalDate) -> Unit) {
mDate = initialDate
updateDateText()
setupOnClick(onDateSet)
}
private fun setupOnClick(onDateSet: (DatePicker, LocalDate) -> Unit) = mTextView.setOnClickListener {
// N.B. month-1 and month+1 in code because Android month values are from 0-11 (to
// correspond with java.util.Calendar) but LocalDate month values are from 1-12.
val listener = DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
onDateSet.invoke(view, LocalDate.of(year, month + 1, dayOfMonth))
}
val displayedDate = mDate ?: LocalDate.now()
DatePickerDialog(
activity,
listener,
displayedDate.year,
displayedDate.monthValue - 1,
displayedDate.dayOfMonth
).show()
}
/**
* Updates the displayed text according to the [date].
*
* @param date used to update the displayed text. This can be null, in which case a
* 'hint' text is shown.
* @param hintTextRes the string resource used to display the hint text
*/
@JvmOverloads
fun updateDate(date: LocalDate?, @StringRes hintTextRes: Int = R.string.property_date) {
mDate = date
updateDateText(hintTextRes)
}
private fun updateDateText(@StringRes hintTextRes: Int = R.string.property_date) {
val date = mDate
if (date == null) {
mTextView.text = activity.getString(hintTextRes)
mTextView.setTextColor(ContextCompat.getColor(activity, R.color.mdu_text_black_secondary))
} else {
mTextView.text = date.format(DateUtils.FORMATTER_FULL_DATE)
mTextView.setTextColor(ContextCompat.getColor(activity, R.color.mdu_text_black))
}
}
}
| app/src/main/java/co/timetableapp/ui/components/DateSelectorHelper.kt | 1503649913 |
/*
* (C) Copyright 2014 mjahnen <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package me.jahnen.libaums.core.driver.scsi.commands
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.experimental.and
/**
* This class represents the response of a SCSI Inquiry. It holds various
* information about the mass storage device.
*
*
* This response is received in the data phase.
*
* @author mjahnen
* @see com.github.mjdev.libaums.driver.scsi.commands.ScsiInquiry
*/
class ScsiInquiryResponse private constructor() {
/**
*
* @return Zero if a device is connected to the unit.
*/
var peripheralQualifier: Byte = 0
private set
/**
* The type of the mass storage device.
*
* @return Zero for a direct access block device.
*/
var peripheralDeviceType: Byte = 0
private set
/**
*
* @return True if the media can be removed (eg. card reader).
*/
var isRemovableMedia: Boolean = false
internal set
/**
* This method returns the version of the SCSI Primary Commands (SPC)
* standard the device supports.
*
* @return Version of the SPC standard
*/
var spcVersion: Byte = 0
internal set
var responseDataFormat: Byte = 0
internal set
override fun toString(): String {
return ("ScsiInquiryResponse [peripheralQualifier=" + peripheralQualifier
+ ", peripheralDeviceType=" + peripheralDeviceType + ", removableMedia="
+ isRemovableMedia + ", spcVersion=" + spcVersion + ", responseDataFormat="
+ responseDataFormat + "]")
}
companion object {
/**
* Constructs a new object with the given data.
*
* @param buffer
* The data where the [.ScsiInquiryResponse] is located.
* @return The parsed [.ScsiInquiryResponse].
*/
fun read(buffer: ByteBuffer): ScsiInquiryResponse {
buffer.order(ByteOrder.LITTLE_ENDIAN)
val b = buffer.get()
return ScsiInquiryResponse().apply {
peripheralQualifier = b and 0xe0.toByte()
peripheralDeviceType = b and 0x1f.toByte()
isRemovableMedia = buffer.get().toInt() == 0x80
spcVersion = buffer.get()
responseDataFormat = buffer.get() and 0x7.toByte()
}
}
}
}
| libaums/src/main/java/me/jahnen/libaums/core/driver/scsi/commands/ScsiInquiryResponse.kt | 742083859 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.data
import org.spongepowered.api.data.DataHolder
import org.spongepowered.api.data.DataProvider
import org.spongepowered.api.data.DataTransactionResult
import org.spongepowered.api.data.Key
import org.spongepowered.api.data.value.Value
import java.util.Optional
interface IDataProvider<V : Value<E>, E : Any> : DataProvider<V, E> {
override fun getKey(): Key<V>
override fun isSupported(container: DataHolder): Boolean
override fun allowsAsynchronousAccess(container: DataHolder): Boolean
@JvmDefault
override fun getValue(container: DataHolder): Optional<V> = super.getValue(container)
override fun get(container: DataHolder): Optional<E>
override fun offer(container: DataHolder.Mutable, element: E): DataTransactionResult
@JvmDefault
fun offerFast(container: DataHolder.Mutable, element: E) = offer(container, element).isSuccessful
@JvmDefault
override fun offerValue(container: DataHolder.Mutable, value: V): DataTransactionResult = super.offerValue(container, value)
@JvmDefault
fun offerValueFast(container: DataHolder.Mutable, value: V) = offerValue(container, value).isSuccessful
override fun remove(container: DataHolder.Mutable): DataTransactionResult
@JvmDefault
fun removeFast(container: DataHolder.Mutable) = remove(container).isSuccessful
override fun <I : DataHolder.Immutable<I>> with(immutable: I, element: E): Optional<I>
@JvmDefault
override fun <I : DataHolder.Immutable<I>> withValue(immutable: I, value: V): Optional<I> = super.withValue(immutable, value)
override fun <I : DataHolder.Immutable<I>> without(immutable: I): Optional<I>
}
| src/main/kotlin/org/lanternpowered/server/data/IDataProvider.kt | 2978158508 |
/**
* Copyright (C) 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.playbilling.trivialdrive.kotlin
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.trivialdrive.R
/**
* This Fragment is simply a wrapper for the inventory (i.e. items for sale). It contains two
* [lists][RecyclerView], one for subscriptions and one for in-app products. Here again there is
* no complicated billing logic. All the billing logic reside inside the [BillingRepository].
* The [BillingRepository] provides a [AugmentedSkuDetails] object that shows what
* is for sale and whether the user is allowed to buy the item at this moment. E.g. if the user
* already has a full tank of gas, then they cannot buy gas at this moment.
*/
class MakePurchaseFragment : Fragment() {
val LOG_TAG = "MakePurchaseFragment"
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.fragment_make_purchase, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.d(LOG_TAG, "onViewCreated")
}
}
| codelab-00/app/src/main/java/com/example/playbilling/trivialdrive/kotlin/MakePurchaseFragment.kt | 1946160591 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.play
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientPlayerMovementPacket
object ClientPlayerMovementDecoder : PacketDecoder<ClientPlayerMovementPacket> {
override fun decode(ctx: CodecContext, buf: ByteBuffer): ClientPlayerMovementPacket {
val position = buf.readVector3d()
val onGround = buf.readBoolean()
return ClientPlayerMovementPacket(position, onGround)
}
}
| src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientPlayerMovementDecoder.kt | 4263021372 |
package com.mercadopago.android.px.internal.callbacks
import android.arch.lifecycle.MutableLiveData
import com.mercadopago.android.px.internal.viewmodel.PaymentModel
import com.mercadopago.android.px.model.Card
import com.mercadopago.android.px.model.PaymentRecovery
import com.mercadopago.android.px.model.exceptions.MercadoPagoError
import com.mercadopago.android.px.tracking.internal.model.Reason
internal class PaymentServiceEventHandler {
val paymentFinishedLiveData = MutableLiveData<Event<PaymentModel>>()
val requireCvvLiveData = MutableLiveData<Event<Pair<Card, Reason>>>()
val recoverInvalidEscLiveData = MutableLiveData<Event<PaymentRecovery>>()
val paymentErrorLiveData = MutableLiveData<Event<MercadoPagoError>>()
val visualPaymentLiveData = MutableLiveData<Event<Unit>>()
} | px-checkout/src/main/java/com/mercadopago/android/px/internal/callbacks/PaymentServiceEventHandler.kt | 2217318556 |
/*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.changelogs.ui.views
import android.content.Context
import android.support.v7.widget.AppCompatTextView
import android.util.AttributeSet
import com.thunderclouddev.changelogs.R
class TextViewWithResizableCompoundDrawable : AppCompatTextView {
private var mDrawableWidth: Int = 0
private var mDrawableHeight: Int = 0
constructor(context: Context) : super(context) {
init(context, null, 0, 0)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs, 0, 0)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(context, attrs, defStyleAttr, 0)
}
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public TextViewWithResizableCompoundDrawable(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
// super(context, attrs, defStyleAttr, defStyleRes);
// init(context, attrs, defStyleAttr, defStyleRes);
// }
private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) {
val array = context.obtainStyledAttributes(attrs, R.styleable.TextViewWithResizableCompoundDrawable, defStyleAttr, defStyleRes)
try {
mDrawableWidth = array.getDimensionPixelSize(R.styleable.TextViewWithResizableCompoundDrawable_compoundDrawableWidth, -1)
mDrawableHeight = array.getDimensionPixelSize(R.styleable.TextViewWithResizableCompoundDrawable_compoundDrawableHeight, -1)
} finally {
array.recycle()
}
if (mDrawableWidth > 0 || mDrawableHeight > 0) {
initCompoundDrawableSize()
}
}
private fun initCompoundDrawableSize() {
val drawables =
if (compoundDrawables.any { it != null })
compoundDrawables
else
compoundDrawablesRelative
for (drawable in drawables) {
if (drawable == null) {
continue
}
val realBounds = drawable.bounds
val scaleFactor = realBounds.height() / realBounds.width().toFloat()
var drawableWidth = realBounds.width().toFloat()
var drawableHeight = realBounds.height().toFloat()
if (mDrawableWidth > 0) {
// save scale factor of image
if (drawableWidth > mDrawableWidth) {
drawableWidth = mDrawableWidth.toFloat()
drawableHeight = drawableWidth * scaleFactor
}
}
if (mDrawableHeight > 0) {
// save scale factor of image
if (drawableHeight > mDrawableHeight) {
drawableHeight = mDrawableHeight.toFloat()
drawableWidth = drawableHeight / scaleFactor
}
}
realBounds.right = realBounds.left + Math.round(drawableWidth)
realBounds.bottom = realBounds.top + Math.round(drawableHeight)
drawable.bounds = realBounds
}
setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3])
}
}
| app/src/main/java/com/thunderclouddev/changelogs/ui/views/TextViewWithResizableCompoundDrawable.kt | 1199167769 |
package com.mercadopago.android.px.internal.core
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
class SessionIdInterceptor(private val sessionIdProvider: SessionIdProvider) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val request = originalRequest.newBuilder()
.header(SESSION_ID_HEADER, sessionIdProvider.sessionId)
.build()
return chain.proceed(request)
}
companion object {
private const val SESSION_ID_HEADER = "X-Session-Id"
}
} | px-services/src/main/java/com/mercadopago/android/px/internal/core/SessionIdInterceptor.kt | 4070822868 |
package net.simonvt.cathode.common.ui
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
@Suppress("UNCHECKED_CAST")
fun <T : Fragment> FragmentManager.instantiate(fragmentClass: Class<T>, args: Bundle? = null): T {
val fragment = fragmentFactory.instantiate(javaClass.classLoader!!, fragmentClass.name)
fragment.arguments = args
return fragment as T
}
| cathode-common/src/main/java/net/simonvt/cathode/common/ui/fragments.kt | 2683358066 |
/*
* Copyright (c) 2016. KESTI co, ltd
* 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 debop4k.core.retry
import debop4k.core.asyncs.ready
import nl.komponents.kovenant.Kovenant
import nl.komponents.kovenant.Promise
import nl.komponents.kovenant.deferred
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.util.concurrent.atomic.*
/**
* SyncRetryExecutorKotlinTest
* @author debop [email protected]
*/
class SyncRetryExecutorKotlinTest : AbstractRetryKotlinTest() {
private val executor: RetryExecutor = SyncRetryExecutor
@Test
fun shouldReturnPromiseWhenDoWithRetryCalled() {
// given
val mainThread = Thread.currentThread().name
val poolThread = AtomicReference<String>()
// when
val promise = executor.doWithRetry { ctx -> poolThread.set(Thread.currentThread().name) }
promise.get()
assertThat(poolThread.get()).isEqualTo(mainThread)
}
@Test
fun shouldWrapExceptionInPromiseRatherThanThrowingIt() {
val promise = executor.doWithRetry { ctx -> throw IllegalArgumentException(DON_T_PANIC) }
promise.ready()
assertThat(promise.isFailure()).isTrue()
assertThat(promise.getError())
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(DON_T_PANIC)
}
@Test
fun shouldReturnCompletedFutureWhenGetWithRetryCalled() {
//given
val mainThread = Thread.currentThread().name
//when
val promise = executor.getWithRetry { Thread.currentThread().name }
//then
assertThat(promise.get()).isEqualTo(mainThread)
}
@Test
fun shouldWrapExceptionInFutureRatherThanThrowingItInGetWithRetry() {
//given
val block = { throw IllegalArgumentException(DON_T_PANIC) }
val promise = executor.getWithRetry { ctx -> block() }
promise.ready()
assertThat(promise.isFailure()).isTrue()
assertThat(promise.getError())
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(DON_T_PANIC)
}
@Test
fun shouldReturnCompletedFutureWhenGetWithRetryCalledContext() {
//given
val mainThread = Thread.currentThread().name
//when
val promise = executor.getWithRetry { ctx -> Thread.currentThread().name }
//then
assertThat(promise.get()).isEqualTo(mainThread)
}
@Test
fun shouldWrapExceptionInFutureRatherThanThrowingItInGetWithRetryContext() {
//given
val block = { ctx: RetryContext -> throw IllegalArgumentException(DON_T_PANIC) }
val promise = executor.getWithRetry { block.invoke(it) }
promise.ready()
assertThat(promise.isFailure()).isTrue()
assertThat(promise.getError())
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(DON_T_PANIC)
}
@Test
fun shouldReturnCompletedFutureWhenGetWithRetryOnFutureCalled() {
//given
val mainThread = Thread.currentThread().name
//when
val result = executor.getFutureWithRetry { ctx -> Promise.of(Thread.currentThread().name) }
//then
assertThat(result.get()).isEqualTo(mainThread)
}
@Test
fun shouldWrapExceptionInFutureRatherThanThrowingItInGetWithRetryOnFuture() {
//given
val block = { ctx: RetryContext ->
val defer = deferred<String, Exception>(Kovenant.context)
defer.reject(IllegalArgumentException(DON_T_PANIC))
defer.promise
}
val promise = executor.getFutureWithRetry<String> { block(it) }
promise.ready()
assertThat(promise.isFailure()).isTrue()
assertThat(promise.getError())
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(DON_T_PANIC)
}
} | debop4k-core/src/test/kotlin/debop4k/core/retry/SyncRetryExecutorKotlinTest.kt | 3398038121 |
package com.andreapivetta.blu.ui.base.exception
/**
* Created by andrea on 15/05/16.
*/
class MvpViewNotAttachedException : RuntimeException(
"Please call Presenter.attachView(MvpView) before requesting data to the Presenter") | app/src/main/java/com/andreapivetta/blu/ui/base/exception/MvpViewNotAttachedException.kt | 2312264553 |
package com.gdgnantes.devfest.android.provider
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
internal class ScheduleDatabase(private val context: Context) :
SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_NAME = "schedule.db"
private const val DATABASE_VERSION = 1
}
object Tables {
const val ROOMS = "Rooms"
const val SESSIONS = "Sessions"
const val SESSIONS_SPEAKERS = "SessionsSpeakers"
const val SPEAKERS = "Speakers"
const val SESSIONS_LJ_ROOMS = "Sessions " +
"LEFT JOIN Rooms ON session_room_id = room_id"
const val SESSIONS_LJ_ROOMS_LJ_SESSIONS_SPEAKERS_J_SPEAKERS = "Sessions " +
"LEFT JOIN Rooms ON session_room_id = room_id " +
"LEFT JOIN SessionsSpeakers ON session_speaker_session_id = session_id " +
"LEFT JOIN Speakers ON session_speaker_speaker_id = speaker_id"
const val SESSIONS_SPEAKERS_J_SESSIONS_J_SPEAKERS_LJ_ROOMS = "SessionsSpeakers " +
"JOIN Sessions ON session_speaker_session_id = session_id " +
"JOIN Speakers ON session_speaker_speaker_id = speaker_id " +
"LEFT JOIN Rooms ON session_room_id = room_id"
}
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE ${Tables.ROOMS} (" +
"${ScheduleContract.Rooms.ROOM_ID} TEXT NOT NULL, " +
"${ScheduleContract.Rooms.ROOM_NAME} TEXT, " +
"UNIQUE (${ScheduleContract.Rooms.ROOM_ID}) ON CONFLICT REPLACE)")
db.execSQL("CREATE TABLE ${Tables.SESSIONS} (" +
"${ScheduleContract.Sessions.SESSION_ID} TEXT NOT NULL, " +
"${ScheduleContract.Sessions.SESSION_DESCRIPTION} TEXT, " +
"${ScheduleContract.Sessions.SESSION_END_TIMESTAMP} INTEGER, " +
"${ScheduleContract.Sessions.SESSION_LANGUAGE} TEXT, " +
"${ScheduleContract.Sessions.SESSION_ROOM_ID} TEXT, " +
"${ScheduleContract.Sessions.SESSION_START_TIMESTAMP} INTEGER, " +
"${ScheduleContract.Sessions.SESSION_TITLE} TEXT, " +
"${ScheduleContract.Sessions.SESSION_TRACK} TEXT, " +
"${ScheduleContract.Sessions.SESSION_TYPE} TEXT, " +
"UNIQUE (${ScheduleContract.Sessions.SESSION_ID}) ON CONFLICT REPLACE)")
db.execSQL("CREATE TABLE ${Tables.SESSIONS_SPEAKERS} (" +
"${ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SESSION_ID} TEXT NOT NULL, " +
"${ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SPEAKER_ID} TEXT NOT NULL, " +
"UNIQUE (" +
"${ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SESSION_ID}, " +
"${ScheduleContract.SessionsSpeakers.SESSION_SPEAKER_SPEAKER_ID}) " +
"ON CONFLICT REPLACE)")
db.execSQL("CREATE TABLE ${Tables.SPEAKERS} (" +
"${ScheduleContract.Speakers.SPEAKER_ID} TEXT NOT NULL, " +
"${ScheduleContract.Speakers.SPEAKER_BIO} TEXT, " +
"${ScheduleContract.Speakers.SPEAKER_COMPANY} TEXT, " +
"${ScheduleContract.Speakers.SPEAKER_NAME} TEXT, " +
"${ScheduleContract.Speakers.SPEAKER_PHOTO_URL} TEXT, " +
"${ScheduleContract.Speakers.SPEAKER_SOCIAL_LINKS} TEXT, " +
"UNIQUE (${ScheduleContract.Speakers.SPEAKER_ID}) ON CONFLICT REPLACE)")
ScheduleSeed(context).seed(db)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS ${Tables.ROOMS}")
db.execSQL("DROP TABLE IF EXISTS ${Tables.SESSIONS}")
db.execSQL("DROP TABLE IF EXISTS ${Tables.SESSIONS_SPEAKERS}")
db.execSQL("DROP TABLE IF EXISTS ${Tables.SPEAKERS}")
onCreate(db)
}
}
| app/src/main/kotlin/com/gdgnantes/devfest/android/provider/ScheduleDatabase.kt | 1938262660 |
package im.actor.bots.framework.persistence
import akka.util.Timeout
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import shardakka.keyvalue.SimpleKeyValueJava
import java.io.ByteArrayOutputStream
import java.util.concurrent.TimeUnit
fun <T> ServerKeyValue.setDataClass(key: String, obj: T?) {
if (obj == null) {
setStringValue(key, null)
} else {
val output = ByteArrayOutputStream()
val generator = jacksonObjectMapper().jsonFactory.createGenerator(output)
generator.writeObject(obj)
val str = String(output.toByteArray())
setStringValue(key, str)
}
}
inline fun <reified T: Any> ServerKeyValue.getDataClass(key: String): T? {
val str = getStringValue(key)
if (str == null) {
return null
} else {
return jacksonObjectMapper().readValue<T>(str)
}
}
fun <T> SimpleKeyValueJava<T>.get(key: String): T? {
val res = syncGet(key, Timeout.apply(10, TimeUnit.SECONDS))
if (res.isPresent) {
return res.get()
} else {
return null
}
} | actor-bots/src/main/java/im/actor/bots/framework/persistence/KotlinExtensions.kt | 306166754 |
package us.ihmc.aci.dspro.pcap
/**
* Created by gbenincasa on 11/1/17.
*/
interface Message {
/**
* Check whether this packet contains a particular protocol. This will cause
* the packet to examine all the containing packets to check whether they
* are indeed the protocol the user asked for, in which case a message of the
* requested protocol is returned.
* The message itself will be returned otherwise.
*/
fun getMessage(protocol: Protocol): Message
fun getType(): Protocol
} | src/main/kotlin/us/ihmc/aci/dspro/pcap/Message.kt | 2593249246 |
package net.ndrei.teslapoweredthingies.machines.powdermaker
import com.google.gson.JsonElement
import net.minecraft.client.Minecraft
import net.minecraft.init.Blocks
import net.minecraft.init.Items
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.item.crafting.IRecipe
import net.minecraft.util.JsonUtils
import net.minecraft.util.ResourceLocation
import net.minecraftforge.fml.common.discovery.ASMDataTable
import net.minecraftforge.fml.common.registry.GameRegistry
import net.minecraftforge.oredict.OreDictionary
import net.minecraftforge.registries.IForgeRegistry
import net.ndrei.teslacorelib.MaterialColors
import net.ndrei.teslacorelib.PowderRegistry
import net.ndrei.teslacorelib.TeslaCoreLib
import net.ndrei.teslacorelib.annotations.AutoRegisterRecipesHandler
import net.ndrei.teslacorelib.annotations.RegistryHandler
import net.ndrei.teslacorelib.config.readItemStack
import net.ndrei.teslacorelib.config.readItemStacks
import net.ndrei.teslacorelib.items.powders.ColoredPowderItem
import net.ndrei.teslacorelib.utils.copyWithSize
import net.ndrei.teslapoweredthingies.MOD_ID
import net.ndrei.teslapoweredthingies.common.*
import net.ndrei.teslapoweredthingies.config.readExtraRecipesFile
/**
* Created by CF on 2017-07-06.
*/
@RegistryHandler
object PowderMakerRegistry : BaseTeslaRegistry<PowderMakerRecipe>("powder_maker_recipes", PowderMakerRecipe::class.java) {
private val registeredDustNames = mutableListOf<String>()
private val registeredDusts = mutableListOf<ColoredPowderItem>()
override fun registerItems(asm : ASMDataTable, registry: IForgeRegistry<Item>) {
// get all ores
val ores = OreDictionary.getOreNames()
.filter { it.startsWith("ore") }
.map { it.substring(3) }
.filter { OreDictionary.doesOreNameExist("ingot$it") }
// register powder maker recipes
ores.forEach {
val dustName = "dust$it"
var hasDust = false
if (!OreDictionary.doesOreNameExist(dustName)) {
// look for an item with color
val color = MaterialColors.getColor(it)
if (color != null) {
val material = it.decapitalize()
PowderRegistry.addMaterial(it) { registry ->
val item = object: ColoredPowderItem(material, color, 0.0f, "ingot${material.capitalize()}") {}
registry.register(item)
item.registerRecipe { AutoRegisterRecipesHandler.registerRecipe(GameRegistry.findRegistry(IRecipe::class.java), it) }
if (TeslaCoreLib.isClientSide) {
item.registerRenderer()
registeredDusts.add(item)
}
OreDictionary.registerOre("dust${material.capitalize()}", item)
item
}
hasDust = true
}
} else {
hasDust = true
}
if (hasDust) {
this.registeredDustNames.add(it)
}
}
}
override fun registerRecipes(asm: ASMDataTable, registry: IForgeRegistry<IRecipe>) {
// register default recipes
// stones -> 75% gravel
listOf("stone", "cobblestone").forEach {
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, "ore_$it"),
OreDictionary.getOres(it).map { it.copyWithSize(1) },
listOf(SecondaryOutput(.75f, Blocks.GRAVEL))
))
}
listOf("stoneGranite", "stoneDiorite", "stoneAndesite").forEach {
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, "ore_$it"),
OreDictionary.getOres(it).map { it.copyWithSize(1) },
listOf(SecondaryOutput(.75f, Blocks.GRAVEL))
))
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, "ore_${it}Polished"),
OreDictionary.getOres("${it}Polished").map { it.copyWithSize(1) },
listOf(SecondaryOutput(.75f, Blocks.GRAVEL))
))
}
// vanilla default ore recipes
this.registerDefaultOreRecipe("coal")
this.registerDefaultOreRecipe("diamond")
this.registerDefaultOreRecipe("emerald")
this.registerDefaultOreRecipe("redstone")
this.registerDefaultOreRecipe("lapis")
// register dust recipes
this.registeredDustNames.forEach {
// register ingot -> dust
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, "ore_ingot$it"),
OreDictionary.getOres("ingot$it").map { it.copyWithSize(1) },
listOf(OreOutput("dust$it", 1))
))
// register ore -> dust
this.registerDefaultOreRecipe(it)
}
OreDictionary.getOreNames()
.filter { it.startsWith("ore") }
.map { it.substring(3) }
.filter { OreDictionary.doesOreNameExist("dust$it") }
.filter { key -> !this.hasRecipe { it.getPossibleInputs().any { OreDictionary.getOreIDs(it).contains(OreDictionary.getOreID("ore$key")) } } }
.forEach {
this.registerDefaultOreRecipe(it)
}
readExtraRecipesFile(PowderMakerBlock.registryName!!.path) { json ->
val inputs = json.readItemStacks("input_stack")
if (inputs.isNotEmpty() && json.has("outputs")) {
val secondary = json.getAsJsonArray("outputs").mapNotNull<JsonElement, SecondaryOutput> {
if (it.isJsonObject) {
val stack = it.asJsonObject.readItemStack() ?: return@mapNotNull null
val chance = JsonUtils.getFloat(it.asJsonObject, "chance", 1.0f)
if (chance > 0.0f) {
return@mapNotNull SecondaryOutput(Math.min(chance, 1.0f), stack)
}
}
return@mapNotNull null
}
if (secondary.isNotEmpty()) {
inputs.forEach {
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, it.item.registryName.toString().replace(':', '_')),
listOf(it), secondary))
}
}
}
}
}
override fun postInit(asm: ASMDataTable) {
if (this.registeredDusts.isNotEmpty() && TeslaCoreLib.isClientSide) {
this.registeredDusts.forEach {
Minecraft.getMinecraft().itemColors.registerItemColorHandler({ s: ItemStack, t: Int -> it.getColorFromItemStack(s, t) }, arrayOf<Item>(it))
}
this.registeredDusts.clear()
}
}
//#region default ore recipes
private val defaultOreRecipes = mutableMapOf<String, (input: ItemStack, isOre: Boolean) -> PowderMakerRecipe>()
private fun findDefaultOreRecipe(oreKey: String, input: ItemStack, isOre: Boolean): PowderMakerRecipe? {
return if (this.defaultOreRecipes.containsKey(oreKey)) {
this.defaultOreRecipes[oreKey]?.invoke(input, isOre)
}
else null
}
fun registerDefaultOreRecipe(oreKey: String, input: ItemStack, isOre: Boolean) {
val recipe = this.findDefaultOreRecipe(oreKey, input, isOre)
if ((recipe != null) && recipe.ensureValidOutputs().isNotEmpty()) {
this.addRecipe(recipe)
}
else if (recipe == null) {
this.addRecipe(PowderMakerRecipe(
ResourceLocation(MOD_ID, input.item.registryName.toString().replace(':', '_')),
listOf(input), mutableListOf<IRecipeOutput>().also { list ->
list.add(OreOutput("dust${oreKey.capitalize()}", 2))
if (isOre) {
list.add(SecondaryOutput(0.15f, Blocks.COBBLESTONE))
}
}))
}
}
private fun registerDefaultOreRecipe(oreKey: String) {
OreDictionary.getOres("ore${oreKey.capitalize()}").forEach { stack ->
this.registerDefaultOreRecipe(oreKey.decapitalize(), stack, true)
}
}
private fun addDefaultOreRecipe(key: String, vararg output: IRecipeOutput) {
this.addDefaultOreRecipe(key, "dust${key.capitalize()}", *output)
}
private fun addDefaultOreRecipe(key: String, primaryOutput: String, vararg output: IRecipeOutput) {
this.addDefaultOreRecipe(key, primaryOutput, 2, *output)
}
private fun addDefaultOreRecipe(key: String, primaryOutput: String, primaryOutputCount: Int, vararg output: IRecipeOutput) {
this.addDefaultOreRecipe(key, { it, ore ->
PowderMakerRecipe(
ResourceLocation(MOD_ID, it.item.registryName.toString().replace(':', '_')),
listOf(it), mutableListOf<IRecipeOutput>().also { list ->
list.add(OreOutput(primaryOutput, primaryOutputCount))
if (ore) {
list.add(SecondaryOutput(0.15f, Blocks.COBBLESTONE))
}
if (output.isNotEmpty()) {
list.addAll(output)
}
})
})
}
private fun addDefaultOreRecipe(key: String, builder: (input: ItemStack, isOre: Boolean) -> PowderMakerRecipe) {
this.defaultOreRecipes[key] = builder
}
init {
this.addDefaultOreRecipe("iron",
SecondaryOreOutput(0.05f, "dustTin", 1),
SecondaryOreOutput(0.1f, "dustNickel", 1))
this.addDefaultOreRecipe("gold")
this.addDefaultOreRecipe("copper",
SecondaryOreOutput(0.125f, "dustGold", 1))
this.addDefaultOreRecipe("tin")
this.addDefaultOreRecipe("silver",
SecondaryOreOutput(0.1f, "dustLead", 1))
this.addDefaultOreRecipe("lead",
SecondaryOreOutput(0.1f, "dustSilver", 1))
this.addDefaultOreRecipe("aluminum")
this.addDefaultOreRecipe("nickel",
SecondaryOreOutput(0.1f, "dustPlatinum", 1))
this.addDefaultOreRecipe("platinum")
this.addDefaultOreRecipe("iridium")
this.addDefaultOreRecipe("coal", { it, ore ->
PowderMakerRecipe(
ResourceLocation(MOD_ID, it.item.registryName.toString().replace(':', '_')),
listOf(it), mutableListOf<IRecipeOutput>().also { list ->
list.add(Output(ItemStack(Items.COAL, 5)))
if (ore) {
list.add(SecondaryOutput(0.15f, Blocks.COBBLESTONE))
}
})
})
this.addDefaultOreRecipe("diamond", "dustDiamond", 3)
this.addDefaultOreRecipe("emerald", "dustEmerald", 3)
this.addDefaultOreRecipe("redstone", "dustRedstone", 6)
this.addDefaultOreRecipe("lapis", "gemLapis", 5)
}
//#endregion
fun hasRecipe(stack: ItemStack) = this.hasRecipe { it.canProcess(stack) }
fun findRecipe(stack: ItemStack): PowderMakerRecipe? = this.findRecipe { it.canProcess(stack) }
}
| src/main/kotlin/net/ndrei/teslapoweredthingies/machines/powdermaker/PowderMakerRegistry.kt | 3473734684 |
package mati.minesweeper
import com.badlogic.gdx.Application.LOG_DEBUG
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.graphics.*
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
import com.badlogic.gdx.scenes.scene2d.InputListener
import mati.advancedgdx.AdvancedGame
import mati.advancedgdx.assets.FontLoader.FontLoaderParameter
import mati.advancedgdx.utils.isDesktop
import mati.minesweeper.board.Cell
import mati.minesweeper.screens.GameS
import mati.minesweeper.screens.NewGame
import mati.minesweeper.screens.StatsScreen
import mati.minesweeper.screens.Title
import mati.minesweeper.statistics.Statistics
import mati.minesweeper.statistics.Statistics.StatisticsSerializer
import java.security.MessageDigest
import kotlin.properties.Delegates
import kotlin.reflect.KClass
class Game(val cellInput: KClass<out InputListener>) : AdvancedGame() {
companion object Static {
var game: Game by Delegates.notNull<Game>()
var superDebug: Boolean by Delegates.notNull<Boolean>()
fun init(game: Game) {
this.game = game
superDebug = if (Gdx.files.local("debug").exists() &&
Gdx.files.local("debug").readString().substring(0, 2) == "on") {
val digest: MessageDigest = MessageDigest.getInstance("SHA-512")
val text = Gdx.files.local("debug").readString().substring(2)
digest.update(text.toByteArray())
val hasharr: ByteArray = digest.digest()
val sb: StringBuffer = StringBuffer()
for (i in hasharr.indices)
sb.append(Integer.toString((hasharr[i].toInt() and 0xff) + 0x100, 16).substring(1));
sb.toString() == "70620298b6ffda5a28a02eae45c3f07f930b6f6cbb41023134e86e160cb6b51290cbb03" +
"6db26bf750deb9d3c846737fccc3584543c84127056fbb6c574eb0b94"
} else false
}
}
var cursors: Array<Cursor> by Delegates.notNull<Array<Cursor>>()
var stats: Statistics by Delegates.notNull<Statistics>()
override fun create() {
Static.init(this)
super.create()
init(this)
Gdx.input.isCatchBackKey = true
Gdx.app.logLevel = LOG_DEBUG
prepare()
if (superDebug)
Gdx.gl.glClearColor(0.25f, 0f, 0f, 1f)
else
Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 1f)
}
private fun prepare() {
scrManager.add("Title", Title(this)).add("Game", GameS(this)).add("New", NewGame(this))
.add("Stats", StatsScreen(this))
astManager.queue("UbuntuBGen", "fonts/Ubuntu-B.ttf", FreeTypeFontGenerator::class)
.queue("UbuntuRGen", "fonts/Ubuntu-R.ttf", FreeTypeFontGenerator::class)
.queue("UbuntuMRGen", "fonts/UbuntuMono-R.ttf", FreeTypeFontGenerator::class)
.queue("Title", "TitleFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuBGen"]) {
it.size = 64
it.color = Color.YELLOW
it.borderColor = Color.BLACK
it.borderWidth = 5f
})
.queue("GeneralW", "GeneralFontW", BitmapFont::class, FontLoaderParameter(astManager["UbuntuRGen"]) {
it.size = 32
it.color = Color.WHITE
it.borderColor = Color.BLACK
it.borderWidth = 1f
})
.queue("GeneralB", "GeneralFontB", BitmapFont::class, FontLoaderParameter(astManager["UbuntuRGen"]) {
it.size = 32
it.color = Color.BLACK
it.borderColor = Color.WHITE
it.borderWidth = 1f
})
.queue("GeneralR", "GeneralFontR", BitmapFont::class, FontLoaderParameter(astManager["UbuntuRGen"]) {
it.size = 32
it.color = Color.RED
it.borderColor = Color.BLACK
it.borderWidth = 1f
})
.queue("WarningF", "WarningFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuRGen"]) {
it.size = 48
it.color = Color.WHITE
it.borderColor = Color.BLACK
it.borderWidth = 5f
})
.queue("TimerF", "TimerFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuMRGen"]) {
it.size = 24
it.color = Color.GOLD
it.borderColor = Color.WHITE
it.borderWidth = 0.5f
})
.queue("GameOverF", "GameOverFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuBGen"]) {
it.size = 32
it.color = Color.RED
it.borderColor = Color.BLACK
it.borderWidth = 1f
})
.queue("WinF", "WinFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuBGen"]) {
it.size = 32
it.color = Color.GREEN
it.borderColor = Color.WHITE
it.borderWidth = 1f
})
.queue("AndroidF", "AndroidFont", BitmapFont::class, FontLoaderParameter(astManager["UbuntuRGen"]) {
it.size = 16
it.color = Color.WHITE
})
.queue("ButtonUp", "GUI/ButtonUp.png", Texture::class)
.queue("ButtonDown", "GUI/ButtonDown.png", Texture::class)
.queue("ButtonLocked", "GUI/ButtonLocked.png", Texture::class)
.queue("CellUp", "game/CellUp.png", Texture::class)
.queue("CellDown", "game/CellDown.png", Texture::class)
.queue("CellOpen", "game/CellOpen.png", Texture::class)
.queue("N", "game/", ".png", Texture::class, 1, 7)
.queue("Mine", "game/Mine.png", Texture::class)
.queue("Mine1", "game/Mine1.png", Texture::class)
.queue("Flag", "game/Flag.png", Texture::class)
.queue("CursorBlue", "GUI/CursorBlue.png", Pixmap::class)
.queue("CursorRed", "GUI/CursorRed.png", Pixmap::class)
.queue("GUIb", "GUI/GUIb.png", Texture::class)
.queue("GUIt", "GUI/GUIt.png", Texture::class)
.queue("GUIl", "GUI/GUIl.png", Texture::class)
.queue("CamDD", "GUI/CamDownDown.png", Texture::class)
.queue("CamDU", "GUI/CamDownUp.png", Texture::class)
.queue("CamLD", "GUI/CamLeftDown.png", Texture::class)
.queue("CamLU", "GUI/CamLeftUp.png", Texture::class)
.queue("CamRD", "GUI/CamRightDown.png", Texture::class)
.queue("CamRU", "GUI/CamRightUp.png", Texture::class)
.queue("CamUD", "GUI/CamUpDown.png", Texture::class)
.queue("CamUU", "GUI/CamUpUp.png", Texture::class)
.queue("CamPU", "GUI/CamPlusUp.png", Texture::class)
.queue("CamPD", "GUI/CamPlusDown.png", Texture::class)
.queue("CamMU", "GUI/CamMinusUp.png", Texture::class)
.queue("CamMD", "GUI/CamMinusDown.png", Texture::class)
.queue("CamCU", "GUI/CamCenterUp.png", Texture::class)
.queue("CamCD", "GUI/CamCenterDown.png", Texture::class)
.queue("Dialog", "GUI/Dialog.png", Texture::class)
.queue("PauseUp", "GUI/PauseUp.png", Texture::class)
.queue("PauseDown", "GUI/PauseDown.png", Texture::class)
.queue("OpenS", "sounds/Open.ogg", Sound::class)
.queue("ExplosionS", "sounds/Explosion.ogg", Sound::class)
.queue("WinS", "sounds/Win.ogg", Sound::class)
.load {
if (isDesktop()) {
cursors = arrayOf(Gdx.graphics.newCursor(astManager["CursorBlue", Pixmap::class], 0, 0),
Gdx.graphics.newCursor(astManager["CursorRed", Pixmap::class], 0, 0))
Gdx.graphics.setCursor(cursors[0])
}
Cell.init(this)
scrManager.loadAll()
scrManager.change("Title")
if (ioManager.exists("stats")) stats = ioManager.load("stats", StatisticsSerializer::class)
else stats = Statistics()
if (!stats.cheated) {
stats.cheated = superDebug
stats.save()
}
}
}
override fun render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
super.render()
}
}
| core/src/kotlin/mati/minesweeper/Game.kt | 2156831389 |
/*****************************************************************************
* NetworkModel.kt
*****************************************************************************
* Copyright © 2018 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc.viewmodels.browser
import android.content.Context
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.videolan.vlc.ExternalMonitor
import org.videolan.tools.CoroutineContextProvider
import org.videolan.tools.NetworkMonitor
class NetworkModel(context: Context, url: String? = null, showHiddenFiles: Boolean, coroutineContextProvider: CoroutineContextProvider = CoroutineContextProvider()) : BrowserModel(context, url, TYPE_NETWORK, showHiddenFiles, true, coroutineContextProvider) {
init {
NetworkMonitor.getInstance(context).connectionFlow.onEach { if (it.connected) refresh() }.launchIn(viewModelScope)
}
class Factory(val context: Context, val url: String?, private val showHiddenFiles: Boolean): ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return NetworkModel(context.applicationContext, url, showHiddenFiles) as T
}
}
} | application/vlc-android/src/org/videolan/vlc/viewmodels/browser/NetworkModel.kt | 1501422442 |
/*
* 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 okio.Buffer
import okio.BufferedSink
import okio.ByteString
internal class DerWriter(sink: BufferedSink) {
/** A stack of buffers that will be concatenated once we know the length of each. */
private val stack = mutableListOf(sink)
/** Type hints scoped to the call stack, manipulated with [pushTypeHint] and [popTypeHint]. */
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>()
/**
* False unless we made a recursive call to [write] at the current stack frame. The explicit box
* adapter can clear this to synthesize non-constructed values that are embedded in octet strings.
*/
var constructed = false
fun write(name: String, tagClass: Int, tag: Long, block: (BufferedSink) -> Unit) {
val constructedBit: Int
val content = Buffer()
stack.add(content)
constructed = false // The enclosed object written in block() is not constructed.
path += name
try {
block(content)
constructedBit = if (constructed) 0b0010_0000 else 0
constructed = true // The enclosing object is constructed.
} finally {
stack.removeAt(stack.size - 1)
path.removeAt(path.size - 1)
}
val sink = sink()
// Write the tagClass, tag, and constructed bit. This takes 1 byte if tag is less than 31.
if (tag < 31) {
val byte0 = tagClass or constructedBit or tag.toInt()
sink.writeByte(byte0)
} else {
val byte0 = tagClass or constructedBit or 0b0001_1111
sink.writeByte(byte0)
writeVariableLengthLong(tag)
}
// Write the length. This takes 1 byte if length is less than 128.
val length = content.size
if (length < 128) {
sink.writeByte(length.toInt())
} else {
// count how many bytes we'll need to express the length.
val lengthBitCount = 64 - java.lang.Long.numberOfLeadingZeros(length)
val lengthByteCount = (lengthBitCount + 7) / 8
sink.writeByte(0b1000_0000 or lengthByteCount)
for (shift in (lengthByteCount - 1) * 8 downTo 0 step 8) {
sink.writeByte((length shr shift).toInt())
}
}
// Write the payload.
sink.writeAll(content)
}
/**
* 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)
}
}
private fun sink(): BufferedSink = stack[stack.size - 1]
fun writeBoolean(b: Boolean) {
sink().writeByte(if (b) -1 else 0)
}
fun writeBigInteger(value: BigInteger) {
sink().write(value.toByteArray())
}
fun writeLong(v: Long) {
val sink = sink()
val lengthBitCount: Int = if (v < 0L) {
65 - java.lang.Long.numberOfLeadingZeros(v xor -1L)
} else {
65 - java.lang.Long.numberOfLeadingZeros(v)
}
val lengthByteCount = (lengthBitCount + 7) / 8
for (shift in (lengthByteCount - 1) * 8 downTo 0 step 8) {
sink.writeByte((v shr shift).toInt())
}
}
fun writeBitString(bitString: BitString) {
val sink = sink()
sink.writeByte(bitString.unusedBitsCount)
sink.write(bitString.byteString)
}
fun writeOctetString(byteString: ByteString) {
sink().write(byteString)
}
fun writeUtf8(value: String) {
sink().writeUtf8(value)
}
fun writeObjectIdentifier(s: String) {
val utf8 = Buffer().writeUtf8(s)
val v1 = utf8.readDecimalLong()
require(utf8.readByte() == '.'.toByte())
val v2 = utf8.readDecimalLong()
writeVariableLengthLong(v1 * 40 + v2)
while (!utf8.exhausted()) {
require(utf8.readByte() == '.'.toByte())
val vN = utf8.readDecimalLong()
writeVariableLengthLong(vN)
}
}
fun writeRelativeObjectIdentifier(s: String) {
// Add a leading dot so each subidentifier has a dot prefix.
val utf8 = Buffer()
.writeByte('.'.toByte().toInt())
.writeUtf8(s)
while (!utf8.exhausted()) {
require(utf8.readByte() == '.'.toByte())
val vN = utf8.readDecimalLong()
writeVariableLengthLong(vN)
}
}
/** Used for tags and subidentifiers. */
private fun writeVariableLengthLong(v: Long) {
val sink = sink()
val bitCount = 64 - java.lang.Long.numberOfLeadingZeros(v)
val byteCount = (bitCount + 6) / 7
for (shift in (byteCount - 1) * 7 downTo 0 step 7) {
val lastBit = if (shift == 0) 0 else 0b1000_0000
sink.writeByte(((v shr shift) and 0b0111_1111).toInt() or lastBit)
}
}
override fun toString() = path.joinToString(separator = " / ")
}
| okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt | 2858600462 |
/*
* The MIT License (MIT)
*
* Copyright 2017 Miguel Panelo
*
* 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 io.github.gumil.basamto.navigation
import android.os.Bundle
import android.os.Parcelable
import io.github.gumil.basamto.common.BaseFragment
internal abstract class BaseKey: Parcelable {
open fun getFragmentTag(): String = javaClass.simpleName
fun newFragment(): BaseFragment {
return createFragment().apply {
arguments = (arguments ?: Bundle()).apply {
putParcelable("KEY", this@BaseKey)
}
}
}
abstract fun createFragment(): BaseFragment
} | app/src/main/kotlin/io/github/gumil/basamto/navigation/BaseKey.kt | 244814573 |
package org.videolan.resources.interfaces
interface FocusListener {
fun onFocusChanged(position: Int)
} | application/resources/src/main/java/org/videolan/resources/interfaces/FocusListener.kt | 2492596331 |
package tv.superawesome.demoapp.interaction
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.ViewInteraction
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.matcher.ViewMatchers.*
import tv.superawesome.demoapp.MainActivity
import tv.superawesome.demoapp.R
import tv.superawesome.demoapp.model.TestData
import tv.superawesome.demoapp.util.*
import tv.superawesome.demoapp.util.WireMockHelper.stubCommonPaths
import tv.superawesome.demoapp.util.WireMockHelper.stubFailure
import tv.superawesome.demoapp.util.WireMockHelper.stubSuccess
object CommonInteraction {
private fun launchActivityWithSuccessStub(
placement: String,
fileName: String,
settings: (() -> Unit)? = null
) {
stubCommonPaths()
stubSuccess(placement, fileName)
launchActivity<MainActivity>()
settings?.let {
SettingsInteraction.openSettings()
SettingsInteraction.commonSettings()
settings.invoke()
SettingsInteraction.closeSettings()
} ?: run {
SettingsInteraction.applyCommonSettings()
}
}
fun launchActivityWithSuccessStub(testData: TestData, settings: (() -> Unit)? = null) {
launchActivityWithSuccessStub(testData.placement, testData.fileName, settings)
}
fun launchActivityWithFailureStub(testData: TestData) {
launchActivityWithFailureStub(testData.placement)
}
private fun launchActivityWithFailureStub(placement: String) {
stubCommonPaths()
stubFailure(placement)
launchActivity<MainActivity>()
SettingsInteraction.applyCommonSettings()
}
private fun clickPlacementById(placementId: String) {
onData(AdapterUtil.withPlacementId(placementId)).inAdapterView(withId(R.id.listView))
.perform(click())
}
fun clickItemAt(testData: TestData) {
clickPlacementById(testData.placement)
}
fun checkSubtitleContains(text: String) {
onView(withId(R.id.subtitleTextView))
.perform(waitUntil(isDisplayed()))
.perform(waitUntil(withSubstring(text)))
}
fun waitForCloseButtonThenClick() {
ViewTester()
.waitForView(withContentDescription("Close"))
.perform(waitUntil(isDisplayed()))
.check(isVisible())
.perform(click())
}
fun waitForCloseButtonWithDelayThenClick() {
waitForCloseButtonWithDelay()
.perform(click())
}
fun waitForCloseButtonWithDelay(): ViewInteraction = ViewTester()
.waitForView(withContentDescription("Close"))
.check(isGone())
.perform(waitUntil(isDisplayed()))
.check(isVisible())
fun waitForAdContentThenClick() {
ViewTester()
.waitForView(withContentDescription("Ad content"))
.perform(waitUntil(isDisplayed()))
.perform(click())
}
fun waitForSafeAdLogoThenClick() {
ViewTester()
.waitForView(withContentDescription("Safe Ad Logo"))
.check(isVisible())
.perform(click())
}
fun waitAndCheckSafeAdLogo() {
ViewTester()
.waitForView(withContentDescription("Safe Ad Logo"))
.check(isVisible())
}
} | app/src/androidTest/java/tv/superawesome/demoapp/interaction/CommonInteraction.kt | 3917713246 |
package com.quickblox.sample.pushnotifications.kotlin.activities
import android.app.ProgressDialog
import android.content.DialogInterface
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import com.quickblox.sample.pushnotifications.kotlin.R
import com.quickblox.sample.pushnotifications.kotlin.utils.showSnackbar
abstract class BaseActivity : AppCompatActivity() {
private var progressDialog: ProgressDialog? = null
protected fun showProgressDialog(@StringRes messageId: Int) {
if (progressDialog == null) {
progressDialog = ProgressDialog(this)
progressDialog?.isIndeterminate = true
progressDialog?.setCancelable(false)
progressDialog?.setCanceledOnTouchOutside(false)
// disable the back button
val keyListener = DialogInterface.OnKeyListener { dialog, keyCode, event -> keyCode == KeyEvent.KEYCODE_BACK }
progressDialog?.setOnKeyListener(keyListener)
}
progressDialog?.setMessage(getString(messageId))
progressDialog?.show()
}
override fun onPause() {
super.onPause()
hideProgressDialog()
}
protected fun hideProgressDialog() {
if (progressDialog?.isShowing == true) {
progressDialog?.dismiss()
}
}
protected fun showErrorSnackbar(@StringRes resId: Int, e: Exception, clickListener: View.OnClickListener?) {
val rootView = window.decorView.findViewById<View>(android.R.id.content)
rootView?.let {
showSnackbar(it, resId, e, R.string.dlg_retry, clickListener)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
} | sample-pushnotifications-kotlin/app/src/main/java/com/quickblox/sample/pushnotifications/kotlin/activities/BaseActivity.kt | 2381723702 |
package jp.kentan.studentportalplus.data
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import jp.kentan.studentportalplus.data.component.LectureQuery
import jp.kentan.studentportalplus.data.component.NoticeQuery
import jp.kentan.studentportalplus.data.component.PortalData
import jp.kentan.studentportalplus.data.component.PortalDataSet
import jp.kentan.studentportalplus.data.dao.*
import jp.kentan.studentportalplus.data.model.*
import jp.kentan.studentportalplus.data.parser.LectureCancellationParser
import jp.kentan.studentportalplus.data.parser.LectureInformationParser
import jp.kentan.studentportalplus.data.parser.MyClassParser
import jp.kentan.studentportalplus.data.parser.NoticeParser
import jp.kentan.studentportalplus.data.shibboleth.ShibbolethClient
import jp.kentan.studentportalplus.data.shibboleth.ShibbolethDataProvider
import jp.kentan.studentportalplus.util.getSimilarSubjectThresholdFloat
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.jetbrains.anko.defaultSharedPreferences
class PortalRepository(
private val context: Context,
shibbolethDataProvider: ShibbolethDataProvider
) {
private val client = ShibbolethClient(context, shibbolethDataProvider)
private val similarSubjectThresholdListener: SharedPreferences.OnSharedPreferenceChangeListener
private val noticeParser = NoticeParser()
private val lectureInfoParser = LectureInformationParser()
private val lectureCancelParser = LectureCancellationParser()
private val myClassParser = MyClassParser()
private val noticeDao = NoticeDao(context.database)
private val lectureInfoDao: LectureInformationDao
private val lectureCancelDao: LectureCancellationDao
private val myClassDao = MyClassDao(context.database)
private val _portalDataSet = MutableLiveData<PortalDataSet>()
private val noticeList = MutableLiveData<List<Notice>>()
private val lectureInfoList = MutableLiveData<List<LectureInformation>>()
private val lectureCancelList = MutableLiveData<List<LectureCancellation>>()
private val _myClassList = MutableLiveData<List<MyClass>>()
val portalDataSet: LiveData<PortalDataSet>
get() = _portalDataSet
val myClassList: LiveData<List<MyClass>>
get() = _myClassList
val subjectList: LiveData<List<String>> by lazy {
return@lazy MediatorLiveData<List<String>>().apply {
addSource(lectureInfoList) { list ->
value = list.asSequence()
.map { it.subject }
.plus(value.orEmpty())
.distinct().toList()
}
addSource(lectureCancelList) { list ->
value = list.asSequence()
.map { it.subject }
.plus(value.orEmpty())
.distinct().toList()
}
addSource(_myClassList) { list ->
value = list.asSequence()
.map { it.subject }
.plus(value.orEmpty())
.distinct().toList()
}
}
}
init {
val threshold = context.defaultSharedPreferences.getSimilarSubjectThresholdFloat()
lectureInfoDao = LectureInformationDao(context.database, threshold)
lectureCancelDao = LectureCancellationDao(context.database, threshold)
similarSubjectThresholdListener = SharedPreferences.OnSharedPreferenceChangeListener { pref, key ->
if (key == "similar_subject_threshold") {
val th = pref.getSimilarSubjectThresholdFloat()
lectureInfoDao.similarThreshold = th
lectureCancelDao.similarThreshold = th
GlobalScope.launch {
postValues(
lectureInfoList = lectureInfoDao.getAll(),
lectureCancelList = lectureCancelDao.getAll()
)
}
}
}
context.defaultSharedPreferences.registerOnSharedPreferenceChangeListener(similarSubjectThresholdListener)
}
@Throws(Exception::class)
fun sync() = GlobalScope.async {
val noticeList = noticeParser.parse(PortalData.NOTICE.fetchDocument())
val lectureInfoList = lectureInfoParser.parse(PortalData.LECTURE_INFO.fetchDocument())
val lectureCancelList = lectureCancelParser.parse(PortalData.LECTURE_CANCEL.fetchDocument())
val myClassList = myClassParser.parse(PortalData.MY_CLASS.fetchDocument())
myClassDao.updateAll(myClassList)
val updatedNoticeList = noticeDao.updateAll(noticeList)
val updatedLectureInfoList = lectureInfoDao.updateAll(lectureInfoList)
val updatedLectureCancelList = lectureCancelDao.updateAll(lectureCancelList)
loadFromDb().await()
return@async mapOf(
PortalData.NOTICE to updatedNoticeList,
PortalData.LECTURE_INFO to updatedLectureInfoList,
PortalData.LECTURE_CANCEL to updatedLectureCancelList
)
}
fun loadFromDb() = GlobalScope.async {
postValues(
noticeList = noticeDao.getAll(),
lectureInfoList = lectureInfoDao.getAll(),
lectureCancelList = lectureCancelDao.getAll(),
myClassList = myClassDao.getAll()
)
}
fun getNoticeList(query: NoticeQuery): LiveData<List<Notice>> {
val result = MediatorLiveData<List<Notice>>()
result.addSource(noticeList) { list ->
GlobalScope.launch {
result.postValue(
list.filter { notice ->
if (query.isUnread && notice.isRead) {
return@filter false
}
if (query.isRead && !notice.isRead) {
return@filter false
}
if (query.isFavorite && !notice.isFavorite) {
return@filter false
}
if (query.dateRange != NoticeQuery.DateRange.ALL) {
return@filter notice.createdDate.time >= query.dateRange.time
}
if (query.keywordList.isNotEmpty()) {
return@filter query.keywordList.any { notice.title.contains(it, true) }
}
return@filter true
}
)
}
}
return result
}
fun getLectureInfoList(query: LectureQuery): LiveData<List<LectureInformation>> {
val result = MediatorLiveData<List<LectureInformation>>()
result.addSource(lectureInfoList) { list ->
GlobalScope.launch {
val filtered = list.filter { lecture ->
if (query.isUnread && lecture.isRead) {
return@filter false
}
if (query.isRead && !lecture.isRead) {
return@filter false
}
if (query.isAttend && !lecture.attend.isAttend()) {
return@filter false
}
if (query.keywordList.isNotEmpty()) {
return@filter query.keywordList.any {
lecture.subject.contains(it, true) || lecture.instructor.contains(it, true)
}
}
return@filter true
}
result.postValue(
if (query.order == LectureQuery.Order.ATTEND_CLASS) {
filtered.sortedBy { !it.attend.isAttend() }
} else {
filtered
}
)
}
}
return result
}
fun getLectureCancelList(query: LectureQuery): LiveData<List<LectureCancellation>> {
val result = MediatorLiveData<List<LectureCancellation>>()
result.addSource(lectureCancelList) { list ->
GlobalScope.launch {
val filtered = list.filter { lecture ->
if (query.isUnread && lecture.isRead) {
return@filter false
}
if (query.isRead && !lecture.isRead) {
return@filter false
}
if (query.isAttend && !lecture.attend.isAttend()) {
return@filter false
}
if (query.keywordList.isNotEmpty()) {
return@filter query.keywordList.any {
lecture.subject.contains(it, true) || lecture.instructor.contains(it, true)
}
}
return@filter true
}
result.postValue(
if (query.order == LectureQuery.Order.ATTEND_CLASS) {
filtered.sortedBy { !it.attend.isAttend() }
} else {
filtered
}
)
}
}
return result
}
fun getMyClassSubjectList() = myClassDao.getSubjectList()
fun getNotice(id: Long): LiveData<Notice> {
if (noticeList.value == null) {
loadFromDb()
}
return Transformations.map(noticeList) { list -> list.find { it.id == id } }
}
fun getLectureInfo(id: Long): LiveData<LectureInformation> {
if (lectureInfoList.value == null) {
loadFromDb()
}
return Transformations.map(lectureInfoList) { list -> list.find { it.id == id } }
}
fun getLectureCancel(id: Long): LiveData<LectureCancellation> {
if (lectureCancelList.value == null) {
loadFromDb()
}
return Transformations.map(lectureCancelList) { list -> list.find { it.id == id } }
}
fun getMyClass(id: Long, isAllowNullOnlyFirst: Boolean = false): LiveData<MyClass> {
val result = MediatorLiveData<MyClass>()
var isFirst = true
result.addSource(_myClassList) { list ->
val data = list.find { it.id == id }
if (!isAllowNullOnlyFirst || isFirst || data != null) {
result.value = data
}
isFirst = false
}
return result
}
fun getMyClassWithSync(id: Long) = _myClassList.value?.find { it.id == id }
fun updateNotice(data: Notice) = GlobalScope.async {
if (noticeDao.update(data) > 0) {
postValues(noticeList = noticeDao.getAll())
return@async true
}
return@async false
}
fun updateLectureInfo(data: LectureInformation) = GlobalScope.async {
if (lectureInfoDao.update(data) > 0) {
postValues(lectureInfoList = lectureInfoDao.getAll())
return@async true
}
return@async false
}
fun updateLectureCancel(data: LectureCancellation) = GlobalScope.async {
if (lectureCancelDao.update(data) > 0) {
postValues(lectureCancelList = lectureCancelDao.getAll())
return@async true
}
return@async false
}
fun updateMyClass(data: MyClass) = GlobalScope.async {
if (myClassDao.update(data) > 0) {
postValues(
myClassDao.getAll(),
lectureInfoDao.getAll(),
lectureCancelDao.getAll())
return@async true
}
return@async false
}
fun addMyClass(data: MyClass) = GlobalScope.async {
if (myClassDao.insert(listOf(data)) > 0) {
postValues(
myClassDao.getAll(),
lectureInfoDao.getAll(),
lectureCancelDao.getAll())
return@async true
}
return@async false
}
fun addToMyClass(data: Lecture) = GlobalScope.async {
try {
val list = myClassParser.parse(data)
myClassDao.insert(list)
} catch (e: Exception) {
Log.e("PortalRepository", "Failed to add to MyClass", e)
return@async false
}
postValues(
myClassDao.getAll(),
lectureInfoDao.getAll(),
lectureCancelDao.getAll()
)
return@async true
}
fun deleteFromMyClass(subject: String) = GlobalScope.async {
try {
myClassDao.delete(subject)
} catch (e: Exception) {
Log.e("PortalRepository", "Failed to delete from MyClass", e)
return@async false
}
postValues(
myClassDao.getAll(),
lectureInfoDao.getAll(),
lectureCancelDao.getAll()
)
return@async true
}
fun deleteAll() = GlobalScope.async {
val isSuccess = context.deleteDatabase(context.database.databaseName)
if (isSuccess) {
postValues(emptyList(), emptyList(), emptyList(), emptyList())
}
return@async isSuccess
}
private fun postValues(
myClassList: List<MyClass>? = null,
lectureInfoList: List<LectureInformation>? = null,
lectureCancelList: List<LectureCancellation>? = null,
noticeList: List<Notice>? = null
) {
var postCount = 0
var set = _portalDataSet.value ?: PortalDataSet()
if (myClassList != null) {
postCount++
this._myClassList.postValue(myClassList)
set = set.copy(myClassList = myClassList)
}
if (lectureInfoList != null) {
postCount++
this.lectureInfoList.postValue(lectureInfoList)
set = set.copy(lectureInfoList = lectureInfoList)
}
if (lectureCancelList != null) {
postCount++
this.lectureCancelList.postValue(lectureCancelList)
set = set.copy(lectureCancelList = lectureCancelList)
}
if (noticeList != null) {
postCount++
this.noticeList.postValue(noticeList)
set = set.copy(noticeList = noticeList)
}
if (postCount > 0 && _portalDataSet.value != set) {
_portalDataSet.postValue(set)
}
Log.d("PortalRepository", "posted $postCount lists")
}
private fun PortalData.fetchDocument() = client.fetch(url)
} | app/src/main/java/jp/kentan/studentportalplus/data/PortalRepository.kt | 4188587146 |
/*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge.load_management
import org.jitsi.config.JitsiConfig
import org.jitsi.metaconfig.config
import org.jitsi.metaconfig.from
import org.jitsi.utils.OrderedJsonObject
import org.jitsi.utils.logging2.cdebug
import org.jitsi.utils.logging2.cinfo
import org.jitsi.utils.logging2.createLogger
import org.jitsi.videobridge.Conference
import org.jitsi.videobridge.Endpoint
import org.jitsi.videobridge.JvbLastN
import java.lang.Integer.max
import java.time.Duration
import java.util.function.Supplier
/**
* A [JvbLoadReducer] which samples the amount of currently forwarded endpoints across
* the entire bridge and sets a bridge-wide last-n value (via [JvbLastN]) to a number
* less than that (based on [reductionScale]).
*/
class LastNReducer(
private val conferencesSupplier: Supplier<Collection<Conference>>,
private val jvbLastN: JvbLastN
) : JvbLoadReducer {
private val logger = createLogger()
private val reductionScale: Double by config(
"${JvbLoadReducer.CONFIG_BASE}.last-n.reduction-scale".from(JitsiConfig.newConfig)
)
private val recoverScale: Double by config(
"${JvbLoadReducer.CONFIG_BASE}.last-n.recover-scale".from(JitsiConfig.newConfig)
)
private val impactTime: Duration by config(
"${JvbLoadReducer.CONFIG_BASE}.last-n.impact-time".from(JitsiConfig.newConfig)
)
private val minLastN: Int by config(
"${JvbLoadReducer.CONFIG_BASE}.last-n.minimum-last-n-value".from(JitsiConfig.newConfig)
)
private val maxEnforcedLastN: Int by config(
"${JvbLoadReducer.CONFIG_BASE}.last-n.maximum-enforced-last-n-value".from(JitsiConfig.newConfig)
)
init {
logger.cinfo { this.toString() }
}
private fun getMaxForwardedEps(): Int? {
return conferencesSupplier.get()
.flatMap { it.endpoints }
.asSequence()
.filterIsInstance<Endpoint>()
.map {
it.numForwardedEndpoints()
}
.maxOrNull()
}
override fun reduceLoad() {
// Find the highest amount of endpoints any endpoint on this bridge is forwarding video for
// so we can set a new last-n number to something lower
val maxForwardedEps = getMaxForwardedEps() ?: run {
logger.info("No endpoints with video being forwarded, can't reduce load by reducing last n")
return
}
val newLastN = max(minLastN, (maxForwardedEps * reductionScale).toInt())
logger.info(
"Largest number of forwarded videos was $maxForwardedEps, A last-n value of $newLastN is " +
"being enforced to reduce bridge load"
)
jvbLastN.jvbLastN = newLastN
}
override fun recover(): Boolean {
val currLastN = jvbLastN.jvbLastN
if (currLastN == -1) {
logger.cdebug { "No recovery necessary, no JVB last-n is set" }
return false
}
// We want to make sure the last-n value increases by at least 1
val newLastN = maxOf(currLastN + 1, (currLastN * recoverScale).toInt())
if (newLastN >= maxEnforcedLastN) {
logger.info(
"JVB last-n was $currLastN, increasing to $newLastN which is beyond the max enforced value" +
"of $maxEnforcedLastN, removing limit completely"
)
jvbLastN.jvbLastN = -1
} else {
logger.info("JVB last-n was $currLastN, increasing to $newLastN as part of load recovery")
jvbLastN.jvbLastN = newLastN
}
return true
}
override fun impactTime(): Duration = impactTime
override fun getStats() = OrderedJsonObject().apply {
put("jvbLastN", jvbLastN.jvbLastN)
}
override fun toString(): String = buildString {
append("LastNReducer with")
append(" reductionScale: $reductionScale")
append(" recoverScale: $recoverScale")
append(" impactTime: $impactTime")
append(" minLastN: $minLastN")
append(" maxEnforcedLastN: $maxEnforcedLastN")
}
}
| jvb/src/main/kotlin/org/jitsi/videobridge/load_management/LastNReducer.kt | 1284603711 |
package com.sandjelkovic.dispatchd.content.trakt.converter
import com.sandjelkovic.dispatchd.content.data.entity.Season
import com.sandjelkovic.dispatchd.content.trakt.dto.SeasonTrakt
import org.springframework.core.convert.converter.Converter
/**
* @author sandjelkovic
* @date 14.4.18.
*/
class Trakt2SeasonConverter : Converter<SeasonTrakt, Season> {
override fun convert(source: SeasonTrakt): Season = Season().apply {
number = source.number
description = source.overview ?: ""
airDate = source.firstAired
episodesCount = source.episodeCount ?: 0
episodesAiredCount = source.airedEpisodes
traktId = source.ids.getOrDefault("trakt", "")
imdbId = source.ids.getOrDefault("imdb", "")
tvdbId = source.ids.getOrDefault("tvdb", "")
}
}
| content-service/src/main/kotlin/com/sandjelkovic/dispatchd/content/trakt/converter/Trakt2SeasonConverter.kt | 3817296485 |
package io.gitlab.arturbosch.detekt.core.baseline
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.api.ReportingExtension
import io.gitlab.arturbosch.detekt.api.RuleSetId
import io.gitlab.arturbosch.detekt.api.SetupContext
import io.gitlab.arturbosch.detekt.api.UnstableApi
import io.gitlab.arturbosch.detekt.api.getOrNull
import io.gitlab.arturbosch.detekt.core.DetektResult
import java.nio.file.Path
@OptIn(UnstableApi::class)
class BaselineResultMapping : ReportingExtension {
private var baselineFile: Path? = null
private var createBaseline: Boolean = false
override fun init(context: SetupContext) {
baselineFile = context.getOrNull(DETEKT_BASELINE_PATH_KEY)
createBaseline = context.getOrNull(DETEKT_BASELINE_CREATION_KEY) ?: false
}
override fun transformFindings(findings: Map<RuleSetId, List<Finding>>): Map<RuleSetId, List<Finding>> {
val baselineFile = baselineFile
require(!createBaseline || (createBaseline && baselineFile != null)) {
"Invalid baseline options invariant."
}
return baselineFile?.let { findings.transformWithBaseline(it) } ?: findings
}
private fun Map<RuleSetId, List<Finding>>.transformWithBaseline(baselinePath: Path): Map<RuleSetId, List<Finding>> {
val facade = BaselineFacade()
val flatten = this.flatMap { it.value }
if (flatten.isEmpty()) {
return this
}
if (createBaseline) {
facade.createOrUpdate(baselinePath, flatten)
}
return facade.transformResult(baselinePath, DetektResult(this)).findings
}
}
| detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/baseline/BaselineResultMapping.kt | 1508583544 |
package net.nemerosa.ontrack.git.model.plot
interface GItem {
val type: String
val maxX: Int
val maxY: Int
}
| ontrack-git/src/main/java/net/nemerosa/ontrack/git/model/plot/GItem.kt | 2237851511 |
package org.lindelin.lindale.models
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder
data class Project(var id: Int,
var title: String,
var content: String,
var start_at: String?,
var end_at: String?,
var image: String,
var type: String,
var status: String,
var taskStatus: String,
var todoStatus: String,
var progress: Int,
var createdAt: String,
var updatedAt: String) {
class Deserializer : ResponseDeserializable<Project> {
override fun deserialize(content: String): Project {
val gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
return gson.fromJson(content, Project::class.java)
}
}
} | app/src/main/java/org/lindelin/lindale/models/Project.kt | 581366129 |
package net.nemerosa.ontrack.model.structure
import com.fasterxml.jackson.annotation.JsonIgnore
import net.nemerosa.ontrack.model.structure.ID.Companion.isDefined
/**
* A `ProjectEntity` is an [Entity] that belongs into a [Project]. It has also a [description].
*/
interface ProjectEntity : Entity {
/**
* Gets the description of this entity.
*/
val description: String?
/**
* Returns the project this entity is associated with
*/
@get:JsonIgnore
val project: Project
/**
* Returns the parent of this entity (ie. the branch for a build, etc.).
*
* For a project, null is returned.
*/
@get:JsonIgnore
val parent: ProjectEntity?
/**
* Returns the ID of the project that contains this entity. This method won't return `null`
* but the ID could be [undefined][ID.NONE].
*/
@get:JsonIgnore
val projectId: ID
get() = project.id
/**
* Shortcut to get the ID as a value.
*
* @throws IllegalArgumentException If the project ID is not [set][ID.isSet].
*/
fun projectId(): Int {
val id = projectId
check(isDefined(id)) { "Project ID must be defined" }
return id.get()
}
/**
* Gets the type of entity as an enum.
*/
@get:JsonIgnore
val projectEntityType: ProjectEntityType
/**
* Representation, like "Branch P/X"
*/
@get:JsonIgnore
val entityDisplayName: String
/**
* Creation signature of the project entity.
*
* @return Creation signature for the project entity.
*/
val signature: Signature
} | ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/ProjectEntity.kt | 3289024834 |
/*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.util
import android.widget.TextView
import androidx.test.platform.app.InstrumentationRegistry
import java.util.concurrent.atomic.AtomicBoolean
import org.junit.Assert.assertTrue
import org.junit.Test
class TextViewExtensionTest {
private val context = InstrumentationRegistry.getInstrumentation().context
private val view = TextView(context)
@Test
fun doBeforeTextChanged() {
val called = AtomicBoolean()
view.doBeforeTextChanged { _, _, _, _ ->
called.set(true)
}
view.text = "text"
assertTrue(called.get())
}
@Test
fun doOnTextChanged() {
val called = AtomicBoolean()
view.doOnTextChanged { _, _, _, _ ->
called.set(true)
}
view.text = "text"
assertTrue(called.get())
}
@Test
fun doAfterTextChanged() {
val called = AtomicBoolean()
view.doAfterTextChanged { _ ->
called.set(true)
}
view.text = "text"
assertTrue(called.get())
}
}
| core/src/androidTest/java/io/plaidapp/core/util/TextViewExtensionTest.kt | 3647958941 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.vcs.log.VcsLogDataKeys
import com.intellij.vcsUtil.VcsUtil
import git4idea.GitFileRevision
import git4idea.GitRevisionNumber
import git4idea.GitUtil
import git4idea.history.GitHistoryUtils
import org.jetbrains.plugins.github.api.GithubRepositoryPath
import org.jetbrains.plugins.github.pullrequest.action.GithubPullRequestKeys
import org.jetbrains.plugins.github.util.GithubGitHelper
import org.jetbrains.plugins.github.util.GithubNotifications
import org.jetbrains.plugins.github.util.GithubUtil
open class GithubOpenInBrowserActionGroup
: ActionGroup("Open on GitHub", "Open corresponding link in browser", AllIcons.Vcs.Vendors.Github), DumbAware {
override fun update(e: AnActionEvent) {
val repositories = getData(e.dataContext)?.first
e.presentation.isEnabledAndVisible = repositories != null && repositories.isNotEmpty()
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
e ?: return emptyArray()
val data = getData(e.dataContext) ?: return emptyArray()
if (data.first.size <= 1) return emptyArray()
return data.first.map { GithubOpenInBrowserAction(it, data.second) }.toTypedArray()
}
override fun isPopup(): Boolean = true
override fun actionPerformed(e: AnActionEvent) {
getData(e.dataContext)?.let { GithubOpenInBrowserAction(it.first.first(), it.second) }?.actionPerformed(e)
}
override fun canBePerformed(context: DataContext): Boolean {
return getData(context)?.first?.size == 1
}
override fun disableIfNoVisibleChildren(): Boolean = false
protected open fun getData(dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return null
return getDataFromPullRequest(project, dataContext)
?: getDataFromHistory(project, dataContext)
?: getDataFromLog(project, dataContext)
?: getDataFromVirtualFile(project, dataContext)
}
private fun getDataFromPullRequest(project: Project, dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? {
val pullRequest = dataContext.getData(GithubPullRequestKeys.SELECTED_PULL_REQUEST) ?: return null
val serverPath = dataContext.getData(GithubPullRequestKeys.SERVER_PATH) ?: return null
val fullPath = dataContext.getData(GithubPullRequestKeys.FULL_PATH) ?: return null
val htmlUrl = pullRequest.pullRequestLinks?.htmlUrl ?: return null
return setOf(GithubRepositoryPath(serverPath, fullPath)) to Data.URL(project, htmlUrl)
}
private fun getDataFromHistory(project: Project, dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? {
val filePath = dataContext.getData(VcsDataKeys.FILE_PATH) ?: return null
val fileRevision = dataContext.getData(VcsDataKeys.VCS_FILE_REVISION) ?: return null
if (fileRevision !is GitFileRevision) return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFile(filePath)
if (repository == null) return null
val accessibleRepositories = service<GithubGitHelper>().getPossibleRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories to Data.Revision(project, fileRevision.revisionNumber.asString())
}
private fun getDataFromLog(project: Project, dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? {
val log = dataContext.getData(VcsLogDataKeys.VCS_LOG) ?: return null
val selectedCommits = log.selectedCommits
if (selectedCommits.size != 1) return null
val commit = ContainerUtil.getFirstItem(selectedCommits) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForRoot(commit.root)
if (repository == null) return null
val accessibleRepositories = service<GithubGitHelper>().getPossibleRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories to Data.Revision(project, commit.hash.asString())
}
private fun getDataFromVirtualFile(project: Project, dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? {
val virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(virtualFile)
if (repository == null) return null
val accessibleRepositories = service<GithubGitHelper>().getPossibleRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
val changeListManager = ChangeListManager.getInstance(project)
if (changeListManager.isUnversioned(virtualFile)) return null
val change = changeListManager.getChange(virtualFile)
return if (change != null && change.type == Change.Type.NEW) null
else accessibleRepositories to Data.File(project, repository.root, virtualFile)
}
protected sealed class Data(val project: Project) {
class File(project: Project, val gitRepoRoot: VirtualFile, val virtualFile: VirtualFile) : Data(project)
class Revision(project: Project, val revisionHash: String) : Data(project)
class URL(project: Project, val htmlUrl: String) : Data(project)
}
private companion object {
private const val CANNOT_OPEN_IN_BROWSER = "Can't open in browser"
class GithubOpenInBrowserAction(private val repoPath: GithubRepositoryPath, val data: Data)
: DumbAwareAction(repoPath.toString().replace('_', ' ')) {
override fun actionPerformed(e: AnActionEvent) {
when (data) {
is Data.Revision -> openCommitInBrowser(repoPath, data.revisionHash)
is Data.File -> openFileInBrowser(data.project, data.gitRepoRoot, repoPath, data.virtualFile, e.getData(CommonDataKeys.EDITOR))
is Data.URL -> BrowserUtil.browse(data.htmlUrl)
}
}
private fun openCommitInBrowser(path: GithubRepositoryPath, revisionHash: String) {
BrowserUtil.browse("${path.toUrl()}/commit/$revisionHash")
}
private fun openFileInBrowser(project: Project,
repositoryRoot: VirtualFile,
path: GithubRepositoryPath,
virtualFile: VirtualFile,
editor: Editor?) {
val relativePath = VfsUtilCore.getRelativePath(virtualFile, repositoryRoot)
if (relativePath == null) {
GithubNotifications.showError(project, CANNOT_OPEN_IN_BROWSER, "File is not under repository root",
"Root: " + repositoryRoot.presentableUrl + ", file: " + virtualFile.presentableUrl)
return
}
val hash = getCurrentFileRevisionHash(project, virtualFile)
if (hash == null) {
GithubNotifications.showError(project, CANNOT_OPEN_IN_BROWSER, "Can't get last revision.")
return
}
val githubUrl = makeUrlToOpen(editor, relativePath, hash, path)
if (githubUrl != null) BrowserUtil.browse(githubUrl)
}
private fun getCurrentFileRevisionHash(project: Project, file: VirtualFile): String? {
val ref = Ref<GitRevisionNumber>()
object : Task.Modal(project, "Getting Last Revision", true) {
override fun run(indicator: ProgressIndicator) {
ref.set(GitHistoryUtils.getCurrentRevision(project, VcsUtil.getFilePath(file), "HEAD") as GitRevisionNumber?)
}
override fun onThrowable(error: Throwable) {
GithubUtil.LOG.warn(error)
}
}.queue()
return if (ref.isNull) null else ref.get().rev
}
private fun makeUrlToOpen(editor: Editor?,
relativePath: String,
branch: String,
path: GithubRepositoryPath): String? {
val builder = StringBuilder()
if (StringUtil.isEmptyOrSpaces(relativePath)) {
builder.append(path.toUrl()).append("/tree/").append(branch)
}
else {
builder.append(path.toUrl()).append("/blob/").append(branch).append('/').append(relativePath)
}
if (editor != null && editor.document.lineCount >= 1) {
// lines are counted internally from 0, but from 1 on github
val selectionModel = editor.selectionModel
val begin = editor.document.getLineNumber(selectionModel.selectionStart) + 1
val selectionEnd = selectionModel.selectionEnd
var end = editor.document.getLineNumber(selectionEnd) + 1
if (editor.document.getLineStartOffset(end - 1) == selectionEnd) {
end -= 1
}
builder.append("#L").append(begin)
if (begin != end) {
builder.append("-L").append(end)
}
}
return builder.toString()
}
}
}
} | plugins/github/src/org/jetbrains/plugins/github/GithubOpenInBrowserActionGroup.kt | 3229543573 |
package io.mockk.impl.recording
import io.mockk.EqMatcher
import io.mockk.Matcher
import io.mockk.every
import io.mockk.impl.log.SafeToString
import io.mockk.mockk
import kotlin.test.Test
import kotlin.test.assertEquals
class ChainedCallDetectorTest {
val safeToString = mockk<SafeToString>(relaxed = true)
val detector = ChainedCallDetector(safeToString)
val callRound1 = mockk<CallRound>(relaxed = true)
val callRound2 = mockk<CallRound>(relaxed = true)
val call1 = mockk<SignedCall>(relaxed = true)
val call2 = mockk<SignedCall>(relaxed = true)
val signedMatcher1 = mockk<SignedMatcher>(relaxed = true)
val signedMatcher2 = mockk<SignedMatcher>(relaxed = true)
@Test
fun givenTwoCallRoundsWithOneCallNoArgsWhenDetectCallsHappenThenOneCallIsReturned() {
every { callRound1.calls } returns listOf(call1)
every { callRound2.calls } returns listOf(call2)
every { call1.method.name } returns "abc"
every { call2.method.name } returns "abc"
every { call1.method.varArgsArg } returns -1
every { call2.method.varArgsArg } returns -1
detector.detect(listOf(callRound1, callRound2), 0, hashMapOf())
assertEquals("abc", detector.call.matcher.method.name)
}
@Test
fun givenTwoCallsRoundsWithOneCallOneArgWhenDetectCallsHappenThenOneCallWithArgIsReturned() {
val matcherMap = hashMapOf<List<Any>, Matcher<*>>()
matcherMap[listOf(signedMatcher1.signature, signedMatcher2.signature)] = signedMatcher1.matcher
every { callRound1.calls } returns listOf(call1)
every { callRound2.calls } returns listOf(call2)
every { signedMatcher1.signature } returns 5
every { signedMatcher2.signature } returns 6
every { call1.args } returns listOf(5)
every { call2.args } returns listOf(6)
every { call1.method.name } returns "abc"
every { call2.method.name } returns "abc"
every { call1.method.varArgsArg } returns -1
every { call2.method.varArgsArg } returns -1
detector.detect(listOf(callRound1, callRound2), 0, matcherMap)
assertEquals("abc", detector.call.matcher.method.name)
assertEquals(listOf<Matcher<*>>(EqMatcher(5)), detector.call.matcher.args)
}
} | modules/mockk/src/commonTest/kotlin/io/mockk/impl/recording/ChainedCallDetectorTest.kt | 2106639592 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.