repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JStege1206/AdventOfCode | aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day07.kt | 1 | 3103 | package nl.jstege.adventofcode.aoc2015.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.applyIf
import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues
import nl.jstege.adventofcode.aoccommon.utils.extensions.isCastableToInt
import nl.jstege.adventofcode.aoccommon.utils.extensions.transformTo
/**
*
* @author Jelle Stege
*/
class Day07 : Day(title = "Some Assembly Required") {
private companion object Configuration {
private const val INPUT_PATTERN_STRING =
"""^(NOT)?\s?([a-z0-9]+)\s?(AND|OR|LSHIFT|RSHIFT)?\s?([a-z0-9]*) -> ([a-z]+)$"""
private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex()
private const val NOT_OP_INDEX = 1
private const val WIRE1_INDEX = 2
private const val OPR_INDEX = 3
private const val WIRE2_INDEX = 4
private const val WIRE_OUT_INDEX = 5
private val OP_INDICES = intArrayOf(
NOT_OP_INDEX,
WIRE1_INDEX,
OPR_INDEX,
WIRE2_INDEX,
WIRE_OUT_INDEX
)
private val SECOND_INIT = "b" to Wire(3176)
}
override fun first(input: Sequence<String>): Any = input.compute()
override fun second(input: Sequence<String>): Any = input.compute(SECOND_INIT)
private fun Sequence<String>.compute(vararg init: Pair<String, Wire>): Int = this
.map { it.extractValues(INPUT_REGEX, *OP_INDICES) }
.transformTo(mutableMapOf(*init)) { wires, (notOp, w1, infixOp, w2, wo) ->
val op = when {
notOp.isNotEmpty() -> Operator.NOT
infixOp.isNotEmpty() -> Operator.valueOf(infixOp)
else -> Operator.MOVE
}
wires.getOrCreate(wo).let {
it.gate = Gate(op, wires.getOrCreate(w1), wires.getOrCreate(w2), it)
}
}
.getOrElse("a") { Wire() }
.value
private fun MutableMap<String, Wire>.getOrCreate(ident: String): Wire =
if (ident.isNotEmpty() && ident.isCastableToInt()) {
Wire(ident.toInt())
} else {
this.getOrPut(ident) { Wire() }
}
private data class Gate(val op: Operator, val wire1: Wire, val wire2: Wire, val wireOut: Wire) {
operator fun invoke() {
wireOut.value = op(wire1, wire2)
}
}
private data class Wire(private val _value: Int = -1) {
var value = _value
get() {
if (field < 0) {
gate()
}
return field
}
lateinit var gate: Gate
}
private enum class Operator(val f: (Wire, Wire) -> Int) {
MOVE({ w1, _ -> w1.value }),
NOT({ w1, _ -> (w1.value.inv()) and 0xFFFF }),
AND({ w1, w2 -> w1.value and (w2.value) }),
OR({ w1, w2 -> w1.value or (w2.value) }),
LSHIFT({ w1, w2 -> w1.value shl (w2.value) }),
RSHIFT({ w1, w2 -> w1.value ushr (w2.value) });
operator fun invoke(wire1: Wire, wire2: Wire) = f(wire1, wire2)
}
}
| mit | 7727a5e586939eda8b469853660809e2 | 33.098901 | 100 | 0.570416 | 3.689655 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/util/DomainPhoneNumberUtils.kt | 1 | 9215 | package org.wordpress.android.util
import android.text.TextUtils
class DomainPhoneNumberUtils {
companion object {
private const val PHONE_NUMBER_PREFIX = "+"
private const val PHONE_NUMBER_CONNECTING_CHARACTER = "."
private val countryCodeToPhoneNumberPrefixMap = mapOf(
"AC" to 247,
"AD" to 376,
"AE" to 971,
"AF" to 93,
"AG" to 1268,
"AI" to 1264,
"AL" to 355,
"AM" to 374,
"AO" to 244,
"AR" to 54,
"AS" to 1684,
"AT" to 43,
"AU" to 61,
"AW" to 297,
"AX" to 358,
"AZ" to 994,
"BA" to 387,
"BB" to 1246,
"BD" to 880,
"BE" to 32,
"BF" to 226,
"BG" to 359,
"BH" to 973,
"BI" to 257,
"BJ" to 229,
"BL" to 590,
"BM" to 1441,
"BN" to 673,
"BO" to 591,
"BQ" to 599,
"BR" to 55,
"BS" to 1242,
"BT" to 975,
"BV" to 47,
"BW" to 267,
"BY" to 375,
"BZ" to 501,
"CA" to 1,
"CC" to 61,
"CD" to 243,
"CF" to 236,
"CG" to 242,
"CH" to 41,
"CI" to 225,
"CK" to 682,
"CL" to 56,
"CM" to 237,
"CN" to 86,
"CO" to 57,
"CR" to 506,
"CU" to 53,
"CV" to 238,
"CW" to 599,
"CX" to 61,
"CY" to 357,
"CZ" to 420,
"DE" to 49,
"DJ" to 253,
"DK" to 45,
"DM" to 1767,
"DZ" to 213,
"EC" to 593,
"EE" to 372,
"EG" to 20,
"ER" to 291,
"ES" to 34,
"ET" to 251,
"FI" to 358,
"FJ" to 679,
"FK" to 500,
"FM" to 691,
"FO" to 298,
"FR" to 33,
"GA" to 241,
"GB" to 44,
"GD" to 1473,
"GE" to 995,
"GF" to 594,
"GG" to 44,
"GH" to 233,
"GI" to 350,
"GL" to 299,
"GM" to 220,
"GN" to 224,
"GP" to 590,
"GQ" to 240,
"GR" to 30,
"GS" to 500,
"GT" to 502,
"GU" to 1671,
"GW" to 245,
"GY" to 592,
"HK" to 852,
"HM" to 61,
"HN" to 504,
"HR" to 385,
"HT" to 509,
"HU" to 36,
"ID" to 62,
"IE" to 353,
"IL" to 972,
"IM" to 44,
"IN" to 91,
"IO" to 246,
"IQ" to 964,
"IR" to 98,
"IS" to 354,
"IT" to 39,
"JE" to 44,
"JM" to 1876,
"JO" to 962,
"JP" to 81,
"KE" to 254,
"KG" to 996,
"KH" to 855,
"KI" to 686,
"KM" to 269,
"KN" to 1869,
"KP" to 850,
"KR" to 82,
"KV" to 383,
"KW" to 965,
"KY" to 1345,
"KZ" to 7,
"LA" to 856,
"LB" to 961,
"LC" to 1758,
"LI" to 423,
"LK" to 94,
"LR" to 231,
"LS" to 266,
"LT" to 370,
"LU" to 352,
"LV" to 371,
"LY" to 218,
"MA" to 212,
"MC" to 377,
"MD" to 373,
"ME" to 382,
"MF" to 590,
"MG" to 261,
"MH" to 692,
"MK" to 389,
"ML" to 223,
"MM" to 95,
"MN" to 976,
"MO" to 853,
"MP" to 1670,
"MQ" to 596,
"MR" to 222,
"MS" to 1664,
"MT" to 356,
"MU" to 230,
"MV" to 960,
"MW" to 265,
"MX" to 52,
"MY" to 60,
"MZ" to 258,
"NA" to 264,
"NC" to 687,
"NE" to 227,
"NF" to 672,
"NG" to 234,
"NI" to 505,
"NL" to 31,
"NO" to 47,
"NP" to 977,
"NR" to 674,
"NU" to 683,
"NZ" to 64,
"OM" to 968,
"PA" to 507,
"PE" to 51,
"PF" to 689,
"PG" to 675,
"PH" to 63,
"PK" to 92,
"PL" to 48,
"PM" to 508,
"PN" to 64,
"PS" to 970,
"PT" to 351,
"PW" to 680,
"PY" to 595,
"QA" to 974,
"RO" to 40,
"RS" to 381,
"RU" to 7,
"RW" to 250,
"SA" to 966,
"SB" to 677,
"SC" to 248,
"SD" to 249,
"SE" to 46,
"SG" to 65,
"SH" to 290,
"SI" to 386,
"SJ" to 47,
"SK" to 421,
"SL" to 232,
"SM" to 378,
"SN" to 221,
"SO" to 252,
"SR" to 597,
"SS" to 211,
"ST" to 239,
"SV" to 503,
"SX" to 1721,
"SY" to 963,
"SZ" to 268,
"TA" to 290,
"TC" to 1649,
"TD" to 235,
"TF" to 262,
"TG" to 228,
"TH" to 66,
"TJ" to 992,
"TK" to 690,
"TL" to 670,
"TM" to 993,
"TN" to 216,
"TO" to 676,
"TR" to 90,
"TT" to 1868,
"TV" to 688,
"TW" to 886,
"TZ" to 255,
"UA" to 380,
"UG" to 256,
"UM" to 1,
"US" to 1,
"UY" to 598,
"UZ" to 998,
"VA" to 39,
"VC" to 1784,
"VE" to 58,
"VG" to 1284,
"VI" to 1340,
"VN" to 84,
"VU" to 678,
"WF" to 681,
"WS" to 685,
"YE" to 967,
"ZA" to 27,
"ZM" to 260,
"ZW" to 263
)
fun getPhoneNumberPrefix(countryCode: String): String? {
if (countryCodeToPhoneNumberPrefixMap.containsKey(countryCode)) {
return countryCodeToPhoneNumberPrefixMap[countryCode].toString()
}
return null
}
fun getPhoneNumberPrefixFromFullPhoneNumber(phoneNumber: String?): String? {
if (TextUtils.isEmpty(phoneNumber)) {
return null
}
val phoneParts = phoneNumber!!.split(PHONE_NUMBER_CONNECTING_CHARACTER)
if (phoneParts.size == 2) {
var countryCode = phoneParts[0]
if (countryCode.startsWith(PHONE_NUMBER_PREFIX)) {
countryCode = countryCode.drop(1)
}
return countryCode
}
return null
}
fun getPhoneNumberWithoutPrefix(phoneNumber: String?): String? {
if (TextUtils.isEmpty(phoneNumber)) {
return null
}
val phoneParts = phoneNumber!!.split(PHONE_NUMBER_CONNECTING_CHARACTER)
if (phoneParts.size == 2) {
val phoneNumberWithoutPrefix = phoneParts[1]
if (!TextUtils.isEmpty(phoneNumberWithoutPrefix)) {
return phoneNumberWithoutPrefix
}
}
return null
}
fun formatPhoneNumberandPrefix(phoneNumberPrefix: String?, phoneNumber: String?): String? {
if (TextUtils.isEmpty(phoneNumberPrefix) && TextUtils.isEmpty(phoneNumber)) {
return null
}
return PHONE_NUMBER_PREFIX + StringUtils.notNullStr(phoneNumberPrefix) +
PHONE_NUMBER_CONNECTING_CHARACTER + StringUtils.notNullStr(phoneNumber)
}
}
}
| gpl-2.0 | a230e80c1574ad9a5cc2bee1686cd138 | 29.213115 | 99 | 0.31796 | 4.262257 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/PostListEventListener.kt | 1 | 15347 | package org.wordpress.android.ui.posts
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode.BACKGROUND
import org.greenrobot.eventbus.ThreadMode.MAIN
import org.wordpress.android.R
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.model.CauseOfOnPostChanged
import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.MediaStore.OnMediaChanged
import org.wordpress.android.fluxc.store.MediaStore.OnMediaUploaded
import org.wordpress.android.fluxc.store.PostStore
import org.wordpress.android.fluxc.store.PostStore.OnPostChanged
import org.wordpress.android.fluxc.store.PostStore.OnPostUploaded
import org.wordpress.android.fluxc.store.PostStore.PostDeleteActionType.DELETE
import org.wordpress.android.fluxc.store.PostStore.PostDeleteActionType.TRASH
import org.wordpress.android.ui.posts.PostUploadAction.MediaUploadedSnackbar
import org.wordpress.android.ui.posts.PostUploadAction.PostRemotePreviewSnackbarError
import org.wordpress.android.ui.posts.PostUploadAction.PostUploadedSnackbar
import org.wordpress.android.ui.uploads.PostEvents
import org.wordpress.android.ui.uploads.ProgressEvent
import org.wordpress.android.ui.uploads.UploadService
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
/**
* This is a temporary class to make the PostListViewModel more manageable. Please feel free to refactor it any way
* you see fit.
*/
@Suppress("LongParameterList")
class PostListEventListener(
private val lifecycle: Lifecycle,
private val dispatcher: Dispatcher,
private val bgDispatcher: CoroutineDispatcher,
private val postStore: PostStore,
private val site: SiteModel,
private val postActionHandler: PostActionHandler,
private val handlePostUpdatedWithoutError: () -> Unit,
private val handlePostUploadedWithoutError: (LocalId) -> Unit,
private val triggerPostUploadAction: (PostUploadAction) -> Unit,
private val invalidateUploadStatus: (List<Int>) -> Unit,
private val invalidateFeaturedMedia: (List<Long>) -> Unit,
private val triggerPreviewStateUpdate: (PostListRemotePreviewState, PostInfoType) -> Unit,
private val isRemotePreviewingFromPostsList: () -> Boolean,
private val hasRemoteAutoSavePreviewError: () -> Boolean
) : DefaultLifecycleObserver, CoroutineScope {
init {
dispatcher.register(this)
EventBus.getDefault().register(this)
lifecycle.addObserver(this)
}
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = bgDispatcher + job
private fun handleRemoteAutoSave(post: PostModel, isError: Boolean) {
if (isError || hasRemoteAutoSavePreviewError.invoke()) {
triggerPreviewStateUpdate(
PostListRemotePreviewState.REMOTE_AUTO_SAVE_PREVIEW_ERROR,
PostInfoType.PostNoInfo
)
triggerPostUploadAction.invoke(PostRemotePreviewSnackbarError(R.string.remote_preview_operation_error))
} else {
triggerPreviewStateUpdate(
PostListRemotePreviewState.PREVIEWING,
PostInfoType.PostInfo(post = post, hasError = isError)
)
}
uploadStatusChanged(post.id)
if (!isError) {
handlePostUploadedWithoutError.invoke(LocalId(post.id))
}
}
/**
* Handles the [Lifecycle.Event.ON_DESTROY] event to cleanup the registration for dispatcher and removing the
* observer for lifecycle.
*/
override fun onDestroy(owner: LifecycleOwner) {
job.cancel()
lifecycle.removeObserver(this)
dispatcher.unregister(this)
EventBus.getDefault().unregister(this)
}
/**
* Has lower priority than the PostUploadHandler and UploadService, which ensures that they already processed this
* OnPostChanged event. This means we can safely rely on their internal state being up to date.
*/
@Suppress("unused", "LongMethod", "ComplexMethod")
@Subscribe(threadMode = MAIN, priority = 5)
fun onPostChanged(event: OnPostChanged) {
// We need to subscribe on the MAIN thread, in order to ensure the priority parameter is taken into account.
// However, we want to perform the body of the method on a background thread.
launch {
when (event.causeOfChange) {
// Fetched post list event will be handled by OnListChanged
is CauseOfOnPostChanged.UpdatePost -> {
if (event.isError) {
AppLog.e(
T.POSTS,
"Error updating the post with type: ${event.error.type} and" +
" message: ${event.error.message}"
)
} else {
handlePostUpdatedWithoutError.invoke()
invalidateUploadStatus.invoke(
listOf((event.causeOfChange as CauseOfOnPostChanged.UpdatePost).localPostId)
)
}
}
is CauseOfOnPostChanged.DeletePost -> {
val deletePostCauseOfChange = event.causeOfChange as CauseOfOnPostChanged.DeletePost
val localPostId = LocalId(deletePostCauseOfChange.localPostId)
when (deletePostCauseOfChange.postDeleteActionType) {
TRASH -> postActionHandler.handlePostTrashed(localPostId = localPostId, isError = event.isError)
DELETE -> postActionHandler.handlePostDeletedOrRemoved(
localPostId = localPostId,
isRemoved = false,
isError = event.isError
)
}
}
is CauseOfOnPostChanged.RestorePost -> {
val localPostId = LocalId((event.causeOfChange as CauseOfOnPostChanged.RestorePost).localPostId)
postActionHandler.handlePostRestored(localPostId = localPostId, isError = event.isError)
}
is CauseOfOnPostChanged.RemovePost -> {
val localPostId = LocalId((event.causeOfChange as CauseOfOnPostChanged.RemovePost).localPostId)
postActionHandler.handlePostDeletedOrRemoved(
localPostId = localPostId,
isRemoved = true,
isError = event.isError
)
}
is CauseOfOnPostChanged.RemoteAutoSavePost -> {
val post = postStore.getPostByLocalPostId(
(event.causeOfChange as CauseOfOnPostChanged.RemoteAutoSavePost).localPostId
)
if (isRemotePreviewingFromPostsList.invoke()) {
if (event.isError) {
AppLog.d(
T.POSTS, "REMOTE_AUTO_SAVE_POST failed: " +
event.error.type + " - " + event.error.message)
}
handleRemoteAutoSave(post, event.isError)
} else {
uploadStatusChanged(post.id)
}
}
is CauseOfOnPostChanged.FetchPages -> Unit // Do nothing
is CauseOfOnPostChanged.FetchPosts -> Unit // Do nothing
is CauseOfOnPostChanged.RemoveAllPosts -> Unit // Do nothing
is CauseOfOnPostChanged.FetchPostLikes -> Unit // Do nothing
}
}
}
@Suppress("unused")
@Subscribe(threadMode = BACKGROUND)
fun onMediaChanged(event: OnMediaChanged) {
if (!event.isError && event.mediaList != null) {
featuredMediaChanged(*event.mediaList.map { it.mediaId }.toLongArray())
uploadStatusChanged(*event.mediaList.map { it.localPostId }.toIntArray())
}
}
@Suppress("unused")
@Subscribe(threadMode = BACKGROUND)
fun onPostUploaded(event: OnPostUploaded) {
if (event.post != null && event.post.localSiteId == site.id) {
if (!isRemotePreviewingFromPostsList.invoke() && !isRemotePreviewingFromEditor(event.post)) {
triggerPostUploadAction.invoke(
PostUploadedSnackbar(
dispatcher,
site,
event.post,
event.isError,
event.isFirstTimePublish,
null
)
)
}
uploadStatusChanged(event.post.id)
if (!event.isError) {
handlePostUploadedWithoutError.invoke(LocalId(event.post.id))
}
if (isRemotePreviewingFromPostsList.invoke()) {
handleRemoteAutoSave(event.post, event.isError)
}
}
}
@Suppress("unused")
@Subscribe(threadMode = BACKGROUND)
fun onMediaUploaded(event: OnMediaUploaded) {
if (event.isError || event.canceled) {
return
}
if (event.media == null || event.media.localPostId == 0 || site.id != event.media.localSiteId) {
// Not interested in media not attached to posts or not belonging to the current site
return
}
featuredMediaChanged(event.media.mediaId)
uploadStatusChanged(event.media.localPostId)
}
// EventBus Events
@Suppress("unused")
@Subscribe(threadMode = BACKGROUND)
fun onEventBackgroundThread(event: UploadService.UploadErrorEvent) {
EventBus.getDefault().removeStickyEvent(event)
if (event.post != null) {
triggerPostUploadAction.invoke(
PostUploadedSnackbar(
dispatcher,
site,
event.post,
true,
false,
event.errorMessage
)
)
} else if (event.mediaModelList != null && !event.mediaModelList.isEmpty()) {
triggerPostUploadAction.invoke(MediaUploadedSnackbar(site, event.mediaModelList, true, event.errorMessage))
}
}
@Suppress("unused")
@Subscribe(threadMode = BACKGROUND)
fun onEventBackgroundThread(event: UploadService.UploadMediaSuccessEvent) {
EventBus.getDefault().removeStickyEvent(event)
if (event.mediaModelList != null && !event.mediaModelList.isEmpty()) {
triggerPostUploadAction.invoke(
MediaUploadedSnackbar(site, event.mediaModelList, false, event.successMessage)
)
}
}
/**
* Upload started, reload so correct status on uploading post appears
*/
@Suppress("unused")
@Subscribe(threadMode = BACKGROUND)
fun onEventBackgroundThread(event: PostEvents.PostUploadStarted) {
if (site.id == event.post.localSiteId) {
uploadStatusChanged(event.post.id)
}
}
/**
* Upload cancelled (probably due to failed media), reload so correct status on uploading post appears
*/
@Suppress("unused")
@Subscribe(threadMode = BACKGROUND)
fun onEventBackgroundThread(event: PostEvents.PostUploadCanceled) {
if (site.id == event.post.localSiteId) {
uploadStatusChanged(event.post.id)
}
}
@Suppress("unused")
@Subscribe(threadMode = BACKGROUND)
fun onEventBackgroundThread(event: ProgressEvent) {
uploadStatusChanged(event.media.localPostId)
}
@Suppress("unused")
@Subscribe(threadMode = BACKGROUND)
fun onEventBackgroundThread(event: UploadService.UploadMediaRetryEvent) {
if (event.mediaModelList != null && !event.mediaModelList.isEmpty()) {
// if there' a Post to which the retried media belongs, clear their status
val postsToRefresh = PostUtils.getPostsThatIncludeAnyOfTheseMedia(postStore, event.mediaModelList)
uploadStatusChanged(*postsToRefresh.map { it.id }.toIntArray())
}
}
private fun isRemotePreviewingFromEditor(post: PostModel?): Boolean {
val previewedPost = EventBus.getDefault().getStickyEvent(PostEvents.PostPreviewingInEditor::class.java)
return previewedPost != null && post != null &&
post.localSiteId == previewedPost.localSiteId &&
post.id == previewedPost.postId
}
private fun uploadStatusChanged(vararg localPostIds: Int) {
invalidateUploadStatus.invoke(localPostIds.toList())
}
private fun featuredMediaChanged(vararg featuredImageIds: Long) {
invalidateFeaturedMedia.invoke(featuredImageIds.toList())
}
class Factory @Inject constructor() {
@Suppress("LongParameterList")
fun createAndStartListening(
lifecycle: Lifecycle,
dispatcher: Dispatcher,
bgDispatcher: CoroutineDispatcher,
postStore: PostStore,
site: SiteModel,
postActionHandler: PostActionHandler,
handlePostUpdatedWithoutError: () -> Unit,
handlePostUploadedWithoutError: (LocalId) -> Unit,
triggerPostUploadAction: (PostUploadAction) -> Unit,
invalidateUploadStatus: (List<Int>) -> Unit,
invalidateFeaturedMedia: (List<Long>) -> Unit,
triggerPreviewStateUpdate: (PostListRemotePreviewState, PostInfoType) -> Unit,
isRemotePreviewingFromPostsList: () -> Boolean,
hasRemoteAutoSavePreviewError: () -> Boolean
) {
PostListEventListener(
lifecycle = lifecycle,
dispatcher = dispatcher,
bgDispatcher = bgDispatcher,
postStore = postStore,
site = site,
postActionHandler = postActionHandler,
handlePostUpdatedWithoutError = handlePostUpdatedWithoutError,
handlePostUploadedWithoutError = handlePostUploadedWithoutError,
triggerPostUploadAction = triggerPostUploadAction,
invalidateUploadStatus = invalidateUploadStatus,
invalidateFeaturedMedia = invalidateFeaturedMedia,
triggerPreviewStateUpdate = triggerPreviewStateUpdate,
isRemotePreviewingFromPostsList = isRemotePreviewingFromPostsList,
hasRemoteAutoSavePreviewError = hasRemoteAutoSavePreviewError)
}
}
}
| gpl-2.0 | 3b7b70fe2d0e7d10f1987cb4a01e96af | 43.484058 | 120 | 0.62592 | 5.221844 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/CriticalPostActionTracker.kt | 1 | 1660 | package org.wordpress.android.ui.posts
import org.wordpress.android.BuildConfig
import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
class CriticalPostActionTracker(
private val onStateChanged: () -> Unit,
private val shouldCrashOnUnexpectedAction: Boolean = BuildConfig.DEBUG
) {
enum class CriticalPostAction {
DELETING_POST, RESTORING_POST, TRASHING_POST, TRASHING_POST_WITH_LOCAL_CHANGES, MOVING_POST_TO_DRAFT
}
private val map = HashMap<LocalId, CriticalPostAction>()
fun add(localPostId: LocalId, criticalPostAction: CriticalPostAction) {
if (map.containsKey(localPostId)) {
val currentActionName = map[localPostId]?.name
val newActionName = criticalPostAction.name
val errorMessage = "We should not perform more than one critical post action. Current action is " +
"($currentActionName), new action is ($newActionName)"
AppLog.e(T.POSTS, errorMessage)
if (shouldCrashOnUnexpectedAction) {
throw IllegalStateException(errorMessage)
}
}
map[localPostId] = criticalPostAction
onStateChanged.invoke()
}
fun contains(localPostId: LocalId): Boolean = map.containsKey(localPostId)
fun get(localPostId: LocalId): CriticalPostAction? = map[localPostId]
fun remove(localPostId: LocalId, criticalPostAction: CriticalPostAction) {
if (map[localPostId] == criticalPostAction) {
map.remove(localPostId)
onStateChanged.invoke()
}
}
}
| gpl-2.0 | 136ecef85b10e8cdde8eb65309c8d619 | 38.52381 | 111 | 0.693976 | 4.414894 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/test/java/org/wordpress/android/ui/reader/usecases/ReaderFetchPostUseCaseTest.kt | 1 | 5660 | package org.wordpress.android.ui.reader.usecases
import kotlinx.coroutines.InternalCoroutinesApi
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers.anyLong
import org.mockito.Mock
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.test
import org.wordpress.android.ui.reader.actions.ReaderActions
import org.wordpress.android.ui.reader.actions.ReaderPostActionsWrapper
import org.wordpress.android.ui.reader.usecases.ReaderFetchPostUseCase.FetchReaderPostState.Failed
import org.wordpress.android.ui.reader.usecases.ReaderFetchPostUseCase.FetchReaderPostState.Success
import org.wordpress.android.util.NetworkUtilsWrapper
import java.net.HttpURLConnection
private const val REQUEST_BLOG_LISTENER_PARAM_POSITION = 2
@InternalCoroutinesApi
class ReaderFetchPostUseCaseTest : BaseUnitTest() {
@Mock private lateinit var networkUtilsWrapper: NetworkUtilsWrapper
@Mock private lateinit var readerPostActionsWrapper: ReaderPostActionsWrapper
private lateinit var useCase: ReaderFetchPostUseCase
private val postId = 1L
private val blogId = 2L
@Before
fun setUp() {
whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(true)
useCase = ReaderFetchPostUseCase(networkUtilsWrapper, readerPostActionsWrapper)
}
@Test
fun `given no network, when reader post is fetched, then no network is returned`() = test {
whenever(networkUtilsWrapper.isNetworkAvailable()).thenReturn(false)
val result = useCase.fetchPost(postId = postId, blogId = blogId, isFeed = false)
assertThat(result).isEqualTo(Failed.NoNetwork)
}
@Test
fun `given feed, when reader post is fetched, then feed post is requested`() = test {
whenever(readerPostActionsWrapper.requestFeedPost(anyLong(), anyLong(), any())).then {
(it.arguments[REQUEST_BLOG_LISTENER_PARAM_POSITION] as ReaderActions.OnRequestListener<*>)
.onSuccess(null)
}
useCase.fetchPost(postId = postId, blogId = blogId, isFeed = true)
verify(readerPostActionsWrapper)
.requestFeedPost(feedId = eq(blogId), postId = eq(postId), requestListener = any())
}
@Test
fun `given blog, when reader post is fetched, then blog post is requested`() = test {
whenever(readerPostActionsWrapper.requestBlogPost(anyLong(), anyLong(), any())).then {
(it.arguments[REQUEST_BLOG_LISTENER_PARAM_POSITION] as ReaderActions.OnRequestListener<*>)
.onSuccess(null)
}
useCase.fetchPost(postId = postId, blogId = blogId, isFeed = false)
verify(readerPostActionsWrapper)
.requestBlogPost(blogId = eq(blogId), postId = eq(postId), requestListener = any())
}
@Test
fun `given success response, when reader post is fetched, then success is returned`() = test {
whenever(readerPostActionsWrapper.requestBlogPost(anyLong(), anyLong(), any())).then {
(it.arguments[REQUEST_BLOG_LISTENER_PARAM_POSITION] as ReaderActions.OnRequestListener<*>)
.onSuccess(null)
}
val result = useCase.fetchPost(postId = postId, blogId = blogId, isFeed = false)
assertThat(result).isEqualTo(Success)
}
@Test
fun `given http not found status code, when reader post is fetched, then post not found is returned`() = test {
whenever(readerPostActionsWrapper.requestBlogPost(anyLong(), anyLong(), any())).then {
(it.arguments[REQUEST_BLOG_LISTENER_PARAM_POSITION] as ReaderActions.OnRequestListener<*>)
.onFailure(HttpURLConnection.HTTP_NOT_FOUND)
}
val result = useCase.fetchPost(postId = postId, blogId = blogId, isFeed = false)
assertThat(result).isEqualTo(Failed.PostNotFound)
}
@Test
fun `given http unauthorised status code, when reader post is fetched, then not authorised is returned`() = test {
whenever(readerPostActionsWrapper.requestBlogPost(anyLong(), anyLong(), any())).then {
(it.arguments[REQUEST_BLOG_LISTENER_PARAM_POSITION] as ReaderActions.OnRequestListener<*>)
.onFailure(HttpURLConnection.HTTP_UNAUTHORIZED)
}
val result = useCase.fetchPost(postId = postId, blogId = blogId, isFeed = false)
assertThat(result).isEqualTo(Failed.NotAuthorised)
}
@Test
fun `given http forbidden status code, when reader post is fetched, then not authorised is returned`() = test {
whenever(readerPostActionsWrapper.requestBlogPost(anyLong(), anyLong(), any())).then {
(it.arguments[REQUEST_BLOG_LISTENER_PARAM_POSITION] as ReaderActions.OnRequestListener<*>)
.onFailure(HttpURLConnection.HTTP_FORBIDDEN)
}
val result = useCase.fetchPost(postId = postId, blogId = blogId, isFeed = false)
assertThat(result).isEqualTo(Failed.NotAuthorised)
}
@Test
fun `given unknown status code, when reader post is fetched, then request failed is returned`() = test {
whenever(readerPostActionsWrapper.requestBlogPost(anyLong(), anyLong(), any())).then {
(it.arguments[REQUEST_BLOG_LISTENER_PARAM_POSITION] as ReaderActions.OnRequestListener<*>)
.onFailure(500)
}
val result = useCase.fetchPost(postId = postId, blogId = blogId, isFeed = false)
assertThat(result).isEqualTo(Failed.RequestFailed)
}
}
| gpl-2.0 | a1111f99aa78d4b74ac7441d874b9949 | 41.556391 | 118 | 0.705477 | 4.756303 | false | true | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/deeplearning/attention/pointernetwork/PointerNetworkProcessor.kt | 1 | 4453 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.deeplearning.attention.pointernetwork
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.core.layers.models.attention.attentionmechanism.AttentionMechanismLayer
import com.kotlinnlp.simplednn.core.neuralprocessor.NeuralProcessor
import com.kotlinnlp.simplednn.core.neuralprocessor.batchfeedforward.BatchFeedforwardProcessor
import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsList
/**
* The [PointerNetworkProcessor].
*
* @property model the model of the network
* @property id an identification number useful to track a specific processor
*/
class PointerNetworkProcessor(
val model: PointerNetworkModel,
override val id: Int = 0
) : NeuralProcessor<
DenseNDArray, // InputType
DenseNDArray, // OutputType
List<DenseNDArray>, // ErrorsType
PointerNetworkProcessor.InputErrors // InputErrorsType
> {
/**
* Not used: always propagate to the input.
*/
override val propagateToInput: Boolean = true
/**
* @param inputSequenceErrors the list of errors of the input sequence
* @param inputVectorsErrors The list of errors of the input vectors
*/
class InputErrors(val inputSequenceErrors: List<DenseNDArray>, val inputVectorsErrors: List<DenseNDArray>)
/**
* The input sequence that must be set using the [setInputSequence] method.
*/
internal lateinit var inputSequence: List<DenseNDArray>
/**
* The number of forwards performed during the last decoding.
*/
internal var forwardCount: Int = 0
/**
* A boolean indicating if this is the first state.
*/
internal val firstState: Boolean get() = this.forwardCount == 0
/**
* Batch processor for the merge network.
*/
internal val mergeProcessor: BatchFeedforwardProcessor<DenseNDArray> =
BatchFeedforwardProcessor(model = this.model.mergeNetwork, propagateToInput = true)
/**
* The list of attention mechanisms used during the last forward.
*/
internal val usedAttentionMechanisms = mutableListOf<AttentionMechanismLayer>()
/**
* The forward helper.
*/
private val forwardHelper = ForwardHelper(networkProcessor = this)
/**
* The backward helper.
*/
private val backwardHelper: BackwardHelper by lazy { BackwardHelper(networkProcessor = this) }
/**
* Set the encoded sequence.
*
* @param inputSequence the input sequence
*/
fun setInputSequence(inputSequence: List<DenseNDArray>) {
this.forwardCount = 0
this.inputSequence = inputSequence
}
/**
* Forward.
*
* @param input the vector that modulates a content-based attention mechanism over the input sequence
*
* @return an array that contains the importance score for each element of the input sequence
*/
override fun forward(input: DenseNDArray): DenseNDArray {
val output: DenseNDArray = this.forwardHelper.forward(input)
this.forwardCount++
return output
}
/**
* @return an array that contains the importance scores NOT activated resulting from the last forward
*/
fun getLastNotActivatedImportanceScores(): DenseNDArray =
this.usedAttentionMechanisms.last().outputArray.valuesNotActivated.copy()
/**
* Back-propagation of the errors.
*
* @param outputErrors the output errors
*/
override fun backward(outputErrors: List<DenseNDArray>) {
require(outputErrors.size == this.forwardCount)
this.backwardHelper.backward(outputErrors = outputErrors)
}
/**
* @param copy a Boolean indicating if the returned errors must be a copy or a reference (default true)
*
* @return the params errors of this network
*/
override fun getParamsErrors(copy: Boolean): ParamsErrorsList =
this.backwardHelper.getParamsErrors(copy = copy)
/**
* @param copy a Boolean indicating if the returned errors must be a copy or a reference (default true)
*
* @return the input errors
*/
override fun getInputErrors(copy: Boolean) = InputErrors(
inputSequenceErrors = this.backwardHelper.inputSequenceErrors,
inputVectorsErrors = this.backwardHelper.vectorsErrors
)
}
| mpl-2.0 | 53617475d7a13787df9edfa37aa63faa | 30.58156 | 108 | 0.726926 | 4.595459 | false | false | false | false |
ingokegel/intellij-community | plugins/git4idea/src/git4idea/rebase/interactive/dialog/view/CommitMessageCellEditor.kt | 8 | 6704 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.rebase.interactive.dialog.view
import com.intellij.codeInsight.hint.HintUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.CommonShortcuts
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.ui.CommitMessage
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import git4idea.i18n.GitBundle
import git4idea.rebase.GitRebaseEntryWithDetails
import git4idea.rebase.interactive.dialog.GitRebaseCommitsTableView
import org.jetbrains.annotations.NonNls
import java.awt.Component
import java.awt.Cursor
import java.awt.Point
import java.awt.event.ActionEvent
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.util.*
import javax.swing.*
import javax.swing.event.MouseInputAdapter
import javax.swing.table.TableCellEditor
import kotlin.math.max
private fun makeResizable(panel: JPanel, updateHeight: (newHeight: Int) -> Unit) {
val listener = HeightResizeMouseListener(panel, updateHeight)
panel.addMouseListener(listener)
panel.addMouseMotionListener(listener)
}
internal class CommitMessageCellEditor(
private val project: Project,
private val table: GitRebaseCommitsTableView,
private val disposable: Disposable
) : AbstractCellEditor(), TableCellEditor {
companion object {
@NonNls
private const val COMMIT_MESSAGE_HEIGHT_KEY = "Git.Interactive.Rebase.Dialog.Commit.Message.Height"
private val HINT_HEIGHT = JBUIScale.scale(17)
private val DEFAULT_COMMIT_MESSAGE_HEIGHT = GitRebaseCommitsTableView.DEFAULT_CELL_HEIGHT * 5
internal fun canResize(height: Int, point: Point): Boolean = point.y in height - HINT_HEIGHT..height
}
private var savedHeight: Int
get() = PropertiesComponent.getInstance(project).getInt(COMMIT_MESSAGE_HEIGHT_KEY, DEFAULT_COMMIT_MESSAGE_HEIGHT)
set(value) {
PropertiesComponent.getInstance(project).setValue(COMMIT_MESSAGE_HEIGHT_KEY, value, DEFAULT_COMMIT_MESSAGE_HEIGHT)
}
private val closeEditorAction = object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) {
stopCellEditing()
}
}
/**
* Used to save edit message history for each commit (e.g. for undo/redo)
*/
private val commitMessageForEntry = mutableMapOf<GitRebaseEntryWithDetails, CommitMessage>()
private var lastUsedCommitMessageField: CommitMessage? = null
private val hint = createHint()
private fun createCommitMessage() = CommitMessage(project, false, false, true).apply {
editorField.addSettingsProvider { editor ->
editor.scrollPane.border = JBUI.Borders.emptyLeft(6)
registerCloseEditorShortcut(editor, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK))
registerCloseEditorShortcut(editor, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.META_DOWN_MASK))
}
editorField.setCaretPosition(0)
Disposer.register(disposable, this)
}
private fun registerCloseEditorShortcut(editor: EditorEx, shortcut: KeyStroke) {
val key = "applyEdit$shortcut"
editor.contentComponent.inputMap.put(shortcut, key)
editor.contentComponent.actionMap.put(key, closeEditorAction)
}
override fun getTableCellEditorComponent(table: JTable, value: Any?, isSelected: Boolean, row: Int, column: Int): Component {
val model = this.table.model
val commitMessageField = commitMessageForEntry.getOrPut(model.getEntry(row)) { createCommitMessage() }
lastUsedCommitMessageField = commitMessageField
commitMessageField.text = model.getCommitMessage(row)
table.setRowHeight(row, savedHeight)
val componentPanel = object : BorderLayoutPanel() {
override fun requestFocus() {
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown {
IdeFocusManager.getGlobalInstance().requestFocus(commitMessageField.editorField, true)
}
}
}
return componentPanel.addToCenter(commitMessageField).addToBottom(hint).apply {
background = table.background
border = JBUI.Borders.merge(IdeBorderFactory.createBorder(), JBUI.Borders.empty(6, 0, 0, 6), true)
makeResizable(this) { newHeight ->
val height = max(DEFAULT_COMMIT_MESSAGE_HEIGHT, newHeight)
table.setRowHeight(row, height)
savedHeight = height
}
}
}
private fun createHint(): JLabel {
val hint = GitBundle.message("rebase.interactive.dialog.reword.hint.text",
KeymapUtil.getFirstKeyboardShortcutText(CommonShortcuts.CTRL_ENTER))
val hintLabel = HintUtil.createAdComponent(hint, JBUI.CurrentTheme.BigPopup.advertiserBorder(), SwingConstants.LEFT).apply {
foreground = JBUI.CurrentTheme.BigPopup.advertiserForeground()
background = JBUI.CurrentTheme.BigPopup.advertiserBackground()
isOpaque = true
}
val size = hintLabel.preferredSize
size.height = HINT_HEIGHT
hintLabel.preferredSize = size
return hintLabel
}
override fun getCellEditorValue() = lastUsedCommitMessageField?.text ?: ""
override fun isCellEditable(e: EventObject?) = when {
table.selectedRowCount > 1 -> false
e is MouseEvent -> e.clickCount >= 2
else -> true
}
}
private class HeightResizeMouseListener(
private val panel: JPanel,
private val updateHeight: (newHeight: Int) -> Unit
) : MouseInputAdapter() {
private var resizedHeight = panel.height
private var previousPoint: Point? = null
override fun mouseReleased(e: MouseEvent) {
updateCursor(e)
previousPoint = null
}
override fun mouseMoved(e: MouseEvent) {
updateCursor(e)
}
override fun mouseDragged(e: MouseEvent) {
val current = e.locationOnScreen
previousPoint?.let {
val deltaY = current.y - it.y
resizedHeight += deltaY
updateHeight(resizedHeight)
}
previousPoint = current
}
override fun mousePressed(e: MouseEvent) {
previousPoint = e.locationOnScreen
resizedHeight = panel.height
}
private fun updateCursor(e: MouseEvent) {
val point = e.point
panel.cursor = if (CommitMessageCellEditor.canResize(panel.height, point)) {
Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)
}
else {
Cursor.getDefaultCursor()
}
}
} | apache-2.0 | 32045a2a80124f818b469da3d144bfd5 | 36.25 | 140 | 0.75358 | 4.387435 | false | false | false | false |
plombardi89/KOcean | src/main/kotlin/com/github/plombardi89/kocean/model/Links.kt | 1 | 492 | package com.github.plombardi89.kocean.model
import com.eclipsesource.json.JsonObject
public data class Links(val first: String?, val previous: String?, val next: String?, val last: String?) {
constructor(json: JsonObject): this(
json.getString("first", null),
json.getString("prev", null),
json.getString("next", null),
json.getString("last", null)
)
fun isEmpty(): Boolean {
return first == null && previous == null && next == null && last == null
}
} | mit | e2fa5c69a206700e84b992d1a50ac164 | 28 | 106 | 0.660569 | 3.967742 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GrAnnotationReferencingUnknownIdentifiers.kt | 2 | 3462 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInspection.bugs
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiAnnotationMemberValue
import com.intellij.psi.PsiArrayInitializerMemberValue
import com.intellij.psi.PsiLiteral
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.resolve.GroovyStringLiteralManipulator
import org.jetbrains.plugins.groovy.lang.resolve.ast.AffectedMembersCache
import org.jetbrains.plugins.groovy.lang.resolve.ast.constructorGeneratingAnnotations
import org.jetbrains.plugins.groovy.lang.resolve.ast.getAffectedMembersCache
class GrAnnotationReferencingUnknownIdentifiers : BaseInspection() {
override fun buildErrorString(vararg args: Any?): String {
return GroovyBundle.message("inspection.message.couldnt.find.property.field.with.this.name")
}
companion object {
private val IDENTIFIER_MATCHER = Regex("\\w+")
private val DELIMITED_LIST_MATCHER = Regex("^(\\s*\\w+\\s*,)*\\s*\\w+\\s*\$")
private fun iterateOverIdentifierList(value: PsiAnnotationMemberValue, identifiers: Set<String>): Iterable<TextRange> {
when (value) {
is PsiArrayInitializerMemberValue -> {
val initializers = value.initializers
return initializers.mapNotNull {
(it as? PsiLiteral)?.takeUnless { literal -> literal.value in identifiers }?.textRangeInParent
}
}
is PsiLiteral -> {
val stringText: String = value.text ?: return emptyList()
val internalRange = GroovyStringLiteralManipulator.getLiteralRange(stringText)
val content = internalRange.substring(stringText).takeIf(DELIMITED_LIST_MATCHER::matches) ?: return emptyList()
return IDENTIFIER_MATCHER.findAll(content)
.filter { it.value !in identifiers }
.map { TextRange(it.range.first + internalRange.startOffset, it.range.last + internalRange.startOffset + 1) }.asIterable()
}
else -> return emptyList()
}
}
}
override fun buildVisitor(): BaseInspectionVisitor = object : BaseInspectionVisitor() {
private fun processAttribute(identifiers: Set<String>, annotation: GrAnnotation, attributeName: String) {
val value = annotation.findAttributeValue(attributeName) ?: return
// protection against default annotation values stored in annotation's .class file
if (value.containingFile != annotation.containingFile) return
for (range in iterateOverIdentifierList(value, identifiers)) {
registerRangeError(value, range)
}
}
override fun visitAnnotation(annotation: GrAnnotation) {
super.visitAnnotation(annotation)
if (!constructorGeneratingAnnotations.contains(annotation.qualifiedName)) return
val cache = getAffectedMembersCache(annotation)
val affectedMembers = cache.getAllAffectedMembers().mapNotNullTo(mutableSetOf(), AffectedMembersCache.Companion::getExternalName)
processAttribute(affectedMembers, annotation, "includes")
processAttribute(affectedMembers, annotation, "excludes")
}
}
}
| apache-2.0 | 89e7f87041cd7205962db361200142c4 | 49.173913 | 140 | 0.7513 | 4.896747 | false | false | false | false |
uramonk/AndroidTemplateApp | app/src/main/java/com/uramonk/androidtemplateapp/domain/interactor/UseCase.kt | 1 | 2443 | package com.uramonk.androidtemplateapp.domain.interactor
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
/**
* Created by kaz on 2016/12/23.
*/
abstract class UseCase<T> {
private var executionScheduler: Scheduler = Schedulers.newThread()
private var postScheduler: Scheduler = AndroidSchedulers.mainThread()
private var disposable: Disposable? = null
protected constructor() {
}
protected constructor(executionScheduler: Scheduler, postScheduler: Scheduler) {
this.executionScheduler = executionScheduler
this.postScheduler = postScheduler
}
fun executionScheduler(executionScheduler: Scheduler): UseCase<T> {
this.executionScheduler = executionScheduler
return this
}
fun postScheduler(postScheduler: Scheduler): UseCase<T> {
this.postScheduler = postScheduler
return this
}
fun execute(observer: DisposableObserver<T>): Disposable {
val observable: Observable<T> = this.buildObservableUseCase()
.subscribeOn(executionScheduler)
.observeOn(postScheduler)
return observable.subscribeWith(observer)
}
fun execute(onNext: Consumer<in T>): Disposable {
val observable: Observable<T> = this.buildObservableUseCase()
.subscribeOn(executionScheduler)
.observeOn(postScheduler)
return observable.subscribe(onNext)
}
fun execute(onNext: Consumer<in T>, onError: Consumer<in Throwable>): Disposable {
val observable: Observable<T> = this.buildObservableUseCase()
.subscribeOn(executionScheduler)
.observeOn(postScheduler)
return observable.subscribe(onNext, onError)
}
fun execute(onNext: Consumer<in T>, onError: Consumer<in Throwable>,
onCompleted: Action): Disposable {
val observable: Observable<T> = this.buildObservableUseCase()
.subscribeOn(executionScheduler)
.observeOn(postScheduler)
return observable.subscribe(onNext, onError, onCompleted)
}
protected abstract fun buildObservableUseCase(): Observable<T>
}
| mit | 5fc24e4b9789966bffbaf2433b39cbb1 | 31.573333 | 86 | 0.704871 | 4.99591 | false | false | false | false |
helloworld1/FreeOTPPlus | token-data/src/main/java/org/fedorahosted/freeotp/data/MigrationUtil.kt | 1 | 2340 | package org.fedorahosted.freeotp.data
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.fedorahosted.freeotp.data.legacy.SavedTokens
import org.fedorahosted.freeotp.data.legacy.Token
import org.fedorahosted.freeotp.data.legacy.TokenPersistence
import javax.inject.Inject
class MigrationUtil @Inject constructor(
private val optTokenDatabase: OtpTokenDatabase,
private val tokenPersistence: TokenPersistence,
) {
fun isMigrated(): Boolean = tokenPersistence.isLegacyTokenMigrated()
suspend fun migrate() {
withContext(Dispatchers.IO) {
val tokenList = convertLegacyTokensToOtpTokens(tokenPersistence.getTokens())
optTokenDatabase.otpTokenDao().insertAll(tokenList)
tokenPersistence.setLegacyTokenMigrated()
}
}
suspend fun convertLegacySavedTokensToOtpTokens(savedTokens: SavedTokens): List<OtpToken> = withContext(Dispatchers.IO) {
val tokenMap = savedTokens.tokens.map { token ->
token.id to token
}.toMap()
val legacyTokens = savedTokens.tokenOrder.mapNotNull { tokenKey ->
tokenMap[tokenKey]
}
convertLegacyTokensToOtpTokens(legacyTokens)
}
suspend fun convertLegacyTokensToOtpTokens(legacyTokens: List<Token>): List<OtpToken> = withContext(Dispatchers.IO) {
legacyTokens.mapIndexed{ index, legacyToken ->
OtpToken(
id = index.toLong() + 1,
ordinal = index.toLong() + 1,
issuer = legacyToken.issuer,
label = legacyToken.label,
imagePath = legacyToken.image?.toString(),
tokenType = if (legacyToken.type == Token.TokenType.HOTP) OtpTokenType.HOTP else OtpTokenType.TOTP,
algorithm = legacyToken.algorithm ?: "sha1",
counter = legacyToken.counter,
secret = legacyToken.secret,
digits = legacyToken.digits,
period = legacyToken.period,
encryptionType = EncryptionType.PLAIN_TEXT
)
}
};
suspend fun convertOtpTokensToLegacyTokens(tokens: List<OtpToken>) = withContext(Dispatchers.IO) {
tokens.map {
OtpTokenFactory.toUri(it)
}.map { uri ->
Token(uri)
}
}
} | apache-2.0 | 9d669addef737cd96c40527aedf5b93c | 36.758065 | 125 | 0.654274 | 4.543689 | false | false | false | false |
PtrTeixeira/cookbook-backend | strava-api/src/main/kotlin/StravaService.kt | 2 | 1618 | package com.github.ptrteixeira.strava.api
import com.github.ptrteixeira.strava.api.models.AthleteActivitiesResponse
import com.github.ptrteixeira.strava.api.models.TokenResponse
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.time.LocalDateTime
import java.time.ZoneOffset
class StravaService(private val strava: StravaApi) : IStravaService {
override fun getAthleteActivities(
authToken: String,
after: LocalDateTime
): Flux<AthleteActivitiesResponse> {
return getAthleteActivities(authToken, page = 1, after = after)
}
override fun getAuthToken(clientId: String, clientSecret: String, code: String): Mono<TokenResponse> {
return strava.getAuthToken(clientId, clientSecret, code)
}
private fun getAthleteActivities(
authToken: String,
page: Int,
after: LocalDateTime
): Flux<AthleteActivitiesResponse> {
val header = buildAuthHeader(authToken)
val afterUtcSeconds: Long = after.toEpochSecond(ZoneOffset.UTC)
val response = strava
.getAthleteActivities(header, afterUtcSeconds, page = page)
return response
.flatMapMany {
if (it.isEmpty()) {
Flux.fromIterable(it)
} else {
Flux
.fromIterable(it)
.concatWith(getAthleteActivities(authToken, page + 1, after))
}
}
}
private fun buildAuthHeader(token: String): String = "Bearer $token"
} | mit | 727f0a216bd0c65959fb7280d04163b4 | 34.977778 | 106 | 0.634116 | 4.596591 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/internal/api/renderHelpers.kt | 1 | 17298 | package imgui.internal.api
import glm_.b
import glm_.bool
import glm_.f
import glm_.func.common.max
import glm_.vec1.Vec1i
import glm_.vec2.Vec2
import glm_.vec4.Vec4
import imgui.*
import imgui.ImGui.calcTextSize
import imgui.ImGui.currentWindow
import imgui.ImGui.getColorU32
import imgui.ImGui.logText
import imgui.ImGui.style
import imgui.api.g
import imgui.classes.DrawList
import imgui.internal.*
import imgui.internal.classes.Rect
import imgui.internal.sections.*
import unsigned.toUInt
import kotlin.math.max
import imgui.internal.sections.DrawCornerFlag as Dcf
/** Render helpers
* AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT.
* NB: All position are in absolute pixels coordinates (we are never using window coordinates internally) */
internal interface renderHelpers {
fun renderText(pos: Vec2, text: String, hideTextAfterHash: Boolean = true) {
val bytes = text.toByteArray()
renderText(pos, bytes, 0, bytes.size, hideTextAfterHash)
}
fun renderText(pos: Vec2, text: ByteArray, textBegin: Int = 0, textEnd: Int = -1, hideTextAfterHash: Boolean = true) {
val window = g.currentWindow!!
// Hide anything after a '##' string
val textDisplayEnd = when {
hideTextAfterHash -> findRenderedTextEnd(text, textBegin, textEnd)
textEnd == -1 -> text.strlen(textBegin)
else -> textEnd
}
if (textBegin != textDisplayEnd) {
window.drawList.addText(g.font, g.fontSize, pos, Col.Text.u32, text, textBegin, textDisplayEnd)
if (g.logEnabled)
logRenderedText(pos, String(text, textBegin, textEnd - textBegin), textDisplayEnd)
}
}
fun renderTextWrapped(pos: Vec2, text: ByteArray, textEnd_: Int, wrapWidth: Float) {
val window = g.currentWindow!!
val textEnd = if (textEnd_ == -1) text.strlen() else textEnd_ // FIXME-OPT
if (textEnd > 0) {
window.drawList.addText(g.font, g.fontSize, pos, Col.Text.u32, text, 0, textEnd, wrapWidth)
if (g.logEnabled)
logRenderedText(pos, text.cStr, textEnd)
}
}
fun renderTextClipped(posMin: Vec2, posMax: Vec2, text: String, textSizeIfKnown: Vec2? = null,
align: Vec2 = Vec2(), clipRect: Rect? = null) {
val bytes = text.toByteArray()
renderTextClipped(posMin, posMax, bytes, bytes.size, textSizeIfKnown, align, clipRect)
}
fun renderTextClipped(posMin: Vec2, posMax: Vec2, text: ByteArray, textEnd: Int = text.size, textSizeIfKnown: Vec2? = null,
align: Vec2 = Vec2(), clipRect: Rect? = null) {
// Hide anything after a '##' string
val textDisplayEnd = findRenderedTextEnd(text, 0, textEnd)
if (textDisplayEnd == 0) return
val window = g.currentWindow!!
renderTextClippedEx(window.drawList, posMin, posMax, text, textDisplayEnd, textSizeIfKnown, align, clipRect)
if (g.logEnabled)
logRenderedText(posMax, text.cStr, textDisplayEnd)
}
/** Default clipRect uses (pos_min,pos_max)
* Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping
* rectangle edges) */
fun renderTextClippedEx(drawList: DrawList, posMin: Vec2, posMax: Vec2, text: ByteArray, textDisplayEnd: Int = -1,
textSizeIfKnown: Vec2? = null, align: Vec2 = Vec2(), clipRect: Rect? = null) {
// Perform CPU side clipping for single clipped element to avoid using scissor state
val pos = Vec2(posMin)
val textSize = textSizeIfKnown ?: calcTextSize(text, 0, textDisplayEnd, false, 0f)
val clipMin = clipRect?.min ?: posMin
val clipMax = clipRect?.max ?: posMax
var needClipping = (pos.x + textSize.x >= clipMax.x) || (pos.y + textSize.y >= clipMax.y)
clipRect?.let {
// If we had no explicit clipping rectangle then pos==clipMin
needClipping = needClipping || (pos.x < clipMin.x || pos.y < clipMin.y)
}
// Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
if (align.x > 0f) pos.x = pos.x max (pos.x + (posMax.x - pos.x - textSize.x) * align.x)
if (align.y > 0f) pos.y = pos.y max (pos.y + (posMax.y - pos.y - textSize.y) * align.y)
// Render
val fineClipRect = when {
needClipping -> Vec4(clipMin.x, clipMin.y, clipMax.x, clipMax.y)
else -> null
}
drawList.addText(null, 0f, pos, Col.Text.u32, text, 0, textDisplayEnd, 0f, fineClipRect)
}
/** Another overly complex function until we reorganize everything into a nice all-in-one helper.
* This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
* This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move. */
fun renderTextEllipsis(drawList: DrawList, posMin: Vec2, posMax: Vec2, clipMaxX: Float, ellipsisMaxX: Float,
text: ByteArray, textEndFull: Int = findRenderedTextEnd(text), textSizeIfKnown: Vec2?) {
val textSize = textSizeIfKnown ?: calcTextSize(text, 0, textEndFull, false, 0f)
//draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
//draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
//draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
// FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
if (textSize.x > posMax.x - posMin.x) {
/*
Hello wo...
| | |
min max ellipsis_max
<-> this is generally some padding value
*/
val font = drawList._data.font!!
val fontSize = drawList._data.fontSize
val textEndEllipsis = Vec1i(-1)
var ellipsisChar = font.ellipsisChar
var ellipsisCharCount = 1
if (ellipsisChar == '\uffff') {
ellipsisChar = '.'
ellipsisCharCount = 3
}
val glyph = font.findGlyph(ellipsisChar)!!
var ellipsisGlyphWidth = glyph.x1 // Width of the glyph with no padding on either side
var ellipsisTotalWidth = ellipsisGlyphWidth // Full width of entire ellipsis
if (ellipsisCharCount > 1) {
// Full ellipsis size without free spacing after it.
val spacingBetweenDots = 1f * (drawList._data.fontSize / font.fontSize)
ellipsisGlyphWidth = glyph.x1 - glyph.x0 + spacingBetweenDots
ellipsisTotalWidth = ellipsisGlyphWidth * ellipsisCharCount.f - spacingBetweenDots
}
// We can now claim the space between pos_max.x and ellipsis_max.x
val textAvailWidth = ((max(posMax.x, ellipsisMaxX) - ellipsisTotalWidth) - posMin.x) max 1f
var textSizeClippedX = font.calcTextSizeA(fontSize, textAvailWidth, 0f, text,
textEnd = textEndFull, remaining = textEndEllipsis).x
if (0 == textEndEllipsis[0] && textEndEllipsis[0] < textEndFull) {
// Always display at least 1 character if there's no room for character + ellipsis
textEndEllipsis[0] = textCountUtf8BytesFromChar(text, textEndFull)
textSizeClippedX = font.calcTextSizeA(fontSize, Float.MAX_VALUE, 0f, text, textEnd = textEndEllipsis[0]).x
}
while (textEndEllipsis[0] > 0 && charIsBlankA(text[textEndEllipsis[0] - 1].toUInt())) {
// Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
textEndEllipsis[0]--
textSizeClippedX -= font.calcTextSizeA(fontSize, Float.MAX_VALUE, 0f, text,
textEndEllipsis[0], textEndEllipsis[0] + 1).x // Ascii blanks are always 1 byte
}
// Render text, render ellipsis
renderTextClippedEx(drawList, posMin, Vec2(clipMaxX, posMax.y), text, textEndEllipsis[0], textSize, Vec2())
var ellipsisX = posMin.x + textSizeClippedX
if (ellipsisX + ellipsisTotalWidth <= ellipsisMaxX)
for (i in 0 until ellipsisCharCount) {
font.renderChar(drawList, fontSize, Vec2(ellipsisX, posMin.y), Col.Text.u32, ellipsisChar)
ellipsisX += ellipsisGlyphWidth
}
} else
renderTextClippedEx(drawList, posMin, Vec2(clipMaxX, posMax.y), text, textEndFull, textSize, Vec2())
if (g.logEnabled)
logRenderedText(posMin, text.cStr, textEndFull)
}
/** Render a rectangle shaped with optional rounding and borders */
fun renderFrame(pMin: Vec2, pMax: Vec2, fillCol: Int, border: Boolean = true, rounding: Float = 0f) {
val window = g.currentWindow!!
window.drawList.addRectFilled(pMin, pMax, fillCol, rounding)
val borderSize = style.frameBorderSize
if (border && borderSize > 0f) {
window.drawList.addRect(pMin + 1, pMax + 1, Col.BorderShadow.u32, rounding, Dcf.All.i, borderSize)
window.drawList.addRect(pMin, pMax, Col.Border.u32, rounding, 0.inv(), borderSize)
}
}
fun renderFrameBorder(pMin: Vec2, pMax: Vec2, rounding: Float = 0f) = with(g.currentWindow!!) {
val borderSize = style.frameBorderSize
if (borderSize > 0f) {
drawList.addRect(pMin + 1, pMax + 1, Col.BorderShadow.u32, rounding, Dcf.All.i, borderSize)
drawList.addRect(pMin, pMax, Col.Border.u32, rounding, 0.inv(), borderSize)
}
}
/** Helper for ColorPicker4()
* NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.
* Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether.
* FIXME: uses ImGui::GetColorU32
* [JVM] safe passing Vec2 instances */
fun renderColorRectWithAlphaCheckerboard(drawList: DrawList, pMin: Vec2, pMax: Vec2, col: Int, gridStep: Float,
gridOff: Vec2, rounding: Float = 0f, roundingCornersFlags: Int = -1) {
if (((col and COL32_A_MASK) ushr COL32_A_SHIFT) < 0xFF) {
val colBg1 = getColorU32(alphaBlendColors(COL32(204, 204, 204, 255), col))
val colBg2 = getColorU32(alphaBlendColors(COL32(128, 128, 128, 255), col))
drawList.addRectFilled(pMin, pMax, colBg1, rounding, roundingCornersFlags)
var yi = 0
var y = pMin.y + gridOff.y
while (y < pMax.y) {
val y1 = clamp(y, pMin.y, pMax.y)
val y2 = min(y + gridStep, pMax.y)
if (y2 <= y1) {
y += gridStep
yi++
continue
}
var x = pMin.x + gridOff.x + (yi and 1) * gridStep
while (x < pMax.x) {
val x1 = clamp(x, pMin.x, pMax.x)
val x2 = min(x + gridStep, pMax.x)
if (x2 <= x1) {
x += gridStep * 2f
continue
}
var roundingCornersFlagsCell = 0
if (y1 <= pMin.y) {
if (x1 <= pMin.x) roundingCornersFlagsCell = roundingCornersFlagsCell or Dcf.TopLeft
if (x2 >= pMax.x) roundingCornersFlagsCell = roundingCornersFlagsCell or Dcf.TopRight
}
if (y2 >= pMax.y) {
if (x1 <= pMin.x) roundingCornersFlagsCell = roundingCornersFlagsCell or Dcf.BotLeft
if (x2 >= pMax.x) roundingCornersFlagsCell = roundingCornersFlagsCell or Dcf.BotRight
}
roundingCornersFlagsCell = roundingCornersFlagsCell and roundingCornersFlags
drawList.addRectFilled(Vec2(x1, y1), Vec2(x2, y2), colBg2, if (roundingCornersFlagsCell.bool) rounding else 0f, roundingCornersFlagsCell)
x += gridStep * 2f
}
y += gridStep
yi++
}
} else
drawList.addRectFilled(pMin, pMax, col, rounding, roundingCornersFlags)
}
/** Navigation highlight
* @param flags: NavHighlightFlag */
fun renderNavHighlight(bb: Rect, id: ID, flags: NavHighlightFlags = NavHighlightFlag.TypeDefault.i) {
if (id != g.navId) return
if (g.navDisableHighlight && flags hasnt NavHighlightFlag.AlwaysDraw) return
val window = currentWindow
if (window.dc.navHideHighlightOneFrame) return
val rounding = if (flags hasnt NavHighlightFlag.NoRounding) 0f else g.style.frameRounding
val displayRect = Rect(bb)
displayRect clipWith window.clipRect
if (flags has NavHighlightFlag.TypeDefault) {
val THICKNESS = 2f
val DISTANCE = 3f + THICKNESS * 0.5f
displayRect expand Vec2(DISTANCE)
val fullyVisible = displayRect in window.clipRect
if (!fullyVisible)
window.drawList.pushClipRect(displayRect) // check order here down
window.drawList.addRect(displayRect.min + (THICKNESS * 0.5f), displayRect.max - (THICKNESS * 0.5f),
Col.NavHighlight.u32, rounding, Dcf.All.i, THICKNESS)
if (!fullyVisible)
window.drawList.popClipRect()
}
if (flags has NavHighlightFlag.TypeThin)
window.drawList.addRect(displayRect.min, displayRect.max, Col.NavHighlight.u32, rounding, 0.inv(), 1f)
}
/** Find the optional ## from which we stop displaying text. */
fun findRenderedTextEnd(text: String, textEnd: Int = -1): Int {
val bytes = text.toByteArray()
return findRenderedTextEnd(bytes, 0, if (textEnd != -1) textEnd else bytes.size)
}
/** Find the optional ## from which we stop displaying text. */
fun findRenderedTextEnd(text: ByteArray, textBegin: Int = 0, textEnd: Int = text.size): Int {
var textDisplayEnd = textBegin
while (textDisplayEnd < textEnd && text[textDisplayEnd] != 0.b &&
(text[textDisplayEnd + 0] != '#'.b || text[textDisplayEnd + 1] != '#'.b))
textDisplayEnd++
return textDisplayEnd
}
fun logRenderedText(refPos: Vec2?, text: String, textEnd: Int = findRenderedTextEnd(text)) { // TODO ByteArray?
val window = g.currentWindow!!
val logNewLine = refPos?.let { it.y > g.logLinePosY + 1 } ?: false
refPos?.let { g.logLinePosY = it.y }
if (logNewLine)
g.logLineFirstItem = true
var textRemaining = text
if (g.logDepthRef > window.dc.treeDepth) // Re-adjust padding if we have popped out of our starting depth
g.logDepthRef = window.dc.treeDepth
val treeDepth = window.dc.treeDepth - g.logDepthRef
while (true) {
// TODO re-sync
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
// We don't add a trailing \n to allow a subsequent item on the same line to be captured.
val lineStart = textRemaining
val lineEnd = if (lineStart.indexOf('\n') == -1) lineStart.length else lineStart.indexOf('\n')
val isFirstLine = text.startsWith(lineStart)
val isLastLine = text.endsWith(lineStart.substring(0, lineEnd))
if (!isLastLine or lineStart.isNotEmpty()) {
val charCount = lineStart.length
when {
logNewLine or !isFirstLine -> logText("%s%s", "", lineStart)
g.logLineFirstItem -> logText("%s%s", "", lineStart)
else -> logText("%s", lineStart)
}
} else if (logNewLine) {
// An empty "" string at a different Y position should output a carriage return.
logText("\n")
break
}
if (isLastLine)
break
textRemaining = textRemaining.substring(lineEnd + 1)
}
}
// Render helpers (those functions don't access any ImGui state!)
// these are all in the DrawList class
} | mit | c9ade18a359cf35debea25ec549d1a0a | 49.287791 | 276 | 0.612267 | 4.053902 | false | false | false | false |
iSoron/uhabits | uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/models/sqlite/records/HabitRecord.kt | 1 | 4172 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.core.models.sqlite.records
import org.isoron.uhabits.core.database.Column
import org.isoron.uhabits.core.database.Table
import org.isoron.uhabits.core.models.Frequency
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.HabitType
import org.isoron.uhabits.core.models.NumericalHabitType
import org.isoron.uhabits.core.models.PaletteColor
import org.isoron.uhabits.core.models.Reminder
import org.isoron.uhabits.core.models.WeekdayList
import java.util.Objects.requireNonNull
/**
* The SQLite database record corresponding to a [Habit].
*/
@Table(name = "habits")
class HabitRecord {
@field:Column
var description: String? = null
@field:Column
var question: String? = null
@field:Column
var name: String? = null
@field:Column(name = "freq_num")
var freqNum: Int? = null
@field:Column(name = "freq_den")
var freqDen: Int? = null
@field:Column
var color: Int? = null
@field:Column
var position: Int? = null
@field:Column(name = "reminder_hour")
var reminderHour: Int? = null
@field:Column(name = "reminder_min")
var reminderMin: Int? = null
@field:Column(name = "reminder_days")
var reminderDays: Int? = null
@field:Column
var highlight: Int? = null
@field:Column
var archived: Int? = null
@field:Column
var type: Int? = null
@field:Column(name = "target_value")
var targetValue: Double? = null
@field:Column(name = "target_type")
var targetType: Int? = null
@field:Column
var unit: String? = null
@field:Column
var id: Long? = null
@field:Column
var uuid: String? = null
fun copyFrom(model: Habit) {
id = model.id
name = model.name
description = model.description
highlight = 0
color = model.color.paletteIndex
archived = if (model.isArchived) 1 else 0
type = model.type.value
targetType = model.targetType.value
targetValue = model.targetValue
unit = model.unit
position = model.position
question = model.question
uuid = model.uuid
val (numerator, denominator) = model.frequency
freqNum = numerator
freqDen = denominator
reminderDays = 0
reminderMin = null
reminderHour = null
if (model.hasReminder()) {
val reminder = model.reminder
reminderHour = requireNonNull(reminder)!!.hour
reminderMin = reminder!!.minute
reminderDays = reminder.days.toInteger()
}
}
fun copyTo(habit: Habit) {
habit.id = id
habit.name = name!!
habit.description = description!!
habit.question = question!!
habit.frequency = Frequency(freqNum!!, freqDen!!)
habit.color = PaletteColor(color!!)
habit.isArchived = archived != 0
habit.type = HabitType.fromInt(type!!)
habit.targetType = NumericalHabitType.fromInt(targetType!!)
habit.targetValue = targetValue!!
habit.unit = unit!!
habit.position = position!!
habit.uuid = uuid
if (reminderHour != null && reminderMin != null) {
habit.reminder = Reminder(
reminderHour!!,
reminderMin!!,
WeekdayList(reminderDays!!)
)
}
}
}
| gpl-3.0 | 7676002460f4a6048889457aed38008e | 28.58156 | 78 | 0.648526 | 4.175175 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/settings/internal/AppearanceSettingsCallShould.kt | 1 | 4558 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.settings.internal
import com.nhaarman.mockitokotlin2.*
import io.reactivex.Single
import org.hisp.dhis.android.core.arch.api.executors.internal.RxAPICallExecutor
import org.hisp.dhis.android.core.arch.handlers.internal.Handler
import org.hisp.dhis.android.core.maintenance.D2ErrorSamples
import org.hisp.dhis.android.core.settings.AppearanceSettings
import org.hisp.dhis.android.core.settings.FilterSetting
import org.hisp.dhis.android.core.settings.ProgramConfigurationSetting
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class AppearanceSettingsCallShould {
private val filterSettingHandler: Handler<FilterSetting> = mock()
private val programConfigurationHandler: Handler<ProgramConfigurationSetting> = mock()
private val service: SettingAppService = mock()
private val apiCallExecutor: RxAPICallExecutor = mock()
private val appVersionManager: SettingsAppInfoManager = mock()
private val appearanceSettings: AppearanceSettings = mock()
private val appearanceSettingsSingle: Single<AppearanceSettings> = Single.just(appearanceSettings)
private lateinit var appearanceSettingsCall: AppearanceSettingCall
@Before
fun setUp() {
whenever(service.appearanceSettings(any())) doReturn appearanceSettingsSingle
appearanceSettingsCall = AppearanceSettingCall(
filterSettingHandler,
programConfigurationHandler,
service,
apiCallExecutor,
appVersionManager
)
}
@Test
fun call_appearances_endpoint_if_version_1() {
whenever(appVersionManager.getDataStoreVersion()) doReturn Single.just(SettingsAppDataStoreVersion.V1_1)
appearanceSettingsCall.getCompletable(false).blockingAwait()
verify(service, never()).appearanceSettings(any())
}
@Test
fun call_appearances_endpoint_if_version_2() {
whenever(apiCallExecutor.wrapSingle(appearanceSettingsSingle, false)) doReturn appearanceSettingsSingle
whenever(appVersionManager.getDataStoreVersion()) doReturn Single.just(SettingsAppDataStoreVersion.V2_0)
appearanceSettingsCall.getCompletable(false).blockingAwait()
verify(service).appearanceSettings(any())
}
@Test
fun default_to_empty_collection_if_not_found() {
whenever(appVersionManager.getDataStoreVersion()) doReturn Single.just(SettingsAppDataStoreVersion.V2_0)
whenever(apiCallExecutor.wrapSingle(appearanceSettingsSingle, false)) doReturn
Single.error(D2ErrorSamples.notFound())
appearanceSettingsCall.getCompletable(false).blockingAwait()
verify(filterSettingHandler).handleMany(emptyList())
verifyNoMoreInteractions(filterSettingHandler)
verify(programConfigurationHandler).handleMany(emptyList())
verifyNoMoreInteractions(programConfigurationHandler)
}
}
| bsd-3-clause | c6c321a44b2ded6f4f169726d51ff10b | 43.252427 | 112 | 0.766345 | 4.655771 | false | true | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/packet/PacketOutWorldBorder.kt | 1 | 3728 | /*
* Copyright (C) 2016-Present The MoonLake ([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.mcmoonlake.api.packet
import com.mcmoonlake.api.Valuable
import com.mcmoonlake.api.ofValuableNotNull
data class PacketOutWorldBorder(
var action: Action,
var size: Double,
var oldSize: Double,
var newSize: Double,
var speed: Long,
var centerX: Double,
var centerZ: Double,
var portalTeleportBoundary: Int,
var warningTime: Int,
var warningBlocks: Int
) : PacketOutBukkitAbstract("PacketPlayOutWorldBorder") {
@Deprecated("")
constructor() : this(Action.INITIALIZE, .0, .0, .0, 0L, .0, .0, 0, 0, 0)
override fun read(data: PacketBuffer) {
action = ofValuableNotNull(data.readVarInt())
when(action) {
Action.SET_SIZE -> size = data.readDouble()
Action.LERP_SIZE -> {
oldSize = data.readDouble()
newSize = data.readDouble()
speed = data.readVarLong()
}
Action.SET_CENTER -> {
centerX = data.readDouble()
centerZ = data.readDouble()
}
Action.INITIALIZE -> {
centerX = data.readDouble()
centerZ = data.readDouble()
oldSize = data.readDouble()
newSize = data.readDouble()
speed = data.readVarLong()
portalTeleportBoundary = data.readVarInt()
warningTime = data.readVarInt()
warningBlocks = data.readVarInt()
}
Action.SET_WARNING_TIME -> warningTime = data.readVarInt()
Action.SET_WARNING_BLOCKS -> warningBlocks = data.readVarInt()
}
}
override fun write(data: PacketBuffer) {
data.writeVarInt(action.value())
when(action) {
Action.SET_SIZE -> data.writeDouble(size)
Action.LERP_SIZE -> {
data.writeDouble(oldSize)
data.writeDouble(newSize)
data.writeVarLong(speed)
}
Action.SET_CENTER -> {
data.writeDouble(centerX)
data.writeDouble(centerZ)
}
Action.INITIALIZE -> {
data.writeDouble(centerX)
data.writeDouble(centerZ)
data.writeDouble(oldSize)
data.writeDouble(newSize)
data.writeVarLong(speed)
data.writeVarInt(portalTeleportBoundary)
data.writeVarInt(warningTime)
data.writeVarInt(warningBlocks)
}
Action.SET_WARNING_TIME -> data.writeVarInt(warningTime)
Action.SET_WARNING_BLOCKS -> data.writeVarInt(warningBlocks)
}
}
enum class Action(val value: Int) : Valuable<Int> {
SET_SIZE(0),
LERP_SIZE(1),
SET_CENTER(2),
INITIALIZE(3),
SET_WARNING_TIME(4),
SET_WARNING_BLOCKS(5),
;
override fun value(): Int
= value
}
}
| gpl-3.0 | 342a8dc6a17fa88b2d069de8485df7a1 | 33.518519 | 76 | 0.578326 | 4.591133 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/trigram/Trigram4.kt | 1 | 1775 | package katas.kotlin.trigram
import org.junit.Test
import java.io.File
import java.util.*
class Trigram4 {
@Test fun `create trigram map and generate delirious text`() {
val words = listOf(
File("src/katas/kotlin/trigram/18440-0.txt"),
File("src/katas/kotlin/trigram/39702-0.txt"),
File("src/katas/kotlin/trigram/53970-0.txt")
).flatMap{ it.readWords() }
val trigramMap = words.windowed(size = 3)
.map { Trigram(it[0], it[1], it[2]) }
.groupBy { Pair(it.first.normalise(), it.second.normalise()) }
val random = Random(123)
val initial = trigramMap.values.elementAt(random.nextInt(trigramMap.size)).let {
it[random.nextInt(it.size)]
}
val trigrams = generateSequence(initial) {
val nextWords = trigramMap[Pair(it.second.normalise(), it.third.normalise())]!!
nextWords[random.nextInt(nextWords.size)]
}
trigrams.map{ it.third }
.take(200)
.forEach {
print(it + " ")
}
}
private data class Trigram(val first: String, val second: String, val third: String)
private fun String.normalise(): String {
return this.trim()
.toLowerCase()
.replace("-", "")
.replace("_", "")
.replace(",", "")
.replace(";", "")
.replace(":", "")
.replace(".", "")
.replace("!", "")
.replace("?", "")
.replace("'", "")
}
private fun File.readWords(): List<String> {
val regex = Regex("\\s+")
return this.readLines()
.flatMap { it.split(regex) }
.map{ it.replace("_", "") }
}
}
| unlicense | 177df52c5df5dbd0848289dde17f54f3 | 30.696429 | 91 | 0.51493 | 3.979821 | false | false | false | false |
phylame/jem | jem-crawler/src/main/kotlin/jem/crawler/impl/Duxia.kt | 1 | 2482 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jem.crawler.impl
import jclp.io.baseName
import jclp.setting.Settings
import jclp.text.textOf
import jclp.toLocalDateTime
import jem.*
import jem.crawler.*
import jem.crawler.M as T
class Duxia : ReusableCrawler() {
override val name = T.tr("duxia.org")
override val keys = setOf("www.duxia.org")
override fun getBook(url: String, settings: Settings?): Book {
val path = url.replace("du/[\\d]+/([\\d]+)/".toRegex(), "book/$1.html")
val book = CrawlerBook(path, "duxia")
book.bookId = baseName(path)
val soup = fetchSoup(path, "get", settings)
val head = soup.head()
book.title = getOgMeta(head, "title")
book.author = getOgMeta(head, "novel:author")
book.genre = getOgMeta(head, "novel:category")
book.cover = CrawlerFlob(getOgMeta(head, "image"), "get", settings)
book.state = getOgMeta(head, "novel:status")
book.updateTime = getOgMeta(head, "novel:update_time").toLocalDateTime()
book.lastChapter = getOgMeta(head, "novel:latest_chapter_name")
val stub = soup.selectFirst("div.articleInfo")
book.words = stub.selectFirst("ol strong:eq(6)").text()
book.intro = textOf(stub.selectFirst("dd").ownText())
getContents(book, stub.selectFirst("a.reader").absUrl("href"), settings)
return book
}
private fun getContents(book: Book, url: String, settings: Settings?) {
val soup = fetchSoup(url, "get", settings)
for (a in soup.select("div.readerListShow a")) {
val chapter = book.newChapter(a.text())
chapter.setText(a.absUrl("href"), settings)
}
}
override fun getText(url: String, settings: Settings?): String =
fetchSoup(url, "get", settings).selectText("div#content", System.lineSeparator())
}
| apache-2.0 | ae3325651b03d80f941b7320e7a529f9 | 35.5 | 93 | 0.662369 | 3.749245 | false | false | false | false |
google/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/editor/paste/EditorFileDropHandler.kt | 3 | 4304 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor.paste
import com.intellij.ide.dnd.FileCopyPasteUtil
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.executeCommand
import com.intellij.openapi.editor.*
import com.intellij.openapi.editor.actionSystem.EditorActionManager
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiEditorUtil
import com.intellij.refactoring.RefactoringBundle
import org.intellij.images.fileTypes.ImageFileTypeManager
import org.intellij.images.fileTypes.impl.SvgFileType
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.editor.images.ImageUtils
import org.intellij.plugins.markdown.editor.runForEachCaret
import org.intellij.plugins.markdown.lang.MarkdownLanguageUtils.isMarkdownLanguage
import java.awt.datatransfer.Transferable
import java.nio.file.Path
import kotlin.io.path.extension
import kotlin.io.path.name
import kotlin.io.path.relativeTo
internal class EditorFileDropHandler: CustomFileDropHandler() {
override fun canHandle(transferable: Transferable, editor: Editor?): Boolean {
if (editor == null || !editor.document.isWritable) {
return false
}
val file = PsiEditorUtil.getPsiFile(editor)
return file.language.isMarkdownLanguage()
}
override fun handleDrop(transferable: Transferable, editor: Editor?, project: Project?): Boolean {
if (editor == null || project == null) {
return false
}
val file = PsiEditorUtil.getPsiFile(editor)
if (!file.language.isMarkdownLanguage() || !editor.document.isWritable) {
return false
}
val files = FileCopyPasteUtil.getFiles(transferable)?.asSequence() ?: return false
val content = buildTextContent(files, file)
val document = editor.document
runWriteAction {
handleReadOnlyModificationException(project, document) {
executeCommand(project, commandName) {
editor.caretModel.runForEachCaret(reverseOrder = true) { caret ->
document.insertString(caret.offset, content)
caret.moveToOffset(content.length)
}
}
}
}
return true
}
companion object {
private val commandName
get() = MarkdownBundle.message("markdown.image.file.drop.handler.drop.command.name")
internal fun buildTextContent(files: Sequence<Path>, file: PsiFile): String {
val imageFileType = ImageFileTypeManager.getInstance().imageFileType
val registry = FileTypeRegistry.getInstance()
val currentDirectory = file.containingDirectory?.virtualFile?.toNioPath()
val relativePaths = files.map { obtainRelativePath(it, currentDirectory) }
return relativePaths.joinToString(separator = "\n") { path ->
when (registry.getFileTypeByExtension(path.extension)) {
imageFileType, SvgFileType.INSTANCE -> ImageUtils.createMarkdownImageText(
description = path.name,
path = FileUtil.toSystemIndependentName(path.toString())
)
else -> createFileLink(path)
}
}
}
private fun obtainRelativePath(path: Path, currentDirectory: Path?): Path {
if (currentDirectory == null) {
return path
}
return path.relativeTo(currentDirectory)
}
private fun createFileLink(file: Path): String {
val independentPath = FileUtil.toSystemIndependentName(file.toString())
return "[${file.name}]($independentPath)"
}
internal fun handleReadOnlyModificationException(project: Project, document: Document, block: () -> Unit) {
try {
block.invoke()
} catch (exception: ReadOnlyModificationException) {
Messages.showErrorDialog(project, exception.localizedMessage, RefactoringBundle.message("error.title"))
} catch (exception: ReadOnlyFragmentModificationException) {
EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(exception)
}
}
}
}
| apache-2.0 | e9b8d1cd25dffe755a0bb464bb399ca2 | 40.786408 | 158 | 0.739777 | 4.719298 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/map/MapVariantAdapter.kt | 4 | 3474 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.map
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.databinding.ItemMapVariantBinding
import com.google.samples.apps.iosched.util.executeAfter
internal class MapVariantAdapter(
private val callback: (MapVariant) -> Unit
) : Adapter<MapVariantViewHolder>() {
var currentSelection: MapVariant? = null
set(value) {
if (field == value) {
return
}
val previous = field
if (previous != null) {
notifyItemChanged(items.indexOf(previous)) // deselect previous selection
}
field = value
if (value != null) {
notifyItemChanged(items.indexOf(value)) // select new selection
}
}
private val items = MapVariant.values().toMutableList().apply {
sortBy { it.start }
}
override fun getItemCount(): Int = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MapVariantViewHolder {
return MapVariantViewHolder(
ItemMapVariantBinding.inflate(
LayoutInflater.from(parent.context), parent, false
)
)
}
override fun onBindViewHolder(holder: MapVariantViewHolder, position: Int) {
val mapVariant = items[position]
holder.bind(mapVariant, mapVariant == currentSelection, callback)
}
}
internal class MapVariantViewHolder(
val binding: ItemMapVariantBinding
) : ViewHolder(binding.root) {
fun bind(mapVariant: MapVariant, isSelected: Boolean, callback: (MapVariant) -> Unit) {
binding.executeAfter {
variant = mapVariant
isChecked = isSelected
}
itemView.setOnClickListener {
callback(mapVariant)
}
}
}
// This is used instead of drawableStart="@{int_value}" because Databinding interprets the int as a
// color instead of a drawable resource ID.
@BindingAdapter("variantIcon")
fun variantIcon(view: TextView, @DrawableRes iconResId: Int) {
val drawable = AppCompatResources.getDrawable(view.context, iconResId)
// Below API 23 we need to apply the drawableTint manually.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
drawable?.setTintList(
AppCompatResources.getColorStateList(view.context, R.color.map_variant_icon)
)
}
view.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, null, null)
}
| apache-2.0 | 336bfd1346eeb5003487c68e9d29904e | 34.44898 | 99 | 0.696315 | 4.613546 | false | false | false | false |
square/okhttp | okhttp/src/commonTest/kotlin/okhttp3/ResponseBodyTest.kt | 3 | 4041 | /*
* Copyright (C) 2016 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
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isTrue
import kotlin.test.Test
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.Buffer
import okio.BufferedSource
import okio.ByteString.Companion.decodeHex
import okio.ByteString.Companion.encodeUtf8
import okio.IOException
import okio.Source
import okio.buffer
class ResponseBodyTest {
@Test
fun sourceEmpty() {
val mediaType = if (null == null) null else "any/thing; charset=${null}".toMediaType()
val body = "".decodeHex().toResponseBody(mediaType)
val source = body.source()
assertThat(source.exhausted()).isTrue()
assertThat(source.readUtf8()).isEqualTo("")
}
@Test
fun sourceClosesUnderlyingSource() {
var closed = false
val body: ResponseBody = object : ResponseBody() {
override fun contentType(): MediaType? {
return null
}
override fun contentLength(): Long {
return 5
}
override fun source(): BufferedSource {
val source = Buffer().writeUtf8("hello")
return object : ForwardingSource(source) {
override fun close() {
closed = true
super.close()
}
}.buffer()
}
}
body.source().close()
assertThat(closed).isTrue()
}
@Test
fun throwingUnderlyingSourceClosesQuietly() {
val body: ResponseBody = object : ResponseBody() {
override fun contentType(): MediaType? {
return null
}
override fun contentLength(): Long {
return 5
}
override fun source(): BufferedSource {
val source = Buffer().writeUtf8("hello")
return object : ForwardingSource(source) {
@Throws(IOException::class)
override fun close() {
throw IOException("Broken!")
}
}.buffer()
}
}
assertThat(body.source().readUtf8()).isEqualTo("hello")
body.close()
}
@Test
fun unicodeText() {
val text = "eile oli oliiviõli"
val body = text.toResponseBody()
assertThat(body.string()).isEqualTo(text)
}
@Test
fun unicodeTextWithCharset() {
val text = "eile oli oliiviõli"
val body = text.toResponseBody("text/plain; charset=UTF-8".toMediaType())
assertThat(body.string()).isEqualTo(text)
}
@Test
fun unicodeByteString() {
val text = "eile oli oliiviõli"
val body = text.toResponseBody()
assertThat(body.byteString()).isEqualTo(text.encodeUtf8())
}
@Test
fun unicodeByteStringWithCharset() {
val text = "eile oli oliiviõli".encodeUtf8()
val body = text.toResponseBody("text/plain; charset=EBCDIC".toMediaType())
assertThat(body.byteString()).isEqualTo(text)
}
@Test
fun unicodeBytes() {
val text = "eile oli oliiviõli"
val body = text.toResponseBody()
assertThat(body.bytes()).isEqualTo(text.encodeToByteArray())
}
@Test
fun unicodeBytesWithCharset() {
val text = "eile oli oliiviõli".encodeToByteArray()
val body = text.toResponseBody("text/plain; charset=EBCDIC".toMediaType())
assertThat(body.bytes()).isEqualTo(text)
}
}
abstract class ForwardingSource(
val delegate: Source
) : Source {
override fun read(sink: Buffer, byteCount: Long): Long = delegate.read(sink, byteCount)
override fun timeout() = delegate.timeout()
override fun close() = delegate.close()
}
| apache-2.0 | d4d5c32776b827dc945be426022799ae | 26.827586 | 90 | 0.674102 | 4.225131 | false | true | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/cabal/export/CabalProjectImportBuilder.kt | 1 | 2672 | package org.jetbrains.cabal.export
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalProjectImportBuilder
import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataManager
//import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.SdkTypeId
import org.jetbrains.haskell.icons.HaskellIcons
import org.jetbrains.haskell.sdk.HaskellSdkType
import com.intellij.openapi.externalSystem.model.project.ProjectData
//import org.jetbrains.cabal.settings.CabalProjectSettings
import com.intellij.openapi.externalSystem.model.DataNode
import org.jetbrains.cabal.util.*
import javax.swing.Icon
import java.io.File
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.LocalFileSystem
class CabalProjectImportBuilder(dataManager: ProjectDataManager)
: AbstractExternalProjectImportBuilder<ImportFromCabalControl>(dataManager, ImportFromCabalControl(), SYSTEM_ID) {
override fun getName(): String = "Cabal"
override fun getIcon(): Icon = HaskellIcons.CABAL
// override fun getList(): MutableList<CabalProjectSettingsControl>? {
// return arrayList(CabalProjectSettingsControl(CabalProjectSettings()))
// }
//
// override fun isMarked(element: CabalProjectSettingsControl?): Boolean {
// return false
// }
// throws(javaClass<ConfigurationException>())
// override fun setList(list: List<CabalProjectSettingsControl>?) {
// }
//
// override fun setOpenProjectSettingsAfter(on: Boolean) {
// }
override fun isSuitableSdkType(sdkType: SdkTypeId?): Boolean {
return sdkType is HaskellSdkType
}
// override fun commit(project: Project?, model: ModifiableModuleModel?, modulesProvider: ModulesProvider?, artifactModel: ModifiableArtifactModel?): MutableList<Module>? {
// return null
// }
override fun doPrepare(context: WizardContext) {
var pathToUse = fileToImport!!
val file = LocalFileSystem.getInstance()!!.refreshAndFindFileByPath(pathToUse)
if (file != null && file.isDirectory) {
pathToUse = File(pathToUse).absolutePath
}
getControl(context.project).setLinkedProjectPath(pathToUse)
}
override fun beforeCommit(dataNode: DataNode<ProjectData>, project: Project) {
}
override fun applyExtraSettings(context: WizardContext) {
}
override fun getExternalProjectConfigToUse(file: File): File {
return if (file.isDirectory) file else file.parentFile!!
}
} | apache-2.0 | ac6ceb55d45e20a69fc3031a6142478f | 37.73913 | 175 | 0.760853 | 4.671329 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ucache/kotlinScriptEntities.kt | 1 | 8871 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.core.script.ucache
import com.intellij.ide.scratch.ScratchUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.applyIf
import com.intellij.util.concurrency.annotations.RequiresWriteLock
import com.intellij.workspaceModel.ide.BuilderSnapshot
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.ide.impl.toVirtualFileUrl
import com.intellij.workspaceModel.ide.impl.virtualFile
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.dependencies.ScriptAdditionalIdeaDependenciesProvider
import java.nio.file.Path
import kotlin.io.path.pathString
import kotlin.io.path.relativeTo
/**
* This file contains functions to work with [WorkspaceModel] in the context of [KotlinScriptEntity].
* For technical details, see [this article](https://jetbrains.team/p/wm/documents/Development/a/Workspace-model-custom-entities-creation).
*/
fun KotlinScriptEntity.listDependencies(rootTypeId: KotlinScriptLibraryRootTypeId? = null): List<VirtualFile> = dependencies.asSequence()
.flatMap { it.roots }
.applyIf(rootTypeId != null) { filter { it.type == rootTypeId } }
.mapNotNull { it.url.virtualFile }
.filter { it.isValid }
.toList()
@RequiresWriteLock
internal fun Project.syncScriptEntities(actualScriptFiles: Sequence<VirtualFile>) {
var replaced: Boolean
val wsModel = WorkspaceModel.getInstance(this)
do {
val snapshot = wsModel.getBuilderSnapshot()
snapshot.syncScriptEntities(actualScriptFiles, this)
replaced = wsModel.replaceProjectModel(snapshot.getStorageReplacement())
} while (!replaced)
}
private fun BuilderSnapshot.syncScriptEntities(filesToAddOrUpdate: Sequence<VirtualFile>, project: Project) {
val fileUrlManager = VirtualFileUrlManager.getInstance(project)
val actualPaths = filesToAddOrUpdate.map { it.path }.toSet()
builder.entities(KotlinScriptEntity::class.java)
.filter { it.path !in actualPaths }
.forEach { builder.removeEntity(it) /* dependencies are removed automatically */ }
filesToAddOrUpdate.forEach { scriptFile ->
// WorkspaceModel API trait: LibraryEntity needs to be created first and only then it can be referred to (from ScriptEntity).
// ScriptEntity cannot be fully created in a single step.
val scriptDependencies = builder.addOrUpdateScriptDependencies(scriptFile, project)
val scriptEntity = builder.resolve(ScriptId(scriptFile.path))
if (scriptEntity == null) {
val scriptSource = KotlinScriptEntitySource(scriptFile.toVirtualFileUrl(fileUrlManager))
builder.addEntity(KotlinScriptEntity(scriptFile.path, scriptSource) {
this.dependencies = scriptDependencies
})
} else {
val outdatedDependencies =
builder.entitiesBySource { it == scriptEntity.entitySource }[scriptEntity.entitySource]
?.get(LibraryEntity::class.java)
?.let { it.toSet() - scriptDependencies.toSet() }
outdatedDependencies?.forEach { builder.removeEntity(it) }
builder.modifyEntity(scriptEntity) {
this.dependencies = scriptDependencies
}
}
}
}
private fun MutableEntityStorage.addOrUpdateScriptDependencies(scriptFile: VirtualFile, project: Project): List<KotlinScriptLibraryEntity> {
val configurationManager = ScriptConfigurationManager.getInstance(project)
val dependenciesClassFiles = configurationManager.getScriptDependenciesClassFiles(scriptFile)
.filterRedundantDependencies()
val dependenciesSourceFiles = configurationManager.getScriptDependenciesSourceFiles(scriptFile)
.filterRedundantDependencies()
addIdeSpecificDependencies(project, scriptFile, dependenciesClassFiles, dependenciesSourceFiles)
val fileUrlManager = VirtualFileUrlManager.getInstance(project)
val entitySource = KotlinScriptEntitySource(scriptFile.toVirtualFileUrl(fileUrlManager))
val scriptDependencies = mutableListOf<KotlinScriptLibraryEntity>() // list builders are not supported by WorkspaceModel yet
if (dependenciesClassFiles.isNotEmpty() || dependenciesSourceFiles.isNotEmpty()) {
scriptDependencies.add(
project.createLibrary(
"Script: ${scriptFile.relativeName(project)}",
dependenciesClassFiles,
dependenciesSourceFiles,
entitySource
)
)
}
val scriptSdk = configurationManager.getScriptSdk(scriptFile)
val projectSdk = ProjectRootManager.getInstance(project).projectSdk
if (scriptSdk?.homePath != projectSdk?.homePath) {
val sdkClassFiles = configurationManager.getScriptSdkDependenciesClassFiles(scriptFile)
val sdkSourceFiles = configurationManager.getScriptSdkDependenciesSourceFiles(scriptFile)
if (sdkClassFiles.isNotEmpty() || sdkSourceFiles.isNotEmpty()) {
scriptDependencies.add(
project.createLibrary(
"Script: ${scriptFile.relativeName(project)}: sdk<${scriptSdk?.name}>",
sdkClassFiles,
sdkSourceFiles,
entitySource
)
)
}
}
scriptDependencies.forEach { dependency ->
// Library entity modification is currently not detected by indexing mechanism, we use remove/add as a workaround
entities(KotlinScriptLibraryEntity::class.java)
.find { it.name == dependency.name }
?.let { removeEntity(it) }
addEntity(dependency)
}
return scriptDependencies
}
internal fun Collection<VirtualFile>.filterRedundantDependencies() =
if (Registry.`is`("kotlin.scripting.filter.redundant.deps")) {
filterNotTo(hashSetOf()) {
it.name.startsWith("groovy") ||
it.name.startsWith("kotlin-daemon-client") ||
it.name.startsWith("kotlin-script-runtime") ||
it.name.startsWith("kotlin-daemon-embeddable") ||
it.name.startsWith("kotlin-util-klib") ||
it.name.startsWith("kotlin-scripting-compiler-embeddable") ||
it.name.startsWith("kotlin-scripting-compiler-impl-embeddable") ||
it.name.startsWith("kotlin-compiler-embeddable") ||
it.name.startsWith("resources") ||
it.name.endsWith("-sources.jar") ||
with(it.toString()) {
contains("unzipped-distribution/gradle-") && contains("subprojects/")
}
}
} else {
toMutableSet()
}
fun VirtualFile.relativeName(project: Project): String {
return if (ScratchUtil.isScratch(this)) presentableName
else toNioPath().relativeTo(Path.of(project.basePath!!)).pathString
}
private fun addIdeSpecificDependencies(
project: Project,
scriptFile: VirtualFile,
classDependencies: MutableSet<VirtualFile>,
sourceDependencies: MutableSet<VirtualFile>
) {
ScriptAdditionalIdeaDependenciesProvider.getRelatedLibraries(scriptFile, project).forEach { lib ->
val provider = lib.rootProvider
provider.getFiles(OrderRootType.CLASSES).forEach { classDependencies.add(it) }
provider.getFiles(OrderRootType.SOURCES).forEach { sourceDependencies.add(it) }
}
}
private fun Project.createLibrary(
name: String,
classFiles: Collection<VirtualFile>,
sources: Collection<VirtualFile> = emptyList(),
entitySource: KotlinScriptEntitySource
): KotlinScriptLibraryEntity {
val fileUrlManager = VirtualFileUrlManager.getInstance(this)
val libraryRoots = mutableListOf<KotlinScriptLibraryRoot>()
classFiles.forEach {
val fileUrl = it.toVirtualFileUrl(fileUrlManager)
libraryRoots.add(KotlinScriptLibraryRoot(fileUrl, KotlinScriptLibraryRootTypeId.COMPILED))
}
sources.forEach {
val fileUrl = it.toVirtualFileUrl(fileUrlManager)
libraryRoots.add(KotlinScriptLibraryRoot(fileUrl, KotlinScriptLibraryRootTypeId.SOURCES))
}
return KotlinScriptLibraryEntity(name, libraryRoots, entitySource)
} | apache-2.0 | f1b1242b4ec07c55ffe592bff605c9bd | 43.582915 | 140 | 0.715252 | 5.16958 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/MoveRefactoringAction.kt | 1 | 7929 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.actions.internal.refactoringTesting
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.cases.MoveRefactoringCase
import java.io.File
import java.io.IOException
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
class MoveRefactoringAction : AnAction() {
companion object {
val WINDOW_TITLE: String get() = KotlinBundle.message("move.refactoring.testing")
const val RECENT_SELECTED_PATH = "org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.RECENT_SELECTED_PATH"
}
private val refactoring = MoveRefactoringCase()
private var iteration = 0
private var fails = 0
private var verifications = 0
private fun randomRefactoringAndCheck(
project: Project,
projectRoot: VirtualFile,
setIndicator: (String, Double) -> Unit,
actionRunner: CompilationStatusTracker,
fileTracker: FileSystemChangesTracker,
resultsFile: File,
refactoringCountBeforeCheck: Int,
cancelledChecker: () -> Boolean
) {
try {
setIndicator(KotlinBundle.message("update.indices"), 0.0)
DumbService.getInstance(project).waitForSmartMode()
setIndicator(KotlinBundle.message("perform.refactoring"), 0.1)
fileTracker.reset()
var refactoringResult: RandomMoveRefactoringResult = RandomMoveRefactoringResult.Failed
edtExecute {
refactoringResult = refactoring.tryCreateAndRun(project, refactoringCountBeforeCheck)
setIndicator(KotlinBundle.message("saving.files"), 0.3)
FileDocumentManager.getInstance().saveAllDocuments()
VfsUtil.markDirtyAndRefresh(false, true, true, projectRoot)
}
when (val localRefactoringResult = refactoringResult) {
is RandomMoveRefactoringResult.Success -> {
verifications++
setIndicator(KotlinBundle.message("compiling.project"), 0.7)
if (!actionRunner.checkByBuild(cancelledChecker)) {
fails++
resultsFile.appendText("${localRefactoringResult.caseData}\n\n")
}
}
is RandomMoveRefactoringResult.ExceptionCaused -> {
fails++
resultsFile.appendText("${localRefactoringResult.caseData}\nWith exception\n${localRefactoringResult.message}\n\n")
}
is RandomMoveRefactoringResult.Failed -> {
}
}
} finally {
setIndicator(KotlinBundle.message("reset.files"), 0.9)
fileTracker.createdFiles.toList().map {
try {
edtExecute {
runWriteAction {
if (it.exists()) it.delete(null)
}
}
} catch (e: IOException) {
//pass
}
}
gitReset(project, projectRoot)
}
setIndicator(KotlinBundle.message("text.done"), 1.0)
}
private fun createFileIfNotExist(targetPath: String): File? {
val stamp = DateTimeFormatter
.ofPattern("yyyy-MM-dd-HH-mm-ss")
.withZone(ZoneOffset.UTC)
.format(Instant.now())
.toString()
val resultsFile = File(targetPath, "REFACTORING_TEST_RESULT-$stamp.txt")
return try {
resultsFile.apply { createNewFile() }
} catch (e: IOException) {
null
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
val projectRoot = project?.guessProjectDir()
if (projectRoot === null) {
Messages.showErrorDialog(project, KotlinBundle.message("cannot.get.project.root.directory"), WINDOW_TITLE)
return
}
val dialog = MoveRefactoringActionDialog(project, projectRoot.path)
dialog.show()
if (!dialog.isOK) return
val targetPath = dialog.selectedDirectoryName
val countOfMovesBeforeCheck = dialog.selectedCount
val resultsFile = createFileIfNotExist(targetPath)
if (resultsFile === null) {
Messages.showErrorDialog(project, KotlinBundle.message("cannot.get.or.create.results.file"), WINDOW_TITLE)
return
}
PropertiesComponent.getInstance().setValue(RECENT_SELECTED_PATH, targetPath)
ProgressManager.getInstance().run(object : Task.Modal(project, WINDOW_TITLE, /* canBeCancelled = */ true) {
override fun run(indicator: ProgressIndicator) {
try {
unsafeRefactoringAndCheck(
project = project,
indicator = indicator,
projectRoot = projectRoot,
resultsFile = resultsFile,
countOfMovesBeforeCheck = countOfMovesBeforeCheck
)
} catch (e: Exception) {
if (e !is ProcessCanceledException && e.cause !is ProcessCanceledException) {
throw e
}
}
}
})
}
private fun unsafeRefactoringAndCheck(
project: Project,
indicator: ProgressIndicator,
projectRoot: VirtualFile,
resultsFile: File,
countOfMovesBeforeCheck: Int
) {
val compilationStatusTracker = CompilationStatusTracker(project)
val fileSystemChangesTracker = FileSystemChangesTracker()
val cancelledChecker = { indicator.isCanceled }
val setIndicator = { text: String, fraction: Double ->
indicator.text2 = text
indicator.fraction = fraction
}
iteration = 0
fails = 0
verifications = 0
try {
while (!cancelledChecker()) {
iteration++
indicator.text = KotlinBundle.message(
"0.try.1.with.2.fails.and.3.verifications",
WINDOW_TITLE,
iteration,
fails,
verifications
)
randomRefactoringAndCheck(
project = project,
projectRoot = projectRoot,
setIndicator = setIndicator,
actionRunner = compilationStatusTracker,
fileTracker = fileSystemChangesTracker,
resultsFile = resultsFile,
refactoringCountBeforeCheck = countOfMovesBeforeCheck,
cancelledChecker = cancelledChecker
)
}
} finally {
fileSystemChangesTracker.dispose()
indicator.stop()
}
}
}
| apache-2.0 | be0669fb7a1bca81740ed2afa02dee43 | 36.225352 | 158 | 0.607391 | 5.412287 | false | false | false | false |
vhromada/Catalog | core/src/main/kotlin/com/github/vhromada/catalog/controller/SongController.kt | 1 | 4725 | package com.github.vhromada.catalog.controller
import com.github.vhromada.catalog.common.entity.Page
import com.github.vhromada.catalog.common.filter.PagingFilter
import com.github.vhromada.catalog.entity.ChangeSongRequest
import com.github.vhromada.catalog.entity.Song
import com.github.vhromada.catalog.facade.SongFacade
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
/**
* A class represents controller for songs.
*
* @author Vladimir Hromada
*/
@RestController("songController")
@RequestMapping("rest/music/{musicUuid}/songs")
class SongController(
/**
* Facade for songs
*/
private val facade: SongFacade
) {
/**
* Returns page of songs for specified music and filter.
* <br></br>
* Validation errors:
*
* * Music doesn't exist in data storage
*
* @param musicUuid music's UUID
* @param filter filter
* @return page of songs for specified music and filter
*/
@GetMapping
fun search(
@PathVariable("musicUuid") musicUuid: String,
filter: PagingFilter
): Page<Song> {
return facade.findAll(music = musicUuid, filter = filter)
}
/**
* Returns song.
* <br></br>
* Validation errors:
*
* * Music doesn't exist in data storage
* * Song doesn't exist in data storage
*
* @param musicUuid music's UUID
* @param songUuid song's UUID
* @return song
*/
@GetMapping("{songUuid}")
fun get(
@PathVariable("musicUuid") musicUuid: String,
@PathVariable("songUuid") songUuid: String
): Song {
return facade.get(music = musicUuid, uuid = songUuid)
}
/**
* Adds song.
* <br></br>
* Validation errors:
*
* * Name is null
* * Name is empty string
* * Length of song is null
* * Length of song is negative value
* * Music doesn't exist in data storage
*
* @param musicUuid music's UUID
* @param request request fot changing song
* @return added song
*/
@PutMapping
@ResponseStatus(HttpStatus.CREATED)
fun add(
@PathVariable("musicUuid") musicUuid: String,
@RequestBody request: ChangeSongRequest
): Song {
return facade.add(music = musicUuid, request = request)
}
/**
* Updates song.
* <br></br>
* Validation errors:
*
* * Name is null
* * Name is empty string
* * Length of song is null
* * Length of song is negative value
* * Music doesn't exist in data storage
* * Song doesn't exist in data storage
*
* @param musicUuid music's UUID
* @param songUuid song's UUID
* @param request request fot changing song
* @return updated song
*/
@PostMapping("{songUuid}")
fun update(
@PathVariable("musicUuid") musicUuid: String,
@PathVariable("songUuid") songUuid: String,
@RequestBody request: ChangeSongRequest
): Song {
return facade.update(music = musicUuid, uuid = songUuid, request = request)
}
/**
* Removes song.
* <br></br>
* Validation errors:
*
* * Music doesn't exist in data storage
* * Song doesn't exist in data storage
*
* @param musicUuid music's UUID
* @param songUuid song's UUID
*/
@DeleteMapping("{songUuid}")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun remove(
@PathVariable("musicUuid") musicUuid: String,
@PathVariable("songUuid") songUuid: String
) {
facade.remove(music = musicUuid, uuid = songUuid)
}
/**
* Duplicates song.
* <br></br>
* Validation errors:
*
* * Music doesn't exist in data storage
* * Song doesn't exist in data storage
*
* @param musicUuid music's UUID
* @param songUuid song's UUID
* @return duplicated song
*/
@PostMapping("{songUuid}/duplicate")
@ResponseStatus(HttpStatus.CREATED)
fun duplicate(
@PathVariable("musicUuid") musicUuid: String,
@PathVariable("songUuid") songUuid: String
): Song {
return facade.duplicate(music = musicUuid, uuid = songUuid)
}
}
| mit | ebc3c00be7a94bed0b91c5127b8f6256 | 27.98773 | 83 | 0.642116 | 4.18512 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/code-insight/intentions-shared/src/org/jetbrains/kotlin/idea/codeInsight/intentions/shared/SwapBinaryExpressionIntention.kt | 1 | 4019 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight.intentions.shared
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.util.PsiPrecedences
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens.*
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.types.expressions.OperatorConventions
class SwapBinaryExpressionIntention : SelfTargetingIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("flip.binary.expression")
), LowPriorityAction {
companion object {
private val SUPPORTED_OPERATIONS: Set<KtSingleValueToken> by lazy {
setOf(PLUS, MUL, OROR, ANDAND, EQEQ, EXCLEQ, EQEQEQ, EXCLEQEQEQ, GT, LT, GTEQ, LTEQ)
}
private val SUPPORTED_OPERATION_NAMES: Set<String> by lazy {
SUPPORTED_OPERATIONS.asSequence().mapNotNull { OperatorConventions.BINARY_OPERATION_NAMES[it]?.asString() }.toSet() +
setOf("xor", "or", "and", "equals")
}
}
override fun isApplicableTo(element: KtBinaryExpression, caretOffset: Int): Boolean {
val opRef = element.operationReference
if (!opRef.textRange.containsOffset(caretOffset)) return false
if (leftSubject(element) == null || rightSubject(element) == null) {
return false
}
val operationToken = element.operationToken
val operationTokenText = opRef.text
if (operationToken in SUPPORTED_OPERATIONS
|| operationToken == IDENTIFIER && operationTokenText in SUPPORTED_OPERATION_NAMES
) {
setTextGetter(KotlinBundle.lazyMessage("flip.0", operationTokenText))
return true
}
return false
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
// Have to use text here to preserve names like "plus"
val convertedOperator = when (val operator = element.operationReference.text!!) {
">" -> "<"
"<" -> ">"
"<=" -> ">="
">=" -> "<="
else -> operator
}
val left = leftSubject(element) ?: return
val right = rightSubject(element) ?: return
val rightCopy = right.copied()
val leftCopy = left.copied()
left.replace(rightCopy)
right.replace(leftCopy)
element.replace(KtPsiFactory(element.project).createExpressionByPattern("$0 $convertedOperator $1", element.left!!, element.right!!))
}
private fun leftSubject(element: KtBinaryExpression): KtExpression? =
firstDescendantOfTighterPrecedence(element.left, PsiPrecedences.getPrecedence(element), KtBinaryExpression::getRight)
private fun rightSubject(element: KtBinaryExpression): KtExpression? =
firstDescendantOfTighterPrecedence(element.right, PsiPrecedences.getPrecedence(element), KtBinaryExpression::getLeft)
private fun firstDescendantOfTighterPrecedence(
expression: KtExpression?,
precedence: Int,
getChild: KtBinaryExpression.() -> KtExpression?
): KtExpression? {
if (expression is KtBinaryExpression) {
val expressionPrecedence = PsiPrecedences.getPrecedence(expression)
if (!PsiPrecedences.isTighter(expressionPrecedence, precedence)) {
return firstDescendantOfTighterPrecedence(expression.getChild(), precedence, getChild)
}
}
return expression
}
}
| apache-2.0 | 91c7e6b22feb8630c2523008b9482b0c | 42.684783 | 141 | 0.700921 | 4.95561 | false | false | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/attribute/spatial/Spatial.kt | 1 | 4006 | package graphics.scenery.attribute.spatial
import graphics.scenery.Node
import graphics.scenery.net.Networkable
import graphics.scenery.utils.MaybeIntersects
import net.imglib2.RealLocalizable
import net.imglib2.RealPositionable
import org.joml.Matrix4f
import org.joml.Quaternionf
import org.joml.Vector3f
import kotlin.reflect.KProperty
interface Spatial: RealLocalizable, RealPositionable, Networkable {
/** Model matrix **/
var model: Matrix4f
/** World transform matrix */
var world: Matrix4f
/** View matrix. May be null. */
var view: Matrix4f
/** Projection matrix. May be null. */
var projection: Matrix4f
/** World position of the [Renderable] object. */
var position: Vector3f
/** X/Y/Z scale of the object. */
var scale: Vector3f
/** Quaternion defining the rotation of the object in local coordinates. */
var rotation: Quaternionf
/** Stores whether the [model] matrix needs an update. */
var wantsComposeModel: Boolean
/** Stores whether the [model] matrix needs an update. */
var needsUpdate: Boolean
/** Stores whether the [world] matrix needs an update. */
var needsUpdateWorld: Boolean
/**
* Update the the [world] matrix of the [Spatial] node.
*
* This method will update the [model] and [world] matrices of the node,
* if [needsUpdate] is true, or [force] is true. If [recursive] is true,
* this method will also recurse into the [children] and [linkedNodes] of
* the node and update these as well.
*
* @param[recursive] Whether the [children] should be recursed into.
* @param[force] Force update irrespective of [needsUpdate] state.
*/
fun updateWorld(recursive: Boolean, force: Boolean = false)
/**
* Extracts the scaling component from the world matrix.
*
* Is not correct for world matrices with shear!
*
* @return world scale
*/
fun worldScale(): Vector3f
/**
* Extracts the rotation component from the world matrix
*
* Is not correct for world matrices with shear or are anisotropic!
*/
fun worldRotation(): Quaternionf
fun intersectAABB(origin: Vector3f, dir: Vector3f): MaybeIntersects
/**
* Returns the [Node]'s world position
*
* @returns The position in world space
*/
fun worldPosition(v: Vector3f? = null): Vector3f
/**
* Checks whether two node's bounding boxes do intersect using a simple bounding sphere test.
*/
fun intersects(other: Node): Boolean
/**
* Fits the [Node] within a box of the given dimension.
*
* @param[sideLength] - The size of the box to fit the [Node] uniformly into.
* @param[scaleUp] - Whether the model should only be scaled down, or also up.
* @return Vector3f - containing the applied scaling
*/
fun fitInto(sideLength: Float, scaleUp: Boolean = false): Vector3f
/**
* Taking this [Node]'s [boundingBox] into consideration, puts it above
* the [position] entirely.
*/
fun putAbove(position: Vector3f): Vector3f
/**
* Centers the [Node] on a given position.
*
* @param[position] - the position to center the [Node] on.
* @return Vector3f - the center offset calculcated for the [Node].
*/
fun centerOn(position: Vector3f): Vector3f
/**
* Orients the Node between points [p1] and [p2], and optionally
* [rescale]s and [reposition]s it.
*/
fun orientBetweenPoints(p1: Vector3f, p2: Vector3f, rescale: Boolean = false, reposition: Boolean = false): Quaternionf
fun orientBetweenPoints(p1: Vector3f, p2: Vector3f, rescale: Boolean): Quaternionf {
return orientBetweenPoints(p1, p2, rescale, false)
}
fun orientBetweenPoints(p1: Vector3f, p2: Vector3f): Quaternionf {
return orientBetweenPoints(p1, p2, false, false)
}
fun <R> propertyChanged(property: KProperty<*>, old: R, new: R, custom: String = "")
fun composeModel()
}
| lgpl-3.0 | b60212f57b4ee3de57c3b7b891de0c2f | 33.239316 | 123 | 0.668497 | 3.982107 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/titleLabel/ClassTitlePane.kt | 3 | 2070 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl.customFrameDecorations.header.titleLabel
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.displayUrlRelativeToProject
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil
import com.intellij.openapi.wm.impl.FrameTitleBuilder
import com.intellij.openapi.wm.impl.PlatformFrameTitleBuilder
import java.awt.Component
internal class ClassTitlePane : ClippingTitle() {
var fullPath: Boolean = true
var project: Project? = null
var classPath: String = ""
fun updatePath(c: Component) {
longText = project?.let {
if(Disposer.isDisposed(it)) {
classPath = ""
return@let ""
}
val fileEditorManager = FileEditorManager.getInstance(it)
val file = if (fileEditorManager is FileEditorManagerEx) {
val splittersFor = fileEditorManager.getSplittersFor(c)
splittersFor.currentFile
}
else {
fileEditorManager?.selectedEditor?.file
}
file?.let { fl ->
val instance = FrameTitleBuilder.getInstance()
val baseTitle = instance.getFileTitle(it, fl)
classPath = if (instance is PlatformFrameTitleBuilder) {
val fileTitle = VfsPresentationUtil.getPresentableNameForUI(project!!, file)
if (!fileTitle.endsWith(file.presentableName) || file.parent == null) {
fileTitle
} else {
displayUrlRelativeToProject(file, file.presentableUrl, it, true, false)
}
} else {
baseTitle
}
if(fullPath) classPath else baseTitle
}
} ?: kotlin.run {
classPath = ""
""
}
}
override val toolTipPart: String
get() = if (classPath.isEmpty()) "" else "$prefix$classPath$suffix"
} | apache-2.0 | dd40455fe703f86e7ef0d58630a2b243 | 32.403226 | 140 | 0.694203 | 4.569536 | false | false | false | false |
mrebollob/RestaurantBalance | app/src/main/java/com/mrebollob/m2p/presentation/view/form/FormActivity.kt | 2 | 5659 | /*
* Copyright (c) 2017. Manuel Rebollo Báez
*
* 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.mrebollob.m2p.presentation.view.form
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.design.widget.Snackbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.mrebollob.m2p.R
import com.mrebollob.m2p.presentation.presenter.form.FormPresenter
import com.mrebollob.m2p.presentation.view.BaseActivity
import com.mrebollob.m2p.utils.analytics.AnalyticsHelper
import com.mrebollob.m2p.utils.creditcard.CardNumberTextWatcher
import com.mrebollob.m2p.utils.creditcard.CreditCardTextWatcher
import com.mrebollob.m2p.utils.creditcard.ExpDateTextWatcher
import kotlinx.android.synthetic.main.activity_form.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
class FormActivity : BaseActivity(), FormMvpView, CreditCardTextWatcher.CardActionListener {
@Inject lateinit var mPresenter: FormPresenter
@Inject lateinit var mAnalyticsHelper: AnalyticsHelper
var isNewActivity = false
var expDateTextWatcher: ExpDateTextWatcher? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_form)
initializeDependencyInjector()
isNewActivity = (savedInstanceState == null)
initUI()
mAnalyticsHelper.logContentView("Credit card input view", "Input", "form-view",
"Is new", getCardNumber().isNullOrBlank().toString())
}
private fun initUI() {
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
toolbar.setNavigationOnClickListener({ onBackPressed() })
showInputMethod(numberEt)
val cardNumberTextWatcher = CardNumberTextWatcher(numberEt, this)
numberEt.addTextChangedListener(cardNumberTextWatcher)
expDateTextWatcher = ExpDateTextWatcher(this, expDateEt, this)
expDateEt.addTextChangedListener(expDateTextWatcher)
}
fun showInputMethod(view: View) {
Handler().postDelayed({
view.isFocusableInTouchMode = true
view.requestFocus()
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(numberEt, InputMethodManager.SHOW_IMPLICIT)
}, 200)
}
private fun initializeDependencyInjector() {
appComponent.inject(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu_done, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_done) {
updateCreditCard()
return true
} else {
return super.onOptionsItemSelected(item)
}
}
override fun onComplete(index: Int) {
if (index == 0) {
expDateTextWatcher?.focus()
}
}
private fun updateCreditCard() {
mPresenter.updateCreditCard(numberEt.text.toString().replace(" ", ""),
expDateEt.text.toString())
}
override fun showCreditCard(number: String?, expDate: String?) {
numberEt.setText(number)
expDateEt.setText(expDate)
if (number.isNullOrBlank()) {
title = getString(R.string.new_card)
} else {
title = getString(R.string.edit_card)
}
}
override fun showCardBalanceView() {
val returnIntent = Intent()
setResult(Activity.RESULT_OK, returnIntent)
finish()
}
override fun showInvalidCreditCardError() {
Snackbar.make(numberEt, R.string.invalid_card, Snackbar.LENGTH_LONG).show()
}
override fun showError() {
Snackbar.make(numberEt, R.string.error, Snackbar.LENGTH_LONG).show()
}
override fun onStart() {
super.onStart()
mPresenter.mCardNumber = getCardNumber()
mPresenter.mCardExpDate = getCardExpDate()
mPresenter.attachView(this, isNewActivity)
}
override fun onStop() {
super.onStop()
mPresenter.detachView()
}
private fun getCardNumber(): String? {
return intent.getStringExtra(EXTRA_CARD_NUMBER)
}
private fun getCardExpDate(): String? {
return intent.getStringExtra(EXTRA_CARD_EXPIRY)
}
companion object Navigator {
val CREDIT_CARD_FORM = 0x24
val EXTRA_CARD_NUMBER = "card_number"
val EXTRA_CARD_EXPIRY = "card_expiry"
fun openForResult(context: Activity, number: String?, expDate: String?) {
val intent = Intent(context, FormActivity::class.java)
intent.putExtra(EXTRA_CARD_NUMBER, number)
intent.putExtra(EXTRA_CARD_EXPIRY, expDate)
context.startActivityForResult(intent, CREDIT_CARD_FORM)
}
}
} | apache-2.0 | d3906414b3cbafb3d460550835abaad7 | 32.288235 | 92 | 0.69141 | 4.537289 | false | false | false | false |
TeMoMuKo/AutoStopRace | app/src/main/java/pl/temomuko/autostoprace/ui/teamslocationsmap/adapter/wall/WallViewHolder.kt | 2 | 1531 | package pl.temomuko.autostoprace.ui.teamslocationsmap.adapter.wall
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.item_wall.*
class WallViewHolder(onImageClick: ((Uri) -> Unit)?, override val containerView: View) :
RecyclerView.ViewHolder(containerView), LayoutContainer {
private var currentItem: WallItem? = null
init {
photoImageView.setOnClickListener {
currentItem?.imageUrl?.let {
val uri = Uri.parse(it)
onImageClick?.invoke(uri)
}
}
}
fun bind(item: WallItem) {
currentItem = item
with(item) {
messageTextView.visibility = if (message.isNullOrBlank()) View.GONE else View.VISIBLE
messageTextView.text = message
timeInfoTextView.text = timeInfo
locationInfoTextView.text = locationInfo
setupImage(photoImageView, imageUrl)
}
}
private fun setupImage(photoImageView: ImageView, imageUrl: String?) {
if (imageUrl != null) {
imageContainer.visibility = View.VISIBLE
Glide.with(photoImageView.context)
.load(imageUrl)
.into(photoImageView)
} else {
photoImageView.setImageDrawable(null)
imageContainer.visibility = View.GONE
}
}
}
| apache-2.0 | e2c4d4d5323584e792ec5b22f33c9c59 | 31.574468 | 97 | 0.649249 | 4.710769 | false | false | false | false |
ethauvin/semver | examples/kotlin/src/main/kotlin/com/example/Example.kt | 1 | 753 | package com.example
import net.thauvin.erik.semver.Version
import java.text.SimpleDateFormat
import java.util.Locale
@Version(properties = "example.properties", type = "kt", template = "example.mustache", className = "ExampleVersion",
keysPrefix = "example.")
class Example {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US)
println("-------------------------------------------------------")
println(" ${ExampleVersion.PROJECT} ${ExampleVersion.VERSION} ("
+ sdf.format(ExampleVersion.BUILDDATE) + ')')
println("-------------------------------------------------------")
}
}
}
| bsd-3-clause | 580da75ce5f9b5868df5acd00b3dbdc4 | 31.73913 | 117 | 0.528552 | 4.765823 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/src/internal/ExceptionsConstructor.kt | 1 | 4082 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import kotlinx.coroutines.*
import java.lang.reflect.*
import java.util.*
import java.util.concurrent.locks.*
import kotlin.concurrent.*
private val throwableFields = Throwable::class.java.fieldsCountOrDefault(-1)
private typealias Ctor = (Throwable) -> Throwable?
private val ctorCache = try {
if (ANDROID_DETECTED) WeakMapCtorCache
else ClassValueCtorCache
} catch (e: Throwable) {
// Fallback on Java 6 or exotic setups
WeakMapCtorCache
}
@Suppress("UNCHECKED_CAST")
internal fun <E : Throwable> tryCopyException(exception: E): E? {
// Fast path for CopyableThrowable
if (exception is CopyableThrowable<*>) {
return runCatching { exception.createCopy() as E? }.getOrNull()
}
return ctorCache.get(exception.javaClass).invoke(exception) as E?
}
private fun <E : Throwable> createConstructor(clz: Class<E>): Ctor {
val nullResult: Ctor = { null } // Pre-cache class
// Skip reflective copy if an exception has additional fields (that are usually populated in user-defined constructors)
if (throwableFields != clz.fieldsCountOrDefault(0)) return nullResult
/*
* Try to reflectively find constructor(), constructor(message, cause), constructor(cause) or constructor(message).
* Exceptions are shared among coroutines, so we should copy exception before recovering current stacktrace.
*/
val constructors = clz.constructors.sortedByDescending { it.parameterTypes.size }
for (constructor in constructors) {
val result = createSafeConstructor(constructor)
if (result != null) return result
}
return nullResult
}
private fun createSafeConstructor(constructor: Constructor<*>): Ctor? {
val p = constructor.parameterTypes
return when (p.size) {
2 -> when {
p[0] == String::class.java && p[1] == Throwable::class.java ->
safeCtor { e -> constructor.newInstance(e.message, e) as Throwable }
else -> null
}
1 -> when (p[0]) {
Throwable::class.java ->
safeCtor { e -> constructor.newInstance(e) as Throwable }
String::class.java ->
safeCtor { e -> (constructor.newInstance(e.message) as Throwable).also { it.initCause(e) } }
else -> null
}
0 -> safeCtor { e -> (constructor.newInstance() as Throwable).also { it.initCause(e) } }
else -> null
}
}
private inline fun safeCtor(crossinline block: (Throwable) -> Throwable): Ctor =
{ e -> runCatching { block(e) }.getOrNull() }
private fun Class<*>.fieldsCountOrDefault(defaultValue: Int) =
kotlin.runCatching { fieldsCount() }.getOrDefault(defaultValue)
private tailrec fun Class<*>.fieldsCount(accumulator: Int = 0): Int {
val fieldsCount = declaredFields.count { !Modifier.isStatic(it.modifiers) }
val totalFields = accumulator + fieldsCount
val superClass = superclass ?: return totalFields
return superClass.fieldsCount(totalFields)
}
internal abstract class CtorCache {
abstract fun get(key: Class<out Throwable>): Ctor
}
private object WeakMapCtorCache : CtorCache() {
private val cacheLock = ReentrantReadWriteLock()
private val exceptionCtors: WeakHashMap<Class<out Throwable>, Ctor> = WeakHashMap()
override fun get(key: Class<out Throwable>): Ctor {
cacheLock.read { exceptionCtors[key]?.let { return it } }
cacheLock.write {
exceptionCtors[key]?.let { return it }
return createConstructor(key).also { exceptionCtors[key] = it }
}
}
}
@IgnoreJreRequirement
private object ClassValueCtorCache : CtorCache() {
private val cache = object : ClassValue<Ctor>() {
override fun computeValue(type: Class<*>?): Ctor {
@Suppress("UNCHECKED_CAST")
return createConstructor(type as Class<out Throwable>)
}
}
override fun get(key: Class<out Throwable>): Ctor = cache.get(key)
}
| apache-2.0 | 22008a9f48afaa8af083cc54a76e822e | 36.449541 | 123 | 0.675894 | 4.274346 | false | false | false | false |
leafclick/intellij-community | python/src/com/jetbrains/python/sdk/PySdkRendering.kt | 1 | 4861 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.intellij.icons.AllIcons
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkModificator
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.LayeredIcon
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import com.jetbrains.python.sdk.pipenv.PIPENV_ICON
import com.jetbrains.python.sdk.pipenv.isPipEnv
import javax.swing.Icon
const val noInterpreterMarker: String = "<No interpreter>"
fun name(sdk: Sdk, sdkModificator: SdkModificator? = null): Triple<String?, String, String?> = name(sdk, sdkModificator?.name ?: sdk.name)
/**
* Returns modifier that shortly describes that is wrong with passed [sdk], [name] and additional info.
*/
fun name(sdk: Sdk, name: String): Triple<String?, String, String?> {
val modifier = when {
PythonSdkUtil.isInvalid(sdk) || PythonSdkType.hasInvalidRemoteCredentials(sdk) -> "invalid"
PythonSdkType.isIncompleteRemote(sdk) -> "incomplete"
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) -> "unsupported"
else -> null
}
val secondary = if (sdk.isPipEnv) sdk.versionString else if (PythonSdkType.isRunAsRootViaSudo(sdk)) "[sudo]" else null
return Triple(modifier, name, secondary)
}
/**
* Returns a path to be rendered as the sdk's path.
*
* Initial value is taken from the [sdkModificator] or the [sdk] itself,
* then it is converted to a path relative to the user home directory.
*
* Returns null if the initial path or the relative value are presented in the sdk's name.
*
* @see FileUtil.getLocationRelativeToUserHome
*/
fun path(sdk: Sdk, sdkModificator: SdkModificator? = null): String? {
val name = sdkModificator?.name ?: sdk.name
val homePath = sdkModificator?.homePath ?: sdk.homePath ?: return null
return homePath.let { FileUtil.getLocationRelativeToUserHome(it) }.takeIf { homePath !in name && it !in name }
}
/**
* Returns an icon to be used as the sdk's icon.
*
* Result is wrapped with [AllIcons.Actions.Cancel]
* if the sdk is local and does not exist, or remote and incomplete or has invalid credentials, or is not supported.
*
* @see PythonSdkType.isInvalid
* @see PythonSdkType.isIncompleteRemote
* @see PythonSdkType.hasInvalidRemoteCredentials
* @see LanguageLevel.SUPPORTED_LEVELS
*/
fun icon(sdk: Sdk): Icon? {
val flavor = PythonSdkFlavor.getPlatformIndependentFlavor(sdk.homePath)
val icon = if (flavor != null) flavor.icon else (sdk.sdkType as? SdkType)?.icon ?: return null
return when {
PythonSdkUtil.isInvalid(sdk) ||
PythonSdkType.isIncompleteRemote(sdk) ||
PythonSdkType.hasInvalidRemoteCredentials(sdk) ||
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) ->
wrapIconWithWarningDecorator(icon)
sdk is PyDetectedSdk ->
IconLoader.getTransparentIcon(icon)
// XXX: We cannot provide pipenv SDK flavor by path since it's just a regular virtualenv. Consider
// adding the SDK flavor based on the `Sdk` object itself
// TODO: Refactor SDK flavors so they can actually provide icons for SDKs in all cases
sdk.isPipEnv ->
PIPENV_ICON
else ->
icon
}
}
/**
* Groups valid sdks associated with the [module] by types.
* Virtual environments, pipenv and conda environments are considered as [PyRenderedSdkType.VIRTUALENV].
* Remote interpreters are considered as [PyRenderedSdkType.REMOTE].
* All the others are considered as [PyRenderedSdkType.SYSTEM].
*
* @see Sdk.isAssociatedWithAnotherModule
* @see PythonSdkType.isVirtualEnv
* @see PythonSdkType.isCondaVirtualEnv
* @see PythonSdkType.isRemote
* @see PyRenderedSdkType
*/
fun groupModuleSdksByTypes(allSdks: List<Sdk>, module: Module?, invalid: (Sdk) -> Boolean): Map<PyRenderedSdkType, List<Sdk>> {
return allSdks
.asSequence()
.filter { !it.isAssociatedWithAnotherModule(module) && !invalid(it) }
.groupBy {
when {
PythonSdkUtil.isVirtualEnv(it) || PythonSdkUtil.isCondaVirtualEnv(it) -> PyRenderedSdkType.VIRTUALENV
PythonSdkUtil.isRemote(it) -> PyRenderedSdkType.REMOTE
else -> PyRenderedSdkType.SYSTEM
}
}
}
/**
* Order is important, sdks are rendered in the same order as the types are defined.
*
* @see groupModuleSdksByTypes
*/
enum class PyRenderedSdkType {
VIRTUALENV, SYSTEM, REMOTE
}
private fun wrapIconWithWarningDecorator(icon: Icon): LayeredIcon =
LayeredIcon(2).apply {
setIcon(icon, 0)
setIcon(AllIcons.Actions.Cancel, 1)
}
| apache-2.0 | 0e7cf6917dae22160a33e06376bffea1 | 37.579365 | 140 | 0.747789 | 4.264035 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-tests/src/test/kotlin/test/setup/SampleInheritedApi.kt | 1 | 1207 | package test.setup
import slatekit.apis.Action
import slatekit.common.DateTime
/**
* Sample 1:
* This is the simplest example of APIs in Slate Kit.
* APIs are designed to be "Universal" and "Protocol Independent" which means
* that these can be hosted as Web/HTTP APIs and CLI ( Command Line )
*
* NOTES:
* 1. POKO : Plain old kotlin object without any framework code
* 2. Actions : Only public methods declared in this class will be exposed
* 3. Protocol : This API can be accessed via HTTP and/or on the CLI
* 4. Arguments : Method params are automatically loaded
* 5. Annotations: This examples has 0 annotations, but you can add them
* to explicitly declare and configure the APIs
*/
open class SampleExtendedApi : SamplePOKOApi() {
fun getSeconds():Int = DateTime.now().second
fun ping(greeting:String):String = "$greeting back"
}
open class SampleAnnoBaseApi {
@Action()
fun hello(greeting: String): String = "$greeting back"
}
open class SampleAnnoExtendedApi : SampleAnnoBaseApi() {
@Action(name = "seconds")
fun getSeconds():Int = DateTime.now().second
@Action()
fun ping(greeting:String):String = "$greeting back"
}
| apache-2.0 | ef08d35e4405b18b827b1144c64c8506 | 29.948718 | 77 | 0.700911 | 3.983498 | false | false | false | false |
alibaba/transmittable-thread-local | ttl2-compatible/src/test/java/com/alibaba/ttl/reported_bugs/Bug70_Test.kt | 1 | 1418 | package com.alibaba.ttl.reported_bugs
import com.alibaba.noTtlAgentRun
import com.alibaba.ttl.TransmittableThreadLocal
import com.alibaba.ttl.TtlRunnable
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.concurrent.Executors
import java.util.concurrent.FutureTask
import java.util.concurrent.atomic.AtomicReference
import kotlin.concurrent.thread
/**
* Bug URL: https://github.com/alibaba/transmittable-thread-local/issues/70
* Reporter: @aftersss
*/
class Bug70_Test {
@Test
fun test_bug70() {
val hello = "hello"
val executorService = Executors.newSingleThreadExecutor()
val threadLocal = TransmittableThreadLocal<String>().apply { set(hello) }
assertEquals(hello, threadLocal.get())
FutureTask { threadLocal.get() }.also {
val runnable = if (noTtlAgentRun()) TtlRunnable.get(it) else it
executorService.submit(runnable)
assertEquals(hello, it.get())
}
val taskRef = AtomicReference<FutureTask<String>>()
thread(name = "the thread for run executor action") {
FutureTask { threadLocal.get() }.also {
val runnable = if (noTtlAgentRun()) TtlRunnable.get(it, false, false) else it
executorService.submit(runnable)
taskRef.set(it)
}
}.join()
assertEquals(hello, taskRef.get().get())
}
}
| apache-2.0 | d4dcb7de5896d78ef2fa6a8dd9f98125 | 32.761905 | 93 | 0.668547 | 4.31003 | false | true | false | false |
blokadaorg/blokada | android5/app/src/main/java/ui/stats/StatsRetentionView.kt | 1 | 3554 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package ui.stats
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView
import androidx.lifecycle.LifecycleCoroutineScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.blokada.R
import repository.Repos
class StatsRetentionView : FrameLayout {
constructor(context: Context) : super(context) {
init(null, 0)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(attrs, 0)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
init(attrs, defStyle)
}
lateinit var lifecycleScope: LifecycleCoroutineScope
var openPolicy = {}
private val cloudRepo by lazy { Repos.cloud }
private fun init(attrs: AttributeSet?, defStyle: Int) {
// Inflate
LayoutInflater.from(context).inflate(R.layout.view_retention, this, true)
}
fun setup() {
val root = this
val retentionText = root.findViewById<TextView>(R.id.retention_text)
val retentionContinue = root.findViewById<Button>(R.id.retention_continue)
val retentionCurrent = root.findViewById<View>(R.id.retention_current)
val retentionProgress = root.findViewById<View>(R.id.retention_progress)
val retentionPolicy = root.findViewById<TextView>(R.id.retention_policy)
retentionPolicy.setOnClickListener {
openPolicy()
}
val switchWorking = { working: Boolean ->
if (working) {
retentionContinue.isEnabled = false
retentionCurrent.visibility = View.GONE
retentionProgress.visibility = View.VISIBLE
} else {
retentionContinue.isEnabled = true
retentionCurrent.visibility = View.VISIBLE
retentionProgress.visibility = View.GONE
}
}
switchWorking(false)
lifecycleScope.launch {
cloudRepo.activityRetentionHot
.collect {
switchWorking(false)
val enabled = it == "24h"
if (enabled) {
retentionText.text = context.getString(R.string.activity_retention_option_twofourh)
retentionContinue.text = context.getString(R.string.home_power_action_turn_off)
retentionContinue.setOnClickListener {
switchWorking(true)
lifecycleScope.launch { cloudRepo.setActivityRetention("") }
}
} else {
retentionText.text = context.getString(R.string.activity_retention_option_none)
retentionContinue.text = context.getString(R.string.home_power_action_turn_on)
retentionContinue.setOnClickListener {
switchWorking(true)
lifecycleScope.launch { cloudRepo.setActivityRetention("24h") }
}
}
}
}
}
} | mpl-2.0 | 3a4a10a401d2b75073995d23a2fc17c4 | 33.504854 | 105 | 0.629609 | 4.718459 | false | false | false | false |
smmribeiro/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/personalization/impl/PrefixLengthFactor.kt | 9 | 2509 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.completion.ml.personalization.impl
import com.intellij.completion.ml.personalization.UserFactorBase
import com.intellij.completion.ml.personalization.UserFactorDescriptions
import com.intellij.completion.ml.personalization.UserFactorReaderBase
import com.intellij.completion.ml.personalization.UserFactorUpdaterBase
/**
* @author Vitaliy.Bibaev
*/
class PrefixLengthReader(factor: DailyAggregatedDoubleFactor) : UserFactorReaderBase(factor) {
fun getCountsByPrefixLength(): Map<Int, Double> {
return factor.aggregateSum().asIterable().associate { (key, value) -> key.toInt() to value }
}
fun getAveragePrefixLength(): Double? {
val lengthToCount = getCountsByPrefixLength()
if (lengthToCount.isEmpty()) return null
val totalChars = lengthToCount.asSequence().sumByDouble { it.key * it.value }
val completionCount = lengthToCount.asSequence().sumByDouble { it.value }
if (completionCount == 0.0) return null
return totalChars / completionCount
}
}
class PrefixLengthUpdater(factor: MutableDoubleFactor) : UserFactorUpdaterBase(factor) {
fun fireCompletionPerformed(prefixLength: Int) {
factor.incrementOnToday(prefixLength.toString())
}
}
class MostFrequentPrefixLength : UserFactorBase<PrefixLengthReader>("mostFrequentPrefixLength",
UserFactorDescriptions.PREFIX_LENGTH_ON_COMPLETION) {
override fun compute(reader: PrefixLengthReader): String? {
return reader.getCountsByPrefixLength().maxByOrNull { it.value }?.key?.toString()
}
}
class AveragePrefixLength : UserFactorBase<PrefixLengthReader>("averagePrefixLength", UserFactorDescriptions.PREFIX_LENGTH_ON_COMPLETION) {
override fun compute(reader: PrefixLengthReader): String? {
return reader.getAveragePrefixLength()?.toString()
}
} | apache-2.0 | 13eb2516d8b42dc7d0c412bd9e077cf1 | 40.147541 | 139 | 0.735353 | 4.440708 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinComponentUsageInDestructuring.kt | 3 | 3312 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator
import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator.Target
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo
import org.jetbrains.kotlin.idea.refactoring.replaceListPsiAndKeepDelimiters
import org.jetbrains.kotlin.psi.KtDestructuringDeclaration
import org.jetbrains.kotlin.psi.KtDestructuringDeclarationEntry
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.buildDestructuringDeclaration
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.utils.ifEmpty
class KotlinComponentUsageInDestructuring(element: KtDestructuringDeclarationEntry) :
KotlinUsageInfo<KtDestructuringDeclarationEntry>(element) {
override fun processUsage(
changeInfo: KotlinChangeInfo,
element: KtDestructuringDeclarationEntry,
allUsages: Array<out UsageInfo>
): Boolean {
if (!changeInfo.isParameterSetOrOrderChanged) return true
val declaration = element.parent as KtDestructuringDeclaration
val currentEntries = declaration.entries
val newParameterInfos = changeInfo.getNonReceiverParameters()
val newDestructuring = KtPsiFactory(element).buildDestructuringDeclaration {
val lastIndex = newParameterInfos.indexOfLast { it.oldIndex in currentEntries.indices }
val nameValidator = CollectingNameValidator(
filter = NewDeclarationNameValidator(declaration.parent.parent, null, Target.VARIABLES)
)
appendFixedText("val (")
for (i in 0..lastIndex) {
if (i > 0) {
appendFixedText(", ")
}
val paramInfo = newParameterInfos[i]
val oldIndex = paramInfo.oldIndex
if (oldIndex >= 0 && oldIndex < currentEntries.size) {
appendChildRange(PsiChildRange.singleElement(currentEntries[oldIndex]))
} else {
appendFixedText(KotlinNameSuggester.suggestNameByName(paramInfo.name, nameValidator))
}
}
appendFixedText(")")
}
replaceListPsiAndKeepDelimiters(
changeInfo,
declaration,
newDestructuring,
{
apply {
val oldEntries = entries.ifEmpty { return@apply }
val firstOldEntry = oldEntries.first()
val lastOldEntry = oldEntries.last()
val newEntries = it.entries
if (newEntries.isNotEmpty()) {
addRangeBefore(newEntries.first(), newEntries.last(), firstOldEntry)
}
deleteChildRange(firstOldEntry, lastOldEntry)
}
},
{ entries }
)
return true
}
} | apache-2.0 | 63e3eb5e9616f6383592eedb81abbc5e | 43.173333 | 158 | 0.668478 | 5.810526 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/DebuggerFieldSyntheticScopeProvider.kt | 2 | 9929 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.evaluate
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.PropertyDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.PropertyGetterDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.PropertySetterDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.incremental.KotlinLookupLocation
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.components.JavaSourceElementFactoryImpl
import org.jetbrains.kotlin.load.java.components.TypeUsage
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaClassDescriptor
import org.jetbrains.kotlin.load.java.lazy.types.toAttributes
import org.jetbrains.kotlin.load.java.structure.classId
import org.jetbrains.kotlin.load.kotlin.internalName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.DescriptorFactory
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.SyntheticScope
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.synthetic.JavaSyntheticPropertiesScope
import org.jetbrains.kotlin.synthetic.SyntheticScopeProviderExtension
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithStarProjections
import org.jetbrains.org.objectweb.asm.Type
class DebuggerFieldSyntheticScopeProvider : SyntheticScopeProviderExtension {
override fun getScopes(
moduleDescriptor: ModuleDescriptor,
javaSyntheticPropertiesScope: JavaSyntheticPropertiesScope
): List<SyntheticScope> {
return listOf<SyntheticScope>(DebuggerFieldSyntheticScope(javaSyntheticPropertiesScope))
}
}
class DebuggerFieldSyntheticScope(val javaSyntheticPropertiesScope: JavaSyntheticPropertiesScope) : SyntheticScope.Default() {
private val javaSourceElementFactory = JavaSourceElementFactoryImpl()
override fun getSyntheticExtensionProperties(
receiverTypes: Collection<KotlinType>,
name: Name,
location: LookupLocation
): Collection<PropertyDescriptor> {
return getSyntheticExtensionProperties(receiverTypes, location).filter { it.name == name }
}
override fun getSyntheticExtensionProperties(
receiverTypes: Collection<KotlinType>,
location: LookupLocation
): Collection<PropertyDescriptor> {
if (!isInEvaluator(location)) {
return emptyList()
}
val result = mutableListOf<PropertyDescriptor>()
for (type in receiverTypes) {
val clazz = type.constructor.declarationDescriptor as? ClassDescriptor ?: continue
result += getSyntheticPropertiesForClass(clazz)
}
return result
}
private fun isInEvaluator(location: LookupLocation): Boolean {
val element = (location as? KotlinLookupLocation)?.element ?: return false
val containingFile = element.containingFile?.takeIf { it.isValid } as? KtFile ?: return false
val platform = containingFile.platform
if (!platform.isJvm() && !platform.isCommon()) {
return false
}
return containingFile is KtCodeFragment && containingFile.getCopyableUserData(KtCodeFragment.RUNTIME_TYPE_EVALUATOR) != null
}
private fun getSyntheticPropertiesForClass(clazz: ClassDescriptor): Collection<PropertyDescriptor> {
val collected = mutableMapOf<Name, PropertyDescriptor>()
val syntheticPropertyNames = javaSyntheticPropertiesScope
.getSyntheticExtensionProperties(listOf(clazz.defaultType), NoLookupLocation.FROM_SYNTHETIC_SCOPE)
.mapTo(mutableSetOf()) { it.name }
collectPropertiesWithParent(clazz, syntheticPropertyNames, collected)
return collected.values
}
private tailrec fun collectPropertiesWithParent(
clazz: ClassDescriptor,
syntheticNames: Set<Name>,
consumer: MutableMap<Name, PropertyDescriptor>
) {
when (clazz) {
is LazyJavaClassDescriptor -> collectJavaProperties(clazz, syntheticNames, consumer)
is JavaClassDescriptor -> error("Unsupported Java class type")
else -> collectKotlinProperties(clazz, consumer)
}
val superClass = clazz.getSuperClassNotAny()
if (superClass != null) {
collectPropertiesWithParent(superClass, syntheticNames, consumer)
}
}
private fun collectKotlinProperties(clazz: ClassDescriptor, consumer: MutableMap<Name, PropertyDescriptor>) {
for (descriptor in clazz.unsubstitutedMemberScope.getDescriptorsFiltered(DescriptorKindFilter.VARIABLES)) {
val propertyDescriptor = descriptor as? PropertyDescriptor ?: continue
val name = propertyDescriptor.name
if (propertyDescriptor.backingField == null || name in consumer) continue
val type = propertyDescriptor.type
val sourceElement = propertyDescriptor.source
val isVar = propertyDescriptor.isVar
consumer[name] = createSyntheticPropertyDescriptor(
clazz,
type,
name,
isVar,
KotlinDebuggerEvaluationBundle.message("backing.field"),
sourceElement
) { state ->
state.typeMapper.mapType(clazz.defaultType)
}
}
}
private fun collectJavaProperties(
clazz: LazyJavaClassDescriptor,
syntheticNames: Set<Name>,
consumer: MutableMap<Name, PropertyDescriptor>
) {
val javaClass = clazz.jClass
for (field in javaClass.fields) {
val fieldName = field.name
if (field.isEnumEntry || field.isStatic || fieldName in consumer || fieldName !in syntheticNames) continue
val ownerClassName = javaClass.classId?.internalName ?: continue
val typeResolver = clazz.outerContext.typeResolver
val type = typeResolver.transformJavaType(field.type, TypeUsage.COMMON.toAttributes()).replaceArgumentsWithStarProjections()
val sourceElement = javaSourceElementFactory.source(field)
val isVar = !field.isFinal
consumer[fieldName] = createSyntheticPropertyDescriptor(
clazz,
type,
fieldName,
isVar,
KotlinDebuggerEvaluationBundle.message("java.field"),
sourceElement
) {
Type.getObjectType(ownerClassName)
}
}
}
private fun createSyntheticPropertyDescriptor(
clazz: ClassDescriptor,
type: KotlinType,
fieldName: Name,
isVar: Boolean,
description: String,
sourceElement: SourceElement,
ownerType: (GenerationState) -> Type
): PropertyDescriptor {
val propertyDescriptor = DebuggerFieldPropertyDescriptor(clazz, fieldName.asString(), description, ownerType, isVar)
val extensionReceiverParameter = DescriptorFactory.createExtensionReceiverParameterForCallable(
propertyDescriptor,
clazz.defaultType.replaceArgumentsWithStarProjections(),
Annotations.EMPTY
)
propertyDescriptor.setType(type, emptyList(), null, extensionReceiverParameter)
val getter = PropertyGetterDescriptorImpl(
propertyDescriptor, Annotations.EMPTY, Modality.FINAL,
DescriptorVisibilities.PUBLIC, false, false, false,
CallableMemberDescriptor.Kind.SYNTHESIZED,
null, sourceElement
).apply { initialize(type) }
val setter = if (isVar) PropertySetterDescriptorImpl(
propertyDescriptor, Annotations.EMPTY, Modality.FINAL,
DescriptorVisibilities.PUBLIC, false, false, false,
CallableMemberDescriptor.Kind.SYNTHESIZED,
null, sourceElement
).apply {
val setterValueParameter = ValueParameterDescriptorImpl(
this, null, 0, Annotations.EMPTY, Name.identifier("value"), type,
declaresDefaultValue = false, isCrossinline = false, isNoinline = false,
varargElementType = null, source = sourceElement
)
initialize(setterValueParameter)
} else null
propertyDescriptor.initialize(getter, setter)
return propertyDescriptor
}
}
internal class DebuggerFieldPropertyDescriptor(
containingDeclaration: DeclarationDescriptor,
val fieldName: String,
val description: String,
val ownerType: (GenerationState) -> Type,
isVar: Boolean
) : PropertyDescriptorImpl(
containingDeclaration,
null,
Annotations.EMPTY,
Modality.FINAL,
DescriptorVisibilities.PUBLIC,
/*isVar = */isVar,
Name.identifier(fieldName + "_field"),
CallableMemberDescriptor.Kind.SYNTHESIZED,
SourceElement.NO_SOURCE,
/*lateInit = */false,
/*isConst = */false,
/*isExpect = */false,
/*isActual = */false,
/*isExternal = */false,
/*isDelegated = */false
)
| apache-2.0 | 7b0c36bdb9b2e6fd468a163ea3f690f2 | 40.894515 | 158 | 0.713063 | 5.485635 | false | false | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeHintsInspection.kt | 1 | 43358 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.inspections
import com.intellij.codeInsight.controlflow.ControlFlowUtil
import com.intellij.codeInspection.*
import com.intellij.codeInspection.util.IntentionFamilyName
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache
import com.jetbrains.python.codeInsight.controlflow.ReadWriteInstruction
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.codeInsight.functionTypeComments.PyFunctionTypeAnnotationDialect
import com.jetbrains.python.codeInsight.imports.AddImportHelper
import com.jetbrains.python.codeInsight.imports.AddImportHelper.ImportPriority
import com.jetbrains.python.codeInsight.typeHints.PyTypeHintFile
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.isBitwiseOrUnionAvailable
import com.jetbrains.python.documentation.PythonDocumentationProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.resolve.PyResolveUtil
import com.jetbrains.python.psi.types.*
import com.jetbrains.python.sdk.PythonSdkUtil
class PyTypeHintsInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, PyInspectionVisitor.getContext(session))
private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) {
private val genericQName = QualifiedName.fromDottedString(PyTypingTypeProvider.GENERIC)
override fun visitPyCallExpression(node: PyCallExpression) {
super.visitPyCallExpression(node)
val callee = node.callee as? PyReferenceExpression
val calleeQName = callee?.let { PyResolveUtil.resolveImportedElementQNameLocally(it) } ?: emptyList()
if (QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_VAR) in calleeQName) {
val target = (node.parent as? PyAssignmentStatement)?.targetsToValuesMapping?.firstOrNull { it.second == node }?.first
checkTypeVarPlacement(node, target)
checkTypeVarArguments(node, target)
checkTypeVarRedefinition(target)
}
checkInstanceAndClassChecks(node)
checkParenthesesOnGenerics(node)
}
override fun visitPyClass(node: PyClass) {
super.visitPyClass(node)
val superClassExpressions = node.superClassExpressions.asList()
checkPlainGenericInheritance(superClassExpressions)
checkGenericDuplication(superClassExpressions)
checkGenericCompleteness(node)
}
override fun visitPySubscriptionExpression(node: PySubscriptionExpression) {
super.visitPySubscriptionExpression(node)
checkParameters(node)
checkParameterizedBuiltins(node)
}
private fun checkParameterizedBuiltins(node: PySubscriptionExpression) {
if (LanguageLevel.forElement(node).isAtLeast(LanguageLevel.PYTHON39)) return
val qualifier = node.qualifier
if (qualifier is PyReferenceExpression) {
val hasImportFromFuture = (node.containingFile as? PyFile)?.hasImportFromFuture(FutureFeature.ANNOTATIONS) ?: false
if (PyBuiltinCache.isInBuiltins(qualifier) && qualifier.name in PyTypingTypeProvider.TYPING_BUILTINS_GENERIC_ALIASES &&
!hasImportFromFuture) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.builtin.cannot.be.parameterized.directly", qualifier.name),
ReplaceWithTypingGenericAliasQuickFix())
}
}
}
override fun visitPyReferenceExpression(node: PyReferenceExpression) {
super.visitPyReferenceExpression(node)
if (!PyTypingTypeProvider.isInsideTypeHint(node, myTypeEvalContext)) {
return
}
if (node.referencedName == PyNames.CANONICAL_SELF) {
val typeName = myTypeEvalContext.getType(node)?.name
if (typeName != null && typeName != PyNames.CANONICAL_SELF) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.invalid.type.self"), ProblemHighlightType.GENERIC_ERROR, null,
ReplaceWithTypeNameQuickFix(typeName))
}
}
val isTopLevelTypeHint = node.parent is PyAnnotation ||
node.parent is PyExpressionStatement && node.parent.parent is PyTypeHintFile
if (isTopLevelTypeHint) {
if (resolvesToAnyOfQualifiedNames(node, PyTypingTypeProvider.LITERAL, PyTypingTypeProvider.LITERAL_EXT)) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.literal.must.have.at.least.one.parameter"))
}
if (resolvesToAnyOfQualifiedNames(node, PyTypingTypeProvider.ANNOTATED, PyTypingTypeProvider.ANNOTATED_EXT)) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.annotated.must.be.called.with.at.least.two.arguments"))
}
}
else if (resolvesToAnyOfQualifiedNames(node, PyTypingTypeProvider.TYPE_ALIAS, PyTypingTypeProvider.TYPE_ALIAS_EXT)) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.type.alias.must.be.used.as.standalone.type.hint"))
}
}
override fun visitPyFile(node: PyFile) {
super.visitPyFile(node)
if (node is PyTypeHintFile && PyTypingTypeProvider.isInsideTypeHint(node, myTypeEvalContext)) {
node.children.singleOrNull().also { if (it is PyExpressionStatement) checkTupleMatching(it.expression) }
}
}
override fun visitPyElement(node: PyElement) {
super.visitPyElement(node)
if (node is PyTypeCommentOwner &&
node is PyAnnotationOwner &&
node.typeComment?.text.let { it != null && !PyTypingTypeProvider.TYPE_IGNORE_PATTERN.matcher(it).matches() }) {
val message = PyPsiBundle.message("INSP.type.hints.type.specified.both.in.type.comment.and.annotation")
if (node is PyFunction) {
if (node.annotationValue != null || node.parameterList.parameters.any { it is PyNamedParameter && it.annotationValue != null }) {
registerProblem(node.typeComment, message, RemoveElementQuickFix(PyPsiBundle.message("QFIX.remove.type.comment")))
registerProblem(node.nameIdentifier, message, RemoveFunctionAnnotations())
}
}
else if (node.annotationValue != null) {
registerProblem(node.typeComment, message, RemoveElementQuickFix(PyPsiBundle.message("QFIX.remove.type.comment")))
registerProblem(node.annotation, message, RemoveElementQuickFix(PyPsiBundle.message("QFIX.remove.annotation")))
}
}
}
override fun visitPyFunction(node: PyFunction) {
super.visitPyFunction(node)
checkTypeCommentAndParameters(node)
}
override fun visitPyTargetExpression(node: PyTargetExpression) {
super.visitPyTargetExpression(node)
checkAnnotatedNonSelfAttribute(node)
checkTypeAliasTarget(node)
}
private fun checkTypeAliasTarget(target: PyTargetExpression) {
val parent = target.parent
if (parent is PyTypeDeclarationStatement) {
val annotation = target.annotation?.value
if (annotation is PyReferenceExpression && resolvesToAnyOfQualifiedNames(annotation, PyTypingTypeProvider.TYPE_ALIAS,
PyTypingTypeProvider.TYPE_ALIAS_EXT)) {
registerProblem(target, PyPsiBundle.message("INSP.type.hints.type.alias.must.be.immediately.initialized"))
}
}
else if (parent is PyAssignmentStatement &&
PyTypingTypeProvider.isExplicitTypeAlias(parent, myTypeEvalContext) && !PyUtil.isTopLevel(parent)) {
registerProblem(target, PyPsiBundle.message("INSP.type.hints.type.alias.must.be.top.level.declaration"))
}
}
private fun checkTypeVarPlacement(call: PyCallExpression, target: PyExpression?) {
if (target == null) {
registerProblem(call, PyPsiBundle.message("INSP.type.hints.typevar.expression.must.be.always.directly.assigned.to.variable"))
}
}
private fun checkTypeVarRedefinition(target: PyExpression?) {
val scopeOwner = ScopeUtil.getScopeOwner(target) ?: return
val name = target?.name ?: return
val instructions = ControlFlowCache.getControlFlow(scopeOwner).instructions
val startInstruction = ControlFlowUtil.findInstructionNumberByElement(instructions, target)
ControlFlowUtil.iteratePrev(startInstruction, instructions) { instruction ->
if (instruction is ReadWriteInstruction &&
instruction.num() != startInstruction &&
name == instruction.name &&
instruction.access.isWriteAccess) {
registerProblem(target, PyPsiBundle.message("INSP.type.hints.type.variables.must.not.be.redefined"))
ControlFlowUtil.Operation.BREAK
}
else {
ControlFlowUtil.Operation.NEXT
}
}
}
private fun checkTypeVarArguments(call: PyCallExpression, target: PyExpression?) {
val resolveContext = PyResolveContext.defaultContext(myTypeEvalContext)
var covariant = false
var contravariant = false
var bound: PyExpression? = null
val constraints = mutableListOf<PyExpression?>()
call
.multiMapArguments(resolveContext)
.firstOrNull { it.unmappedArguments.isEmpty() && it.unmappedParameters.isEmpty() }
?.let { mapping ->
mapping.mappedParameters.entries.forEach {
val name = it.value.name
val argument = PyUtil.peelArgument(it.key)
when (name) {
"name" ->
if (argument !is PyStringLiteralExpression) {
registerProblem(argument, PyPsiBundle.message("INSP.type.hints.typevar.expects.string.literal.as.first.argument"))
}
else {
val targetName = target?.name
if (targetName != null && targetName != argument.stringValue) {
registerProblem(argument,
PyPsiBundle.message("INSP.type.hints.argument.to.typevar.must.be.string.equal.to.variable.name"),
ReplaceWithTargetNameQuickFix(targetName))
}
}
"covariant" -> covariant = PyEvaluator.evaluateAsBoolean(argument, false)
"contravariant" -> contravariant = PyEvaluator.evaluateAsBoolean(argument, false)
"bound" -> bound = argument
"constraints" -> constraints.add(argument)
}
}
}
if (covariant && contravariant) {
registerProblem(call, PyPsiBundle.message("INSP.type.hints.bivariant.type.variables.are.not.supported"),
ProblemHighlightType.GENERIC_ERROR)
}
if (constraints.isNotEmpty() && bound != null) {
registerProblem(call, PyPsiBundle.message("INSP.type.hints.typevar.constraints.cannot.be.combined.with.bound"),
ProblemHighlightType.GENERIC_ERROR)
}
if (constraints.size == 1) {
registerProblem(call, PyPsiBundle.message("INSP.type.hints.single.typevar.constraint.not.allowed"),
ProblemHighlightType.GENERIC_ERROR)
}
constraints.asSequence().plus(bound).forEach {
if (it != null) {
val type = PyTypingTypeProvider.getType(it, myTypeEvalContext)?.get()
if (PyTypeChecker.hasGenerics(type, myTypeEvalContext)) {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.typevar.constraints.cannot.be.parametrized.by.type.variables"))
}
}
}
}
private fun checkInstanceAndClassChecks(call: PyCallExpression) {
if (call.isCalleeText(PyNames.ISINSTANCE, PyNames.ISSUBCLASS)) {
val base = call.arguments.getOrNull(1) ?: return
checkInstanceAndClassChecksOn(base)
}
}
private fun checkInstanceAndClassChecksOn(base: PyExpression) {
if (base is PyBinaryExpression && base.operator == PyTokenTypes.OR) {
if (isBitwiseOrUnionAvailable(base)) {
val left = base.leftExpression
val right = base.rightExpression
if (left != null) checkInstanceAndClassChecksOn(left)
if (right != null) checkInstanceAndClassChecksOn(right)
}
return
}
checkInstanceAndClassChecksOnTypeVar(base)
checkInstanceAndClassChecksOnReference(base)
checkInstanceAndClassChecksOnSubscription(base)
}
private fun checkInstanceAndClassChecksOnTypeVar(base: PyExpression) {
val type = myTypeEvalContext.getType(base)
if (type is PyGenericType && !type.isDefinition ||
type is PyCollectionType && type.elementTypes.any { it is PyGenericType } && !type.isDefinition) {
registerProblem(base,
PyPsiBundle.message("INSP.type.hints.type.variables.cannot.be.used.with.instance.class.checks"),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun checkInstanceAndClassChecksOnReference(base: PyExpression) {
if (base is PyReferenceExpression) {
val resolvedBase = multiFollowAssignmentsChain(base)
resolvedBase
.asSequence()
.filterIsInstance<PyQualifiedNameOwner>()
.mapNotNull { it.qualifiedName }
.forEach {
when (it) {
PyTypingTypeProvider.ANY,
PyTypingTypeProvider.UNION,
PyTypingTypeProvider.GENERIC,
PyTypingTypeProvider.OPTIONAL,
PyTypingTypeProvider.CLASS_VAR,
PyTypingTypeProvider.NO_RETURN,
PyTypingTypeProvider.FINAL,
PyTypingTypeProvider.FINAL_EXT,
PyTypingTypeProvider.LITERAL,
PyTypingTypeProvider.LITERAL_EXT,
PyTypingTypeProvider.ANNOTATED,
PyTypingTypeProvider.ANNOTATED_EXT,
PyTypingTypeProvider.TYPE_ALIAS,
PyTypingTypeProvider.TYPE_ALIAS_EXT -> {
val shortName = it.substringAfterLast('.')
registerProblem(base, PyPsiBundle.message("INSP.type.hints.type.cannot.be.used.with.instance.class.checks", shortName),
ProblemHighlightType.GENERIC_ERROR)
}
}
}
resolvedBase
.asSequence()
.filterIsInstance<PySubscriptionExpression>()
.filter { myTypeEvalContext.maySwitchToAST(it) }
.forEach { checkInstanceAndClassChecksOnSubscriptionOperand(base, it.operand) }
}
}
private fun checkInstanceAndClassChecksOnSubscription(base: PyExpression) {
if (base is PySubscriptionExpression) {
checkInstanceAndClassChecksOnSubscriptionOperand(base, base.operand)
}
}
private fun checkInstanceAndClassChecksOnSubscriptionOperand(base: PyExpression, operand: PyExpression) {
if (operand is PyReferenceExpression) {
multiFollowAssignmentsChain(operand)
.forEach {
if (it is PyQualifiedNameOwner) {
val qName = it.qualifiedName
when (qName) {
PyTypingTypeProvider.GENERIC,
PyTypingTypeProvider.CLASS_VAR,
PyTypingTypeProvider.FINAL,
PyTypingTypeProvider.FINAL_EXT,
PyTypingTypeProvider.LITERAL,
PyTypingTypeProvider.LITERAL_EXT,
PyTypingTypeProvider.ANNOTATED,
PyTypingTypeProvider.ANNOTATED_EXT -> {
registerParametrizedGenericsProblem(qName, base)
return@forEach
}
PyTypingTypeProvider.UNION,
PyTypingTypeProvider.OPTIONAL -> {
if (!isBitwiseOrUnionAvailable(base)) {
registerParametrizedGenericsProblem(qName, base)
}
else if (base is PySubscriptionExpression) {
val indexExpr = base.indexExpression
if (indexExpr is PyTupleExpression) {
indexExpr.elements.forEach { tupleElement -> checkInstanceAndClassChecksOn(tupleElement) }
}
else if (indexExpr != null) {
checkInstanceAndClassChecksOn(indexExpr)
}
}
}
PyTypingTypeProvider.CALLABLE,
PyTypingTypeProvider.TYPE,
PyTypingTypeProvider.PROTOCOL,
PyTypingTypeProvider.PROTOCOL_EXT -> {
registerProblem(base,
PyPsiBundle.message("INSP.type.hints.parameterized.generics.cannot.be.used.with.instance.class.checks"),
ProblemHighlightType.GENERIC_ERROR,
null,
if (base is PySubscriptionExpression) RemoveGenericParametersQuickFix() else null)
return@forEach
}
}
}
if (it is PyTypedElement) {
val type = myTypeEvalContext.getType(it)
if (type is PyWithAncestors && PyTypingTypeProvider.isGeneric(type, myTypeEvalContext)) {
registerProblem(base,
PyPsiBundle.message("INSP.type.hints.parameterized.generics.cannot.be.used.with.instance.class.checks"),
ProblemHighlightType.GENERIC_ERROR,
null,
if (base is PySubscriptionExpression) RemoveGenericParametersQuickFix() else null)
}
}
}
}
}
private fun registerParametrizedGenericsProblem(qName: String, base: PsiElement) {
val shortName = qName.substringAfterLast('.')
registerProblem(base, PyPsiBundle.message("INSP.type.hints.type.cannot.be.used.with.instance.class.checks", shortName),
ProblemHighlightType.GENERIC_ERROR)
}
private fun checkParenthesesOnGenerics(call: PyCallExpression) {
val callee = call.callee
if (callee is PyReferenceExpression) {
if (PyResolveUtil.resolveImportedElementQNameLocally(callee).any { PyTypingTypeProvider.GENERIC_CLASSES.contains(it.toString()) }) {
registerProblem(call,
PyPsiBundle.message("INSP.type.hints.generics.should.be.specified.through.square.brackets"),
ProblemHighlightType.GENERIC_ERROR,
null,
ReplaceWithSubscriptionQuickFix())
}
else if (PyTypingTypeProvider.isInsideTypeHint(call, myTypeEvalContext)) {
multiFollowAssignmentsChain(callee)
.asSequence()
.map { if (it is PyFunction) it.containingClass else it }
.any { it is PyWithAncestors && PyTypingTypeProvider.isGeneric(it, myTypeEvalContext) }
.also {
if (it) registerProblem(call, PyPsiBundle.message("INSP.type.hints.generics.should.be.specified.through.square.brackets"),
ReplaceWithSubscriptionQuickFix())
}
}
}
}
private fun checkPlainGenericInheritance(superClassExpressions: List<PyExpression>) {
superClassExpressions
.asSequence()
.filterIsInstance<PyReferenceExpression>()
.filter { genericQName in PyResolveUtil.resolveImportedElementQNameLocally(it) }
.forEach {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.cannot.inherit.from.plain.generic"),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun checkGenericDuplication(superClassExpressions: List<PyExpression>) {
superClassExpressions
.asSequence()
.filter { superClass ->
val resolved = if (superClass is PyReferenceExpression) multiFollowAssignmentsChain(superClass) else listOf(superClass)
resolved
.asSequence()
.filterIsInstance<PySubscriptionExpression>()
.filter { myTypeEvalContext.maySwitchToAST(it) }
.mapNotNull { it.operand as? PyReferenceExpression }
.any { genericQName in PyResolveUtil.resolveImportedElementQNameLocally(it) }
}
.drop(1)
.forEach {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.cannot.inherit.from.generic.multiple.times"),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun checkGenericCompleteness(cls: PyClass) {
var seenGeneric = false
val genericTypeVars = linkedSetOf<PsiElement>()
val nonGenericTypeVars = linkedSetOf<PsiElement>()
cls.superClassExpressions.forEach { superClass ->
val generics = collectGenerics(superClass)
generics.first?.let {
genericTypeVars.addAll(it)
seenGeneric = true
}
nonGenericTypeVars.addAll(generics.second)
}
if (seenGeneric && (nonGenericTypeVars - genericTypeVars).isNotEmpty()) {
val nonGenericTypeVarsNames = nonGenericTypeVars
.asSequence()
.filterIsInstance<PyTargetExpression>()
.mapNotNull { it.name }
.joinToString(", ")
val genericTypeVarsNames = genericTypeVars
.asSequence()
.filterIsInstance<PyTargetExpression>()
.mapNotNull { it.name }
.joinToString(", ")
registerProblem(cls.superClassExpressionList,
PyPsiBundle.message("INSP.type.hints.some.type.variables.are.not.listed.in.generic",
nonGenericTypeVarsNames, genericTypeVarsNames),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun collectGenerics(superClassExpression: PyExpression): Pair<Set<PsiElement>?, Set<PsiElement>> {
val resolvedSuperClass =
if (superClassExpression is PyReferenceExpression) multiFollowAssignmentsChain(superClassExpression)
else listOf(superClassExpression)
var seenGeneric = false
val genericTypeVars = linkedSetOf<PsiElement>()
val nonGenericTypeVars = linkedSetOf<PsiElement>()
resolvedSuperClass
.asSequence()
.filterIsInstance<PySubscriptionExpression>()
.filter { myTypeEvalContext.maySwitchToAST(it) }
.forEach { superSubscription ->
val operand = superSubscription.operand
val generic =
operand is PyReferenceExpression &&
genericQName in PyResolveUtil.resolveImportedElementQNameLocally(operand)
val index = superSubscription.indexExpression
val parameters = (index as? PyTupleExpression)?.elements ?: arrayOf(index)
val superClassTypeVars = parameters
.asSequence()
.filterIsInstance<PyReferenceExpression>()
.flatMap { multiFollowAssignmentsChain(it, this::followNotTypeVar).asSequence() }
.filterIsInstance<PyTargetExpression>()
.filter { myTypeEvalContext.getType(it) is PyGenericType }
.toSet()
if (generic) genericTypeVars.addAll(superClassTypeVars) else nonGenericTypeVars.addAll(superClassTypeVars)
seenGeneric = seenGeneric || generic
}
return Pair(if (seenGeneric) genericTypeVars else null, nonGenericTypeVars)
}
private fun checkParameters(node: PySubscriptionExpression) {
val operand = node.operand as? PyReferenceExpression ?: return
val index = node.indexExpression ?: return
val callableQName = QualifiedName.fromDottedString(PyTypingTypeProvider.CALLABLE)
val literalQName = QualifiedName.fromDottedString(PyTypingTypeProvider.LITERAL)
val literalExtQName = QualifiedName.fromDottedString(PyTypingTypeProvider.LITERAL_EXT)
val annotatedQName = QualifiedName.fromDottedString(PyTypingTypeProvider.ANNOTATED)
val annotatedExtQName = QualifiedName.fromDottedString(PyTypingTypeProvider.ANNOTATED_EXT)
val typeAliasQName = QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_ALIAS)
val typeAliasExtQName = QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_ALIAS_EXT)
val qNames = PyResolveUtil.resolveImportedElementQNameLocally(operand)
var typingOnly = true
var callableExists = false
qNames.forEach {
when (it) {
genericQName -> checkGenericParameters(index)
literalQName, literalExtQName -> checkLiteralParameter(index)
annotatedQName, annotatedExtQName -> checkAnnotatedParameter(index)
typeAliasQName, typeAliasExtQName -> reportParameterizedTypeAlias(index)
callableQName -> {
callableExists = true
checkCallableParameters(index)
}
}
typingOnly = typingOnly && it.firstComponent == PyTypingTypeProvider.TYPING
}
if (qNames.isNotEmpty() && typingOnly) {
checkTypingMemberParameters(index, callableExists)
}
}
private fun reportParameterizedTypeAlias(index: PyExpression) {
// There is another warning in the type hint context
if (!PyTypingTypeProvider.isInsideTypeHint(index, myTypeEvalContext)) {
registerProblem(index, PyPsiBundle.message("INSP.type.hints.type.alias.cannot.be.parameterized"),
ProblemHighlightType.GENERIC_ERROR)
}
}
private fun checkLiteralParameter(index: PyExpression) {
val subParameter = if (index is PySubscriptionExpression) index.operand else null
if (subParameter is PyReferenceExpression &&
PyResolveUtil
.resolveImportedElementQNameLocally(subParameter)
.any { qName -> qName.toString().let { it == PyTypingTypeProvider.LITERAL || it == PyTypingTypeProvider.LITERAL_EXT } }) {
// if `index` is like `typing.Literal[...]` and has invalid form,
// outer `typing.Literal[...]` won't be highlighted
return
}
if (PyLiteralType.fromLiteralParameter(index, myTypeEvalContext) == null) {
registerProblem(index, PyPsiBundle.message("INSP.type.hints.illegal.literal.parameter"))
}
}
private fun checkAnnotatedParameter(index: PyExpression) {
if (index !is PyTupleExpression) {
registerProblem(index, PyPsiBundle.message("INSP.type.hints.annotated.must.be.called.with.at.least.two.arguments"))
}
}
private fun checkGenericParameters(index: PyExpression) {
val parameters = (index as? PyTupleExpression)?.elements ?: arrayOf(index)
val genericParameters = mutableSetOf<PsiElement>()
parameters.forEach {
if (it !is PyReferenceExpression) {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.must.all.be.type.variables"),
ProblemHighlightType.GENERIC_ERROR)
}
else {
val type = myTypeEvalContext.getType(it)
if (type != null) {
if (type is PyGenericType || isParamSpecOrConcatenate(it, myTypeEvalContext)) {
if (!genericParameters.addAll(multiFollowAssignmentsChain(it))) {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.must.all.be.unique"),
ProblemHighlightType.GENERIC_ERROR)
}
}
else {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.must.all.be.type.variables"),
ProblemHighlightType.GENERIC_ERROR)
}
}
}
}
}
private fun checkCallableParameters(index: PyExpression) {
if (index !is PyTupleExpression) {
registerProblem(index, PyPsiBundle.message("INSP.type.hints.illegal.callable.format"), ProblemHighlightType.GENERIC_ERROR)
return
}
val parameters = index.elements
if (parameters.size > 2) {
val possiblyLastParameter = parameters[parameters.size - 2]
registerProblem(index,
PyPsiBundle.message("INSP.type.hints.illegal.callable.format"),
ProblemHighlightType.GENERIC_ERROR,
null,
TextRange.create(0, possiblyLastParameter.startOffsetInParent + possiblyLastParameter.textLength),
SurroundElementsWithSquareBracketsQuickFix())
}
else if (parameters.size < 2) {
registerProblem(index, PyPsiBundle.message("INSP.type.hints.illegal.callable.format"), ProblemHighlightType.GENERIC_ERROR)
}
else {
val first = parameters.first()
if (!isSdkAvailable(first) || isParamSpecOrConcatenate(first, myTypeEvalContext)) return
if (first !is PyListLiteralExpression && !(first is PyNoneLiteralExpression && first.isEllipsis)) {
registerProblem(first,
PyPsiBundle.message("INSP.type.hints.illegal.first.parameter"),
ProblemHighlightType.GENERIC_ERROR,
null,
if (first is PyParenthesizedExpression) ReplaceWithListQuickFix() else SurroundElementWithSquareBracketsQuickFix())
}
}
}
private fun isSdkAvailable(element: PsiElement): Boolean =
PythonSdkUtil.findPythonSdk(ModuleUtilCore.findModuleForPsiElement(element)) != null
private fun isParamSpecOrConcatenate(expression: PyExpression, context: TypeEvalContext) : Boolean =
PyTypingTypeProvider.isConcatenate(expression, context) || PyTypingTypeProvider.isParamSpec(expression, context)
private fun checkTypingMemberParameters(index: PyExpression, isCallable: Boolean) {
val parameters = if (index is PyTupleExpression) index.elements else arrayOf(index)
parameters
.asSequence()
.drop(if (isCallable) 1 else 0)
.forEach {
if (it is PyListLiteralExpression) {
registerProblem(it,
PyPsiBundle.message("INSP.type.hints.parameters.to.generic.types.must.be.types"),
ProblemHighlightType.GENERIC_ERROR,
null,
RemoveSquareBracketsQuickFix())
}
else if (it is PyReferenceExpression && multiFollowAssignmentsChain(it).any { resolved -> resolved is PyListLiteralExpression }) {
registerProblem(it, PyPsiBundle.message("INSP.type.hints.parameters.to.generic.types.must.be.types"),
ProblemHighlightType.GENERIC_ERROR)
}
}
}
private fun checkTupleMatching(expression: PyExpression) {
if (expression !is PyTupleExpression) return
val assignment = PyPsiUtils.getRealContext(expression).parent as? PyAssignmentStatement ?: return
val lhs = assignment.leftHandSideExpression ?: return
if (PyTypingTypeProvider.mapTargetsToAnnotations(lhs, expression).isEmpty() &&
(expression.elements.isNotEmpty() || assignment.rawTargets.isNotEmpty())) {
registerProblem(expression, PyPsiBundle.message("INSP.type.hints.type.comment.cannot.be.matched.with.unpacked.variables"))
}
}
private fun checkTypeCommentAndParameters(node: PyFunction) {
val functionTypeAnnotation = PyTypingTypeProvider.getFunctionTypeAnnotation(node) ?: return
val parameterTypes = functionTypeAnnotation.parameterTypeList.parameterTypes
if (parameterTypes.singleOrNull().let { it is PyNoneLiteralExpression && it.isEllipsis }) return
val actualParametersSize = node.parameterList.parameters.size
val commentParametersSize = parameterTypes.size
val cls = node.containingClass
val modifier = node.modifier
val hasSelf = cls != null && modifier != PyFunction.Modifier.STATICMETHOD
if (commentParametersSize < actualParametersSize - if (hasSelf) 1 else 0) {
registerProblem(node.typeComment, PyPsiBundle.message("INSP.type.hints.type.signature.has.too.few.arguments"))
}
else if (commentParametersSize > actualParametersSize) {
registerProblem(node.typeComment, PyPsiBundle.message("INSP.type.hints.type.signature.has.too.many.arguments"))
}
else if (hasSelf && actualParametersSize == commentParametersSize) {
val actualSelfType =
(myTypeEvalContext.getType(cls!!) as? PyInstantiableType<*>)
?.let { if (modifier == PyFunction.Modifier.CLASSMETHOD) it.toClass() else it.toInstance() }
?: return
val commentSelfType =
parameterTypes.firstOrNull()
?.let { PyTypingTypeProvider.getType(it, myTypeEvalContext) }
?.get()
?: return
if (!PyTypeChecker.match(commentSelfType, actualSelfType, myTypeEvalContext)) {
val actualSelfTypeDescription = PythonDocumentationProvider.getTypeDescription(actualSelfType, myTypeEvalContext)
val commentSelfTypeDescription = PythonDocumentationProvider.getTypeDescription(commentSelfType, myTypeEvalContext)
registerProblem(node.typeComment, PyPsiBundle.message("INSP.type.hints.type.self.not.supertype.its.class",
commentSelfTypeDescription, actualSelfTypeDescription))
}
}
}
private fun checkAnnotatedNonSelfAttribute(node: PyTargetExpression) {
val qualifier = node.qualifier ?: return
if (node.annotation == null && node.typeComment == null) return
val scopeOwner = ScopeUtil.getScopeOwner(node)
if (scopeOwner !is PyFunction) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.non.self.attribute.could.not.be.type.hinted"))
return
}
val self = scopeOwner.parameterList.parameters.firstOrNull()?.takeIf { it.isSelf }
if (self == null ||
PyUtil.multiResolveTopPriority(qualifier, resolveContext).let { it.isNotEmpty() && it.all { e -> e != self } }) {
registerProblem(node, PyPsiBundle.message("INSP.type.hints.non.self.attribute.could.not.be.type.hinted"))
}
}
private fun followNotTypingOpaque(target: PyTargetExpression): Boolean {
return !PyTypingTypeProvider.OPAQUE_NAMES.contains(target.qualifiedName)
}
private fun followNotTypeVar(target: PyTargetExpression): Boolean {
return !myTypeEvalContext.maySwitchToAST(target) || target.findAssignedValue() !is PyCallExpression
}
private fun multiFollowAssignmentsChain(referenceExpression: PyReferenceExpression,
follow: (PyTargetExpression) -> Boolean = this::followNotTypingOpaque): List<PsiElement> {
return referenceExpression.multiFollowAssignmentsChain(resolveContext, follow).mapNotNull { it.element }
}
private fun resolvesToAnyOfQualifiedNames(referenceExpr: PyReferenceExpression, vararg names: String): Boolean {
return multiFollowAssignmentsChain(referenceExpr)
.filterIsInstance<PyQualifiedNameOwner>()
.mapNotNull { it.qualifiedName }
.any { names.contains(it) }
}
}
companion object {
private class ReplaceWithTypeNameQuickFix(private val typeName: String) : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.type.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyReferenceExpression ?: return
element.reference.handleElementRename(typeName)
}
}
private class RemoveElementQuickFix(@IntentionFamilyName private val description: String) : LocalQuickFix {
override fun getFamilyName() = description
override fun applyFix(project: Project, descriptor: ProblemDescriptor) = descriptor.psiElement.delete()
}
private class RemoveFunctionAnnotations : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.remove.function.annotations")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val function = (descriptor.psiElement.parent as? PyFunction) ?: return
function.annotation?.delete()
function.parameterList.parameters
.asSequence()
.filterIsInstance<PyNamedParameter>()
.mapNotNull { it.annotation }
.forEach { it.delete() }
}
}
private class ReplaceWithTargetNameQuickFix(private val targetName: String) : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.target.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val old = descriptor.psiElement as? PyStringLiteralExpression ?: return
val new = PyElementGenerator.getInstance(project).createStringLiteral(old, targetName) ?: return
old.replace(new)
}
}
private class RemoveGenericParametersQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.remove.generic.parameters")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val old = descriptor.psiElement as? PySubscriptionExpression ?: return
old.replace(old.operand)
}
}
private class ReplaceWithSubscriptionQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.square.brackets")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyCallExpression ?: return
val callee = element.callee?.text ?: return
val argumentList = element.argumentList ?: return
val index = argumentList.text.let { it.substring(1, it.length - 1) }
val language = element.containingFile.language
val text = if (language == PyFunctionTypeAnnotationDialect.INSTANCE) "() -> $callee[$index]" else "$callee[$index]"
PsiFileFactory
.getInstance(project)
// it's important to create file with same language as element's file to have correct behaviour in injections
.createFileFromText(language, text)
?.let { it.firstChild.lastChild as? PySubscriptionExpression }
?.let { element.replace(it) }
}
}
private class SurroundElementsWithSquareBracketsQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.surround.with.square.brackets")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyTupleExpression ?: return
val list = PyElementGenerator.getInstance(project).createListLiteral()
val originalElements = element.elements
originalElements.dropLast(1).forEach { list.add(it) }
originalElements.dropLast(2).forEach { it.delete() }
element.elements.first().replace(list)
}
}
private class SurroundElementWithSquareBracketsQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.surround.with.square.brackets")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val list = PyElementGenerator.getInstance(project).createListLiteral()
list.add(element)
element.replace(list)
}
}
private class ReplaceWithListQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.replace.with.square.brackets")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val expression = (element as? PyParenthesizedExpression)?.containedExpression ?: return
val elements = expression.let { if (it is PyTupleExpression) it.elements else arrayOf(it) }
val list = PyElementGenerator.getInstance(project).createListLiteral()
elements.forEach { list.add(it) }
element.replace(list)
}
}
private class RemoveSquareBracketsQuickFix : LocalQuickFix {
override fun getFamilyName() = PyPsiBundle.message("QFIX.remove.square.brackets")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? PyListLiteralExpression ?: return
val subscription = PsiTreeUtil.getParentOfType(element, PySubscriptionExpression::class.java, true, ScopeOwner::class.java)
val index = subscription?.indexExpression ?: return
val newIndexElements = if (index is PyTupleExpression) {
index.elements.flatMap { if (it == element) element.elements.asList() else listOf(it) }
}
else {
element.elements.asList()
}
if (newIndexElements.size == 1) {
index.replace(newIndexElements.first())
}
else {
val newIndexText = newIndexElements.joinToString(prefix = "(", postfix = ")") { it.text }
val expression = PyElementGenerator.getInstance(project).createExpressionFromText(LanguageLevel.forElement(element), newIndexText)
val newIndex = (expression as? PyParenthesizedExpression)?.containedExpression as? PyTupleExpression ?: return
index.replace(newIndex)
}
}
}
private class ReplaceWithTypingGenericAliasQuickFix : LocalQuickFix {
override fun getFamilyName(): String = PyPsiBundle.message("QFIX.replace.with.typing.alias")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val subscription = descriptor.psiElement as? PySubscriptionExpression ?: return
val refExpr = subscription.operand as? PyReferenceExpression ?: return
val alias = PyTypingTypeProvider.TYPING_BUILTINS_GENERIC_ALIASES[refExpr.name] ?: return
val languageLevel = LanguageLevel.forElement(subscription)
val priority = if (languageLevel.isAtLeast(LanguageLevel.PYTHON35)) ImportPriority.THIRD_PARTY else ImportPriority.BUILTIN
AddImportHelper.addOrUpdateFromImportStatement(subscription.containingFile, "typing", alias, null, priority, subscription)
val newRefExpr = PyElementGenerator.getInstance(project).createExpressionFromText(languageLevel, alias)
refExpr.replace(newRefExpr)
}
}
}
}
| apache-2.0 | 21d013342d6466ffec3aa492779ac389 | 43.606996 | 142 | 0.675193 | 5.250424 | false | false | false | false |
smmribeiro/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/outputs/impl/NotebookOutputCollapseAllInSelectedCellsAction.kt | 1 | 7146 | package org.jetbrains.plugins.notebooks.visualization.outputs.impl
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.DumbAware
import com.intellij.util.castSafelyTo
import org.jetbrains.plugins.notebooks.visualization.*
import org.jetbrains.plugins.notebooks.visualization.outputs.NotebookOutputInlayController
import java.awt.event.MouseEvent
internal class NotebookOutputCollapseAllAction private constructor() : ToggleAction(), DumbAware {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabledAndVisible = e.notebookEditor != null
}
override fun isSelected(e: AnActionEvent): Boolean =
!allCollapsingComponents(e).any { it.isSeen }
override fun setSelected(e: AnActionEvent, state: Boolean) {
markScrollingPositionBeforeOutputCollapseToggle(e)
for (component in allCollapsingComponents(e)) {
component.isSeen = !state
}
}
private fun allCollapsingComponents(e: AnActionEvent): Sequence<CollapsingComponent> {
val inlayManager = e.notebookCellInlayManager ?: return emptySequence()
return getCollapsingComponents(inlayManager.editor, NotebookCellLines.get(inlayManager.editor).intervals)
}
}
// same as Collapse All Action, but collapse outputs of selected cells
internal class NotebookOutputCollapseAllInSelectedCellsAction private constructor() : ToggleAction(), DumbAware {
override fun update(e: AnActionEvent) {
super.update(e)
val editor = e.notebookEditor
e.presentation.isEnabled = editor != null
e.presentation.isVisible = editor?.cellSelectionModel?.let { it.selectedCells.size > 1 } ?: false
}
override fun isSelected(e: AnActionEvent): Boolean =
!getSelectedCollapsingComponents(e).any { it.isSeen }
override fun setSelected(e: AnActionEvent, state: Boolean) {
markScrollingPositionBeforeOutputCollapseToggle(e)
for(component in getSelectedCollapsingComponents(e)) {
component.isSeen = !state
}
}
private fun getSelectedCollapsingComponents(e: AnActionEvent): Sequence<CollapsingComponent> {
val inlayManager = e.notebookCellInlayManager ?: return emptySequence()
val selectedCells = inlayManager.editor.cellSelectionModel?.selectedCells ?: return emptySequence()
return getCollapsingComponents(inlayManager.editor, selectedCells)
}
}
internal class NotebookOutputCollapseAllInCellAction private constructor() : ToggleAction(), DumbAware {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabledAndVisible = getCollapsingComponents(e) != null
}
override fun isSelected(e: AnActionEvent): Boolean {
val collapsingComponents = getCollapsingComponents(e) ?: return false
return collapsingComponents.isNotEmpty() && collapsingComponents.all { !it.isSeen }
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
markScrollingPositionBeforeOutputCollapseToggle(e)
getCollapsingComponents(e)?.forEach {
it.isSeen = !state
}
}
}
internal class NotebookOutputCollapseSingleInCellAction private constructor() : ToggleAction(), DumbAware {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabledAndVisible = getCollapsingComponents(e) != null
}
override fun isSelected(e: AnActionEvent): Boolean =
getExpectedComponent(e)?.isSeen?.let { !it } ?: false
override fun setSelected(e: AnActionEvent, state: Boolean) {
markScrollingPositionBeforeOutputCollapseToggle(e)
getExpectedComponent(e)?.isSeen = !state
}
private fun getExpectedComponent(e: AnActionEvent): CollapsingComponent? =
e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT)
?.castSafelyTo<CollapsingComponent>()
?.let { expectedComponent ->
getCollapsingComponents(e)?.singleOrNull { it === expectedComponent }
}
}
private fun getCollapsingComponents(e: AnActionEvent): List<CollapsingComponent>? {
val interval = e.dataContext.notebookCellLinesInterval ?: return null
return e.getData(PlatformDataKeys.EDITOR)?.let { getCollapsingComponents(it, interval) }
}
private fun getCollapsingComponents(editor: Editor, interval: NotebookCellLines.Interval): List<CollapsingComponent>? =
NotebookCellInlayManager.get(editor)
?.inlaysForInterval(interval)
?.filterIsInstance<NotebookOutputInlayController>()
?.firstOrNull()
?.collapsingComponents
private fun getCollapsingComponents(editor: Editor, intervals: Iterable<NotebookCellLines.Interval>): Sequence<CollapsingComponent> =
intervals.asSequence()
.filter { it.type == NotebookCellLines.CellType.CODE }
.mapNotNull { getCollapsingComponents(editor, it) }
.flatMap { it }
private val AnActionEvent.notebookCellInlayManager: NotebookCellInlayManager?
get() = getData(PlatformDataKeys.EDITOR)?.let(NotebookCellInlayManager.Companion::get)
private val AnActionEvent.notebookEditor: EditorImpl?
get() = notebookCellInlayManager?.editor
private fun markScrollingPositionBeforeOutputCollapseToggle(e: AnActionEvent) {
val cell = e.dataContext.notebookCellLinesInterval ?: return
val editor = e.notebookCellInlayManager?.editor ?: return
val notebookCellEditorScrollingPositionKeeper = editor.notebookCellEditorScrollingPositionKeeper ?: return
val outputsCellVisible = isLineVisible(editor, cell.lines.last)
if (!outputsCellVisible) {
val cellOutputInlays = editor.inlayModel.getBlockElementsInRange(editor.document.getLineEndOffset(cell.lines.last), editor.document.getLineEndOffset(cell.lines.last))
val visibleArea = editor.scrollingModel.visibleAreaOnScrollingFinished
for (i in (cellOutputInlays.size - 1) downTo 1) {
val inlay = cellOutputInlays[i]
val bounds = inlay.bounds ?: continue
val outputTopIsAboveScreen = bounds.y < visibleArea.y
val outputBottomIsOnOrBelowScreen = bounds.y + bounds.height > visibleArea.y
if (outputTopIsAboveScreen) {
if ((outputBottomIsOnOrBelowScreen)) {
val inputEvent = e.inputEvent
val additionalShift: Int
if (inputEvent is MouseEvent) {
// Adjust scrolling so, that the collapsed output is under the mouse pointer
additionalShift = inputEvent.y - bounds.y - editor.lineHeight
} else {
// Adjust scrolling so, that the collapsed output is visible on the screen
additionalShift = visibleArea.y - bounds.y + editor.lineHeight
}
notebookCellEditorScrollingPositionKeeper.savePosition(cell.lines.last, additionalShift)
return
}
else {
val topVisibleLine: Int = editor.xyToLogicalPosition(visibleArea.location).line
notebookCellEditorScrollingPositionKeeper.savePosition(topVisibleLine)
return
}
}
}
}
notebookCellEditorScrollingPositionKeeper.savePosition(cell.lines.first)
} | apache-2.0 | fd9269cd1b7692b66656e02cdb16b384 | 41.041176 | 170 | 0.762524 | 4.754491 | false | false | false | false |
ianhanniballake/muzei | main/src/main/java/com/google/android/apps/muzei/browse/BrowseProviderFragment.kt | 1 | 8417 | /*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.browse
import android.app.PendingIntent
import android.os.Bundle
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.graphics.drawable.DrawerArrowDrawable
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import coil.load
import com.google.android.apps.muzei.room.Artwork
import com.google.android.apps.muzei.room.MuzeiDatabase
import com.google.android.apps.muzei.room.getCommands
import com.google.android.apps.muzei.sync.ProviderManager
import com.google.android.apps.muzei.util.launchWhenStartedIn
import com.google.android.apps.muzei.util.toast
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import net.nurik.roman.muzei.R
import net.nurik.roman.muzei.databinding.BrowseProviderFragmentBinding
import net.nurik.roman.muzei.databinding.BrowseProviderItemBinding
class BrowseProviderFragment: Fragment(R.layout.browse_provider_fragment) {
companion object {
const val REFRESH_DELAY = 300L // milliseconds
}
private val viewModel: BrowseProviderViewModel by viewModels()
private val args: BrowseProviderFragmentArgs by navArgs()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val binding = BrowseProviderFragmentBinding.bind(view)
val pm = requireContext().packageManager
val providerInfo = pm.resolveContentProvider(args.contentUri.authority!!, 0)
?: run {
findNavController().popBackStack()
return
}
binding.swipeRefresh.setOnRefreshListener {
refresh(binding.swipeRefresh)
}
binding.toolbar.apply {
navigationIcon = DrawerArrowDrawable(requireContext()).apply {
progress = 1f
}
setNavigationOnClickListener {
findNavController().popBackStack()
}
title = providerInfo.loadLabel(pm)
inflateMenu(R.menu.browse_provider_fragment)
setOnMenuItemClickListener {
refresh(binding.swipeRefresh)
true
}
}
val adapter = Adapter()
binding.list.adapter = adapter
viewModel.contentUri = args.contentUri
viewModel.artwork.onEach {
adapter.submitList(it)
}.launchWhenStartedIn(viewLifecycleOwner)
}
private fun refresh(swipeRefreshLayout: SwipeRefreshLayout) {
lifecycleScope.launch {
ProviderManager.requestLoad(requireContext(), args.contentUri)
// Show the refresh indicator for some visible amount of time
// rather than immediately dismissing it. We don't know how long
// the provider will actually take to refresh, if it does at all.
delay(REFRESH_DELAY)
withContext(Dispatchers.Main.immediate) {
swipeRefreshLayout.isRefreshing = false
}
}
}
class ArtViewHolder(
private val owner: LifecycleOwner,
private val binding: BrowseProviderItemBinding
): RecyclerView.ViewHolder(binding.root) {
fun bind(artwork: Artwork) {
val context = itemView.context
binding.image.contentDescription = artwork.title
binding.image.load(artwork.imageUri) {
lifecycle(owner)
}
itemView.setOnClickListener {
owner.lifecycleScope.launch(Dispatchers.Main) {
Firebase.analytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) {
param(FirebaseAnalytics.Param.ITEM_LIST_ID, artwork.providerAuthority)
param(FirebaseAnalytics.Param.ITEM_NAME, artwork.title ?: "")
param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "actions")
param(FirebaseAnalytics.Param.CONTENT_TYPE, "browse")
}
// Ensure the date added is set to the current time
artwork.dateAdded.time = System.currentTimeMillis()
MuzeiDatabase.getInstance(context).artworkDao()
.insert(artwork)
context.toast(if (artwork.title.isNullOrBlank()) {
context.getString(R.string.browse_set_wallpaper)
} else {
context.getString(R.string.browse_set_wallpaper_with_title,
artwork.title)
})
}
}
itemView.setOnCreateContextMenuListener(null)
owner.lifecycleScope.launch(Dispatchers.Main.immediate) {
val actions = artwork.getCommands(context).filterNot {
it.title.isBlank()
}
if (actions.isNotEmpty()) {
itemView.setOnCreateContextMenuListener { menu, _, _ ->
actions.forEachIndexed { index, action ->
menu.add(Menu.NONE, index, index, action.title).apply {
setOnMenuItemClickListener { menuItem ->
Firebase.analytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) {
param(FirebaseAnalytics.Param.ITEM_LIST_ID, artwork.providerAuthority)
param(FirebaseAnalytics.Param.ITEM_NAME, menuItem.title.toString())
param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "actions")
param(FirebaseAnalytics.Param.CONTENT_TYPE, "browse")
}
try {
action.actionIntent.send()
} catch (e: PendingIntent.CanceledException) {
// Why do you give us a cancelled PendingIntent.
// We can't do anything with that.
}
true
}
}
}
}
}
}
}
}
inner class Adapter: ListAdapter<Artwork, ArtViewHolder>(
object: DiffUtil.ItemCallback<Artwork>() {
override fun areItemsTheSame(artwork1: Artwork, artwork2: Artwork) =
artwork1.imageUri == artwork2.imageUri
override fun areContentsTheSame(artwork1: Artwork, artwork2: Artwork) =
artwork1 == artwork2
}
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ArtViewHolder(viewLifecycleOwner,
BrowseProviderItemBinding.inflate(layoutInflater, parent, false))
override fun onBindViewHolder(holder: ArtViewHolder, position: Int) {
holder.bind(getItem(position))
}
}
}
| apache-2.0 | d4133d48d4fc9fe9c9e97dc294e16f20 | 42.838542 | 110 | 0.613639 | 5.519344 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/libs/RelativeDateTimeOptions.kt | 1 | 2550 | package com.kickstarter.libs
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import org.joda.time.DateTime
@Parcelize
class RelativeDateTimeOptions private constructor(
private val abbreviated: Boolean,
private val absolute: Boolean,
private val relativeToDateTime: DateTime?,
private val threshold: Int
) : Parcelable {
/**
* Abbreviates string, e.g.: "in 1 hr"
*/
fun abbreviated() = this.abbreviated
/**
* Don't output tense, e.g.: "1 hour" instead of "in 1 hour"
*/
fun absolute() = this.absolute
/**
* Compare against this date instead of the current time
*/
fun relativeToDateTime() = this.relativeToDateTime
/**
* Number of seconds difference permitted before an attempt to describe the relative date is abandoned.
* For example, "738 days ago" is not helpful to users. The threshold defaults to 30 days.
*/
fun threshold() = this.threshold
@Parcelize
data class Builder(
private var abbreviated: Boolean = false,
private var absolute: Boolean = false,
private var relativeToDateTime: DateTime? = null,
private var threshold: Int = THIRTY_DAYS_IN_SECONDS
) : Parcelable {
fun abbreviated(abbreviated: Boolean) = apply { this.abbreviated = abbreviated }
fun absolute(absolute: Boolean) = apply { this.absolute = absolute }
fun relativeToDateTime(relativeToDateTime: DateTime?) = apply { this.relativeToDateTime = relativeToDateTime }
fun threshold(threshold: Int) = apply { this.threshold = threshold }
fun build() = RelativeDateTimeOptions(
abbreviated = abbreviated,
absolute = absolute,
relativeToDateTime = relativeToDateTime,
threshold = threshold
)
}
fun toBuilder() = Builder(
abbreviated = abbreviated,
absolute = absolute,
relativeToDateTime = relativeToDateTime,
threshold = threshold
)
override fun equals(obj: Any?): Boolean {
var equals = super.equals(obj)
if (obj is RelativeDateTimeOptions) {
equals = abbreviated() == obj.abbreviated() &&
absolute() == obj.absolute() &&
relativeToDateTime() == obj.relativeToDateTime() &&
threshold() == obj.threshold()
}
return equals
}
companion object {
@JvmStatic
fun builder() = Builder()
private const val THIRTY_DAYS_IN_SECONDS = 60 * 60 * 24 * 30
}
}
| apache-2.0 | 1bc01dac4261b308c4a69c575c73bc2a | 31.692308 | 118 | 0.634902 | 4.739777 | false | false | false | false |
vanniktech/lint-rules | lint-rules-android-lint/src/main/java/com/vanniktech/lintrules/android/WrongDrawableNameDetector.kt | 1 | 1781 | @file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final.
package com.vanniktech.lintrules.android
import com.android.resources.ResourceFolderType
import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.ResourceXmlDetector
import com.android.tools.lint.detector.api.Scope.Companion.RESOURCE_FILE_SCOPE
import com.android.tools.lint.detector.api.Severity.WARNING
import com.android.tools.lint.detector.api.XmlContext
import org.w3c.dom.Document
private val allowedPrefixes = listOf(
"animated_selector",
"animated_vector_",
"background_",
"ic_",
"img_",
"notification_icon_",
"ripple_",
"selector_",
"shape_",
"vector_",
)
val ISSUE_WRONG_DRAWABLE_NAME = Issue.create(
"WrongDrawableName",
"Drawable names should be prefixed accordingly.",
"The drawable file name should be prefixed with one of the following: ${allowedPrefixes.joinToString()}. This will improve consistency in your code base as well as enforce a certain structure.",
CORRECTNESS, PRIORITY, WARNING,
Implementation(WrongDrawableNameDetector::class.java, RESOURCE_FILE_SCOPE),
)
class WrongDrawableNameDetector : ResourceXmlDetector() {
override fun appliesTo(folderType: ResourceFolderType) = folderType == ResourceFolderType.DRAWABLE
override fun visitDocument(context: XmlContext, document: Document) {
val modified = fileNameSuggestions(allowedPrefixes, context)
if (modified != null) {
context.report(ISSUE_WRONG_DRAWABLE_NAME, document, context.getLocation(document), "Drawable does not start with one of the following prefixes: ${modified.joinToString()}")
}
}
}
| apache-2.0 | 6f954c91847161b69afeaea1e712f795 | 37.717391 | 196 | 0.775969 | 4.094253 | false | false | false | false |
fabmax/kool | kool-physics/src/commonMain/kotlin/de/fabmax/kool/physics/joints/RevoluteJoint.kt | 1 | 1459 | package de.fabmax.kool.physics.joints
import de.fabmax.kool.math.FLT_EPSILON
import de.fabmax.kool.math.Mat4f
import de.fabmax.kool.math.MutableVec3f
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.physics.RigidActor
expect class RevoluteJoint(bodyA: RigidActor, bodyB: RigidActor, frameA: Mat4f, frameB: Mat4f) : Joint {
val bodyA: RigidActor
val bodyB: RigidActor
val frameA: Mat4f
val frameB: Mat4f
constructor(bodyA: RigidActor, bodyB: RigidActor, pivotA: Vec3f, pivotB: Vec3f, axisA: Vec3f, axisB: Vec3f)
fun disableAngularMotor()
fun enableAngularMotor(angularVelocity: Float, forceLimit: Float)
}
object RevoluteJointHelper {
fun computeFrame(pivot: Vec3f, axis: Vec3f): Mat4f {
val ax1 = MutableVec3f()
val ax2 = MutableVec3f()
val dot = axis * Vec3f.X_AXIS
when {
dot >= 1.0f - FLT_EPSILON -> {
ax1.set(Vec3f.Z_AXIS)
ax2.set(Vec3f.Y_AXIS)
}
dot <= -1.0f + FLT_EPSILON -> {
ax1.set(Vec3f.NEG_Z_AXIS)
ax2.set(Vec3f.NEG_Y_AXIS)
}
else -> {
axis.cross(Vec3f.X_AXIS, ax2)
axis.cross(ax2, ax1)
}
}
val frame = Mat4f()
frame.translate(pivot)
frame.setCol(0, axis, 0f)
frame.setCol(1, ax2.norm(), 0f)
frame.setCol(2, ax1.norm(), 0f)
return frame
}
}
| apache-2.0 | 09bd18ac89f3fc4f2df223a3f328a5e3 | 27.607843 | 111 | 0.591501 | 3.199561 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/skins/SkinInterface.kt | 1 | 4130 | package info.nightscout.androidaps.skins
import android.util.DisplayMetrics
import android.util.TypedValue.COMPLEX_UNIT_PX
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import androidx.constraintlayout.widget.ConstraintLayout
import info.nightscout.androidaps.R
import kotlinx.android.synthetic.main.overview_fragment_nsclient.view.*
import kotlinx.android.synthetic.main.overview_info_layout.view.*
import kotlinx.android.synthetic.main.overview_statuslights_layout.view.*
interface SkinInterface {
@get:StringRes val description: Int
val mainGraphHeight: Int // in dp
val secondaryGraphHeight: Int // in dp
@LayoutRes
fun overviewLayout(isLandscape: Boolean, isTablet: Boolean, isSmallHeight: Boolean): Int
@LayoutRes
fun actionsLayout(isLandscape: Boolean, isSmallWidth: Boolean): Int = R.layout.actions_fragment
fun preProcessLandscapeOverviewLayout(dm: DisplayMetrics, view: View, isTablet: Boolean) {
// pre-process landscape mode
val screenWidth = dm.widthPixels
val screenHeight = dm.heightPixels
val landscape = screenHeight < screenWidth
if (landscape) {
val iobLayoutParams = view.overview_iob_llayout.layoutParams as ConstraintLayout.LayoutParams
iobLayoutParams.startToStart = ConstraintLayout.LayoutParams.UNSET
iobLayoutParams.startToEnd = view.overview_time_llayout.id
iobLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET
iobLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
val timeLayoutParams = view.overview_time_llayout.layoutParams as ConstraintLayout.LayoutParams
timeLayoutParams.endToEnd = ConstraintLayout.LayoutParams.UNSET
timeLayoutParams.endToStart = view.overview_iob_llayout.id
val cobLayoutParams = view.overview_cob_llayout.layoutParams as ConstraintLayout.LayoutParams
cobLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
val basalLayoutParams = view.overview_basal_llayout.layoutParams as ConstraintLayout.LayoutParams
basalLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
val extendedLayoutParams = view.overview_extended_llayout.layoutParams as ConstraintLayout.LayoutParams
extendedLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
val asLayoutParams = view.overview_as_llayout.layoutParams as ConstraintLayout.LayoutParams
asLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
if (isTablet) {
for (v in listOf<TextView?>(
view.overview_bg,
view.overview_time,
view.overview_timeagoshort,
view.overview_iob,
view.overview_cob,
view.overview_basebasal,
view.overview_extendedbolus,
view.overview_sensitivity
)) v?.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.5f)
for (v in listOf<TextView?>(
view.overview_pump,
view.overview_openaps,
view.overview_uploader,
view.careportal_canulaage,
view.careportal_insulinage,
view.careportal_reservoirlevel,
view.careportal_reservoirlevel,
view.careportal_sensorage,
view.careportal_pbage,
view.careportal_batterylevel
)) v?.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.3f)
view.overview_time_llayout?.orientation = LinearLayout.HORIZONTAL
view.overview_timeagoshort?.setTextSize(COMPLEX_UNIT_PX, view.overview_time.textSize)
view.overview_delta_large?.visibility = View.VISIBLE
} else {
view.overview_delta_large?.visibility = View.GONE
}
}
}
} | agpl-3.0 | 7e2badf3099d5ca3d272dcb733fdf47e | 47.6 | 115 | 0.675545 | 5.061275 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/DiscoveryViewModel.kt | 1 | 22344 | package com.kickstarter.viewmodels
import android.content.Intent
import android.net.Uri
import android.util.Pair
import com.kickstarter.R
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.DiscoveryUtils
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.extensions.deriveNavigationDrawerData
import com.kickstarter.libs.utils.extensions.getTokenFromQueryParams
import com.kickstarter.libs.utils.extensions.intValueOrZero
import com.kickstarter.libs.utils.extensions.isNonZero
import com.kickstarter.libs.utils.extensions.isTrue
import com.kickstarter.libs.utils.extensions.isVerificationEmailUrl
import com.kickstarter.libs.utils.extensions.positionFromSort
import com.kickstarter.models.Category
import com.kickstarter.models.User
import com.kickstarter.services.DiscoveryParams
import com.kickstarter.services.apiresponses.ErrorEnvelope
import com.kickstarter.services.apiresponses.InternalBuildEnvelope
import com.kickstarter.ui.SharedPreferenceKey.HAS_SEEN_NOTIF_PERMISSIONS
import com.kickstarter.ui.activities.DiscoveryActivity
import com.kickstarter.ui.adapters.DiscoveryDrawerAdapter
import com.kickstarter.ui.adapters.DiscoveryPagerAdapter
import com.kickstarter.ui.adapters.data.NavigationDrawerData
import com.kickstarter.ui.intentmappers.DiscoveryIntentMapper
import com.kickstarter.ui.viewholders.discoverydrawer.ChildFilterViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.LoggedInViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.LoggedOutViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.ParentFilterViewHolder
import com.kickstarter.ui.viewholders.discoverydrawer.TopFilterViewHolder
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface DiscoveryViewModel {
interface Inputs : DiscoveryDrawerAdapter.Delegate, DiscoveryPagerAdapter.Delegate {
/** Call when a new build is available. */
fun newerBuildIsAvailable(envelope: InternalBuildEnvelope)
/** Call when you want to open or close the drawer. */
fun openDrawer(open: Boolean)
/** Call when the user selects a sort tab. */
fun sortClicked(sortPosition: Int)
/** Call when the user has seen the notifications permission request. */
fun hasSeenNotificationsPermission(hasShown: Boolean)
}
interface Outputs {
/** Emits a boolean that determines if the drawer is open or not. */
fun drawerIsOpen(): Observable<Boolean>
/** Emits the drawable resource ID of the drawer menu icon. */
fun drawerMenuIcon(): Observable<Int>
/** Emits a boolean that determines if the sort tab layout should be expanded/collapsed. */
fun expandSortTabLayout(): Observable<Boolean>
/** Emits when params change so that the tool bar can adjust accordingly. */
fun updateToolbarWithParams(): Observable<DiscoveryParams>
/** Emits when the params of a particular page should be updated. The page will be responsible for
* taking those params and creating paginating projects from it. */
fun updateParamsForPage(): Observable<DiscoveryParams>
fun navigationDrawerData(): Observable<NavigationDrawerData>
/** Emits the root categories and position. Position is used to determine the appropriate fragment
* to pass the categories to. */
fun rootCategoriesAndPosition(): Observable<Pair<List<Category>, Int>>
/** Emits a list of pages that should be cleared of all their content. */
fun clearPages(): Observable<List<Int>>
/** Emits when a newer build is available and an alert should be shown. */
fun showBuildCheckAlert(): Observable<InternalBuildEnvelope>
/** Start activity feed activity. */
fun showActivityFeed(): Observable<Void?>
/** Start creator dashboard activity. */
fun showCreatorDashboard(): Observable<Void?>
/** Start help activity. */
fun showHelp(): Observable<Void?>
/** Start internal tools activity. */
fun showInternalTools(): Observable<Void?>
/** Start login tout activity for result. */
fun showLoginTout(): Observable<Void?>
/** Start [com.kickstarter.ui.activities.MessageThreadsActivity]. */
fun showMessages(): Observable<Void?>
/** Start profile activity. */
fun showProfile(): Observable<Void?>
/** Start settings activity. */
fun showSettings(): Observable<Void?>
/** Emits the success message from verify endpoint */
fun showSuccessMessage(): Observable<String>
/** Emits if the user should be shown the notification permission request */
fun showNotifPermissionsRequest(): Observable<Void?>
/** Emits the error message from verify endpoint */
fun showErrorMessage(): Observable<String?>
}
class ViewModel(environment: Environment) : ActivityViewModel<DiscoveryActivity?>(environment), Inputs, Outputs {
val inputs = this
val outputs = this
private val apiClient = requireNotNull(environment.apiClient())
private val apolloClient = requireNotNull(environment.apolloClient())
private val buildCheck = requireNotNull(environment.buildCheck())
private val currentUserType = requireNotNull(environment.currentUser())
private val currentConfigType = requireNotNull(environment.currentConfig())
private val sharedPreferences = requireNotNull(environment.sharedPreferences())
private val webClient = requireNotNull(environment.webClient())
private fun currentDrawerMenuIcon(user: User?): Int {
if (ObjectUtils.isNull(user)) {
return R.drawable.ic_menu
}
val erroredBackingsCount = user?.erroredBackingsCount().intValueOrZero()
val unreadMessagesCount = user?.unreadMessagesCount().intValueOrZero()
val unseenActivityCount = user?.unseenActivityCount().intValueOrZero()
return when {
erroredBackingsCount.isNonZero() -> R.drawable.ic_menu_error_indicator
(unreadMessagesCount + unseenActivityCount + erroredBackingsCount).isNonZero() -> R.drawable.ic_menu_indicator
else -> R.drawable.ic_menu
}
}
private val activityFeedClick = PublishSubject.create<Void?>()
private val childFilterRowClick = PublishSubject.create<NavigationDrawerData.Section.Row?>()
private val creatorDashboardClick = PublishSubject.create<Void?>()
private val internalToolsClick = PublishSubject.create<Void?>()
private val loggedOutLoginToutClick = PublishSubject.create<Void?>()
private val loggedOutSettingsClick = PublishSubject.create<Void?>()
private val messagesClick = PublishSubject.create<Void?>()
private val newerBuildIsAvailable = PublishSubject.create<InternalBuildEnvelope>()
private val openDrawer = PublishSubject.create<Boolean>()
private val pagerSetPrimaryPage = PublishSubject.create<Int>()
private val parentFilterRowClick = PublishSubject.create<NavigationDrawerData.Section.Row>()
private val profileClick = PublishSubject.create<Void?>()
private val showNotifPermissionRequest = BehaviorSubject.create<Void?>()
private val settingsClick = PublishSubject.create<Void?>()
private val sortClicked = PublishSubject.create<Int>()
private val hasSeenNotificationsPermission = PublishSubject.create<Boolean>()
private val topFilterRowClick = PublishSubject.create<NavigationDrawerData.Section.Row?>()
private val clearPages = BehaviorSubject.create<List<Int>>()
private val drawerIsOpen = BehaviorSubject.create<Boolean>()
private val drawerMenuIcon = BehaviorSubject.create<Int>()
private val expandSortTabLayout = BehaviorSubject.create<Boolean>()
private val navigationDrawerData = BehaviorSubject.create<NavigationDrawerData>()
private val rootCategoriesAndPosition = BehaviorSubject.create<Pair<List<Category>, Int>>()
private val showActivityFeed: Observable<Void?>
private val showBuildCheckAlert: Observable<InternalBuildEnvelope>
private val showCreatorDashboard: Observable<Void?>
private val showHelp: Observable<Void?>
private val showInternalTools: Observable<Void?>
private val showLoginTout: Observable<Void?>
private val showMessages: Observable<Void?>
private val showProfile: Observable<Void?>
private val showSettings: Observable<Void?>
private val updateParamsForPage = BehaviorSubject.create<DiscoveryParams>()
private val updateToolbarWithParams = BehaviorSubject.create<DiscoveryParams>()
private val successMessage = PublishSubject.create<String>()
private val messageError = PublishSubject.create<String?>()
init {
buildCheck.bind(this, webClient)
showActivityFeed = activityFeedClick
showBuildCheckAlert = newerBuildIsAvailable
showCreatorDashboard = creatorDashboardClick
showHelp = loggedOutSettingsClick
showInternalTools = internalToolsClick
showLoginTout = loggedOutLoginToutClick
showMessages = messagesClick
showProfile = profileClick
showSettings = settingsClick
val currentUser = currentUserType.observable()
val changedUser = currentUser
.distinctUntilChanged()
changedUser
.compose(bindToLifecycle())
.subscribe {
apiClient.config()
.compose(Transformers.neverError())
.subscribe { currentConfigType.config(it) }
}
// Seed params when we are freshly launching the app with no data.
val paramsFromInitialIntent = intent()
.take(1)
.map { it.action }
.filter { Intent.ACTION_MAIN == it }
.compose(Transformers.combineLatestPair(changedUser))
.map { DiscoveryParams.getDefaultParams(it.second) }
.share()
val uriFromVerification = intent()
.map { it.data }
.ofType(Uri::class.java)
.filter { it.isVerificationEmailUrl() }
val verification = uriFromVerification
.map { it.getTokenFromQueryParams() }
.filter { ObjectUtils.isNotNull(it) }
.switchMap { apiClient.verifyEmail(it) }
.materialize()
.share()
.distinctUntilChanged()
verification
.compose(Transformers.values())
.map { it.message() }
.compose(bindToLifecycle())
.subscribe(successMessage)
verification
.compose(Transformers.errors())
.map { ErrorEnvelope.fromThrowable(it) }
.map { it?.errorMessage() }
.filter { ObjectUtils.isNotNull(it) }
.compose(bindToLifecycle())
.subscribe(messageError)
currentUserType.isLoggedIn
.filter { it }
.distinctUntilChanged()
.take(1)
.filter { !sharedPreferences.getBoolean(HAS_SEEN_NOTIF_PERMISSIONS, false) }
.compose(bindToLifecycle())
.subscribe { showNotifPermissionRequest.onNext(null) }
hasSeenNotificationsPermission
.compose(bindToLifecycle())
.subscribe { sharedPreferences.edit().putBoolean(HAS_SEEN_NOTIF_PERMISSIONS, it).apply() }
val paramsFromIntent = intent()
.flatMap { DiscoveryIntentMapper.params(it, apiClient, apolloClient) }
val pagerSelectedPage = pagerSetPrimaryPage.distinctUntilChanged()
val drawerParamsClicked = childFilterRowClick
.mergeWith(topFilterRowClick)
.withLatestFrom(
pagerSelectedPage.map { DiscoveryUtils.sortFromPosition(it) }
) { drawerClickParams, currentParams ->
if (drawerClickParams.params().sort() == null)
drawerClickParams.params().toBuilder().sort(currentParams).build()
else drawerClickParams.params()
}
// Merge various param data sources.
val params = Observable.merge(
paramsFromInitialIntent,
paramsFromIntent,
drawerParamsClicked
)
val sortToTabOpen = Observable.merge(
pagerSelectedPage.map { DiscoveryUtils.sortFromPosition(it) },
params.map { it.sort() }
)
.filter { ObjectUtils.isNotNull(it) }
// Combine params with the selected sort position.
val paramsWithSort = Observable.combineLatest(
params,
sortToTabOpen
) { p, s -> p.toBuilder().sort(s).build() }
paramsWithSort
.compose(bindToLifecycle())
.subscribe(updateParamsForPage)
paramsWithSort
.compose(Transformers.takePairWhen(sortClicked.map { DiscoveryUtils.sortFromPosition(it) }))
.map<Pair<DiscoveryParams.Sort, DiscoveryParams>> {
Pair.create(
it.first.sort(),
it.first.toBuilder().sort(it.second).build()
)
}
.compose(bindToLifecycle())
.subscribe { analyticEvents.trackDiscoverSortCTA(it.first, it.second) }
paramsWithSort
.compose(Transformers.takeWhen(drawerParamsClicked))
.compose(bindToLifecycle())
.subscribe {
analyticEvents.trackDiscoverFilterCTA(it)
}
val categories = apolloClient.fetchCategories()
.compose(Transformers.neverError())
.flatMapIterable { it }
.toSortedList()
.share()
// Combine root categories with the selected sort position.
Observable.combineLatest<List<Category>?, Int, Pair<List<Category>, Int>>(
categories
.flatMapIterable { it }
.filter { it.isRoot }
.toList(),
pagerSelectedPage
) { c, psp -> Pair.create(c, psp) }
.compose(bindToLifecycle())
.subscribe(rootCategoriesAndPosition)
val drawerClickedParentCategory = parentFilterRowClick
.map { it.params().category() }
val expandedCategory = Observable.merge(
topFilterRowClick.map { null },
drawerClickedParentCategory
)
.scan(
null
) { previous: Category?, next: Category? ->
if (previous != null && next != null && previous == next) {
return@scan null
}
next
}
// Accumulate a list of pages to clear when the params or user changes,
// to avoid displaying old data.
pagerSelectedPage
.compose(Transformers.takeWhen(params))
.compose(Transformers.combineLatestPair(changedUser))
.map { it.first }
.flatMap {
Observable.from(DiscoveryParams.Sort.defaultSorts)
.map { sort: DiscoveryParams.Sort? -> sort.positionFromSort() }
.filter { sortPosition: Int -> sortPosition != it }
.toList()
}
.compose(bindToLifecycle())
.subscribe(clearPages)
params
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(updateToolbarWithParams)
updateParamsForPage
.map { true }
.compose(bindToLifecycle())
.subscribe(expandSortTabLayout)
Observable.combineLatest<List<Category>, DiscoveryParams, Category?, User, NavigationDrawerData>(
categories,
params,
expandedCategory,
currentUser
) { c, s, ec, u -> s.deriveNavigationDrawerData(c, ec, u) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(navigationDrawerData)
val drawerOpenObservables = listOf(
openDrawer,
childFilterRowClick.map { false },
topFilterRowClick.map { false },
internalToolsClick.map { false },
loggedOutLoginToutClick.map { false },
loggedOutSettingsClick.map { false },
activityFeedClick.map { false },
messagesClick.map { false },
creatorDashboardClick.map { false },
profileClick.map { false },
settingsClick.map { false }
)
Observable.merge(drawerOpenObservables)
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(drawerIsOpen)
val drawerOpened = openDrawer
.filter { bool: Boolean? -> bool.isTrue() }
currentUser
.map { currentDrawerMenuIcon(it) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe { drawerMenuIcon.onNext(it) }
}
override fun childFilterViewHolderRowClick(viewHolder: ChildFilterViewHolder, row: NavigationDrawerData.Section.Row) {
childFilterRowClick.onNext(row)
}
override fun discoveryPagerAdapterSetPrimaryPage(adapter: DiscoveryPagerAdapter, position: Int) {
pagerSetPrimaryPage.onNext(position)
}
override fun loggedInViewHolderActivityClick(viewHolder: LoggedInViewHolder) { activityFeedClick.onNext(null) }
override fun loggedInViewHolderDashboardClick(viewHolder: LoggedInViewHolder) { creatorDashboardClick.onNext(null) }
override fun loggedInViewHolderInternalToolsClick(viewHolder: LoggedInViewHolder) { internalToolsClick.onNext(null) }
override fun loggedInViewHolderMessagesClick(viewHolder: LoggedInViewHolder) { messagesClick.onNext(null) }
override fun loggedInViewHolderProfileClick(viewHolder: LoggedInViewHolder, user: User) { profileClick.onNext(null) }
override fun loggedInViewHolderSettingsClick(viewHolder: LoggedInViewHolder, user: User) { settingsClick.onNext(null) }
override fun loggedOutViewHolderActivityClick(viewHolder: LoggedOutViewHolder) { activityFeedClick.onNext(null) }
override fun loggedOutViewHolderInternalToolsClick(viewHolder: LoggedOutViewHolder) { internalToolsClick.onNext(null) }
override fun loggedOutViewHolderLoginToutClick(viewHolder: LoggedOutViewHolder) { loggedOutLoginToutClick.onNext(null) }
override fun loggedOutViewHolderHelpClick(viewHolder: LoggedOutViewHolder) { loggedOutSettingsClick.onNext(null) }
override fun topFilterViewHolderRowClick(viewHolder: TopFilterViewHolder, row: NavigationDrawerData.Section.Row) {
topFilterRowClick.onNext(row)
}
// - Inputs
override fun newerBuildIsAvailable(envelope: InternalBuildEnvelope) { newerBuildIsAvailable.onNext(envelope) }
override fun openDrawer(open: Boolean) { openDrawer.onNext(open) }
override fun parentFilterViewHolderRowClick(viewHolder: ParentFilterViewHolder, row: NavigationDrawerData.Section.Row) {
parentFilterRowClick.onNext(row)
}
override fun sortClicked(sortPosition: Int) { sortClicked.onNext(sortPosition) }
override fun hasSeenNotificationsPermission(hasShown: Boolean) { hasSeenNotificationsPermission.onNext(hasShown) }
// - Outputs
override fun clearPages(): Observable<List<Int>> { return clearPages }
override fun drawerIsOpen(): Observable<Boolean> { return drawerIsOpen }
override fun drawerMenuIcon(): Observable<Int> { return drawerMenuIcon }
override fun expandSortTabLayout(): Observable<Boolean> { return expandSortTabLayout }
override fun navigationDrawerData(): Observable<NavigationDrawerData> { return navigationDrawerData }
override fun rootCategoriesAndPosition(): Observable<Pair<List<Category>, Int>> { return rootCategoriesAndPosition }
override fun showActivityFeed(): Observable<Void?> { return showActivityFeed }
override fun showBuildCheckAlert(): Observable<InternalBuildEnvelope> { return showBuildCheckAlert }
override fun showCreatorDashboard(): Observable<Void?> { return showCreatorDashboard }
override fun showHelp(): Observable<Void?> { return showHelp }
override fun showInternalTools(): Observable<Void?> { return showInternalTools }
override fun showLoginTout(): Observable<Void?> { return showLoginTout }
override fun showMessages(): Observable<Void?> { return showMessages }
override fun showProfile(): Observable<Void?> { return showProfile }
override fun showSettings(): Observable<Void?> { return showSettings }
override fun updateParamsForPage(): Observable<DiscoveryParams> { return updateParamsForPage }
override fun updateToolbarWithParams(): Observable<DiscoveryParams> { return updateToolbarWithParams }
override fun showSuccessMessage(): Observable<String> { return successMessage }
override fun showErrorMessage(): Observable<String?> { return messageError }
override fun showNotifPermissionsRequest(): Observable<Void?> { return showNotifPermissionRequest }
}
}
| apache-2.0 | 8e958fc9ad0b751e3d504139b41ffe02 | 48 | 128 | 0.651316 | 5.500739 | false | false | false | false |
JetBrains/kotlin-native | klib/src/test/testData/TopLevelPropertiesCustomPackage.kt | 4 | 821 | /*
* Copyright 2010-2018 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.
*/
@file:Suppress("UNUSED_PARAMETER")
package custom.pkg
typealias MyTransformer = (String) -> Int
// top-level properties
val v1 = 1
val v2 = "hello"
val v3: (String) -> Int = { it.length }
val v4: MyTransformer = v3
| apache-2.0 | b002bb103e52c6870a820915ce7cc72c | 28.321429 | 75 | 0.724726 | 3.698198 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/utils/junix/virt/virsh/Virsh.kt | 1 | 8376 | package com.github.kerubistan.kerub.utils.junix.virt.virsh
import com.github.kerubistan.kerub.host.executeOrDie
import com.github.kerubistan.kerub.host.process
import com.github.kerubistan.kerub.model.SoftwarePackage
import com.github.kerubistan.kerub.model.display.RemoteConsoleProtocol
import com.github.kerubistan.kerub.model.hypervisor.LibvirtArch
import com.github.kerubistan.kerub.model.hypervisor.LibvirtCapabilities
import com.github.kerubistan.kerub.model.hypervisor.LibvirtGuest
import com.github.kerubistan.kerub.utils.LogLevel
import com.github.kerubistan.kerub.utils.equalsAnyOf
import com.github.kerubistan.kerub.utils.flag
import com.github.kerubistan.kerub.utils.getLogger
import com.github.kerubistan.kerub.utils.junix.common.Centos
import com.github.kerubistan.kerub.utils.junix.common.Debian
import com.github.kerubistan.kerub.utils.junix.common.Fedora
import com.github.kerubistan.kerub.utils.junix.common.OsCommand
import com.github.kerubistan.kerub.utils.junix.common.Ubuntu
import com.github.kerubistan.kerub.utils.junix.common.openSuse
import com.github.kerubistan.kerub.utils.silent
import com.github.kerubistan.kerub.utils.toBigInteger
import io.github.kerubistan.kroki.bytes.toBase64
import io.github.kerubistan.kroki.strings.substringBetween
import org.apache.sshd.client.session.ClientSession
import java.io.OutputStream
import java.io.StringReader
import java.util.Properties
import java.util.UUID
import javax.xml.bind.JAXBContext
object Virsh : OsCommand {
private val logger = getLogger()
private val utf8 = charset("UTF-8")
override fun providedBy(): List<Pair<(SoftwarePackage) -> Boolean, List<String>>> = listOf(
{ distro: SoftwarePackage -> distro.name.equalsAnyOf(Centos, Fedora, openSuse) }
to listOf("libvirt-client"),
{ distro: SoftwarePackage -> distro.name.equalsAnyOf(Debian) } to listOf("libvirt-clients",
"libvirt-daemon"),
{ distro: SoftwarePackage -> distro.name.equalsAnyOf(Ubuntu) } to listOf("libvirt-bin")
)
fun setSecret(session: ClientSession, id: UUID, type: SecretType, value: String) {
val secretDefFile = "/tmp/$id-secret.xml"
val secretDef = """<?xml version="1.0" encoding="UTF-8"?>
<secret ephemeral='no' private='yes'>
<uuid>$id</uuid>
<usage type='$type'>
<target>$id</target>
</usage>
</secret>"""
session.createSftpClient().use { sftp ->
try {
sftp.write(secretDefFile).use { file ->
file.write(secretDef.toByteArray(utf8))
}
session.executeOrDie("virsh secret-define $secretDefFile")
session.executeOrDie("virsh secret-set-value $id ${value.toByteArray().toBase64()}")
} finally {
sftp.remove(secretDefFile)
}
}
}
fun clearSecret(session: ClientSession, id: UUID) {
session.executeOrDie("virsh secret-undefine $id")
}
fun create(session: ClientSession, id: UUID, domainDef: String) {
val domainDefFile = "/tmp/$id.xml"
logger.info("creating domain: \n {}", domainDef)
session.createSftpClient().use { sftp ->
try {
sftp.write(domainDefFile).use { file ->
file.write(domainDef.toByteArray(utf8))
}
session.executeOrDie("virsh create $domainDefFile")
} finally {
silent(level = LogLevel.Debug, actionName = "clear temporary domain file") { sftp.remove(domainDefFile) }
}
}
}
fun blockCopy(session: ClientSession, domaindId: UUID, path: String, destination: String, shallow: Boolean = false,
format: String? = null, blockDev: Boolean = false) {
val formatFlag = if (format != null) {
"--format $format"
} else {
""
}
session.executeOrDie(
"virsh blockcopy $domaindId $path --dest $destination ${shallow.flag("--shallow")}" +
"${blockDev.flag("--blockdev")} --verbose --wait $formatFlag"
)
}
fun migrate(
session: ClientSession,
id: UUID,
targetAddress: String,
live: Boolean = true,
compressed: Boolean = true) {
session.executeOrDie(
"virsh migrate $id qemu+ssh://$targetAddress/system " +
"${if (live) "--live" else ""} ${if (compressed) " --compressed" else ""}" +
" --p2p --tunnelled"
)
}
fun destroy(session: ClientSession, id: UUID) {
session.executeOrDie("virsh destroy $id --graceful")
}
fun list(session: ClientSession): List<UUID> = session.executeOrDie(
"virsh list --uuid").lines().map { UUID.fromString(it) }
fun suspend(session: ClientSession, id: UUID) {
session.executeOrDie("virsh suspend $id")
}
fun resume(session: ClientSession, id: UUID) {
session.executeOrDie("virsh resume $id")
}
private const val domstatsCommand = "virsh domstats --raw"
fun domStat(session: ClientSession): List<DomainStat> {
return parseDomStats(session.executeOrDie(domstatsCommand))
}
internal fun parseDomStats(output: String) = output.split("\n\n").filter { it.isNotBlank() }.map {
toDomStat(it.trim())
}
internal class DomStatsOutputHandler(private val handler: (List<DomainStat>) -> Unit) : OutputStream() {
private val buff = StringBuilder()
override fun write(data: Int) {
buff.append(data.toChar())
if (buff.length > 2 && buff.endsWith("\n\n\n")) {
handler(parseDomStats(buff.toString()))
buff.clear()
}
}
}
fun domStat(session: ClientSession, callback: (List<DomainStat>) -> Unit) {
session.process(
"""bash -c "while true; do $domstatsCommand; sleep 1; done" """,
DomStatsOutputHandler(callback)
)
}
private fun toDomStat(virshDomStat: String): DomainStat {
val header = virshDomStat.substringBefore('\n')
val propertiesSource = virshDomStat.substringAfter('\n')
val props = StringReader(propertiesSource).use {
val tmp = Properties()
tmp.load(it)
tmp
}
val vcpuMax = requireNotNull(props.getProperty("vcpu.maximum")).toInt()
val netCount = props.getProperty("net.count")?.toInt() ?: 0
return DomainStat(
name = header.substringBetween("Domain: '", "'"),
balloonMax = props.getProperty("balloon.maximum")?.toBigInteger(),
balloonSize = props.getProperty("balloon.current")?.toBigInteger(),
vcpuMax = vcpuMax,
netStats = (0 until netCount).map { netId ->
toNetStat(
props.filter { it.key.toString().startsWith("net.$netId.") }
.map { it.key.toString() to it.value.toString() }
.toMap()
, netId
)
},
cpuStats = (0 until vcpuMax).map { vcpuid ->
toCpuStat(props
.filter { it.key.toString().startsWith("vcpu.$vcpuid.") }
.map { it.key.toString() to it.value.toString() }
.toMap(), vcpuid)
}
)
}
private fun toNetStat(props: Map<String, String>, netId: Int) = NetStat(
name = requireNotNull(props["net.$netId.name"]),
received = toNetTrafficStat(props, netId, "rx"),
sent = toNetTrafficStat(props, netId, "tx")
)
private fun netToLong(props: Map<String, String>, netId: Int, type: String, prop: String) = requireNotNull(
props["net.$netId.$type.$prop"]).toLong()
private fun toNetTrafficStat(props: Map<String, String>, netId: Int, type: String): NetTrafficStat = NetTrafficStat(
bytes = netToLong(props, netId, type, "bytes"),
drop = netToLong(props, netId, type, "drop"),
errors = netToLong(props, netId, type, "errs"),
packets = netToLong(props, netId, type, "pkts")
)
fun getDisplay(session: ClientSession, vmId: UUID): Pair<RemoteConsoleProtocol, Int> {
val display = session.executeOrDie("virsh domdisplay $vmId")
val protocol = RemoteConsoleProtocol.valueOf(display.substringBefore("://").toLowerCase())
val port = display.substringAfterLast(":").trim().toInt()
return protocol to port
}
private fun toCpuStat(props: Map<String, String>, id: Int): VcpuStat =
VcpuStat(
state = VcpuState.running,
time = props["vcpu.$id.time"]?.toLong()
)
fun capabilities(session: ClientSession): LibvirtCapabilities {
val capabilities = session.executeOrDie("virsh capabilities")
val jaxbContext = JAXBContext.newInstance(LibvirtXmlArch::class.java, LibvirtXmlCapabilities::class.java,
LibvirtXmlGuest::class.java)
return StringReader(capabilities).use {
val xmlCapabilities = jaxbContext.createUnmarshaller().unmarshal(it) as LibvirtXmlCapabilities
LibvirtCapabilities(xmlCapabilities.guests.map { xmlGuest ->
val arch = requireNotNull(xmlGuest.arch)
LibvirtGuest(
osType = requireNotNull(xmlGuest.osType),
arch = LibvirtArch(name = arch.name, emulator = arch.emulator, wordsize = arch.wordsize)
)
})
}
}
}
| apache-2.0 | b336e35fef9ba59550fe2c5a0a552858 | 34.491525 | 117 | 0.711079 | 3.389721 | false | false | false | false |
alexames/flatbuffers | tests/KotlinTest.kt | 4 | 23204 | /*
* Copyright 2014 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.
*/
import DictionaryLookup.*;
import MyGame.Example.*
import optional_scalars.*
import com.google.flatbuffers.ByteBufferUtil
import com.google.flatbuffers.FlatBufferBuilder
import NamespaceA.*
import NamespaceA.NamespaceB.*
import NamespaceA.NamespaceB.TableInNestedNS
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.FileChannel
import com.google.flatbuffers.Constants.SIZE_PREFIX_LENGTH
@kotlin.ExperimentalUnsignedTypes
class KotlinTest {
companion object {
@JvmStatic
fun main(args: Array<String>) {
// First, let's test reading a FlatBuffer generated by C++ code:
// This file was generated from monsterdata_test.json
val data = RandomAccessFile(File("monsterdata_test.mon"), "r").use {
val temp = ByteArray(it.length().toInt())
it.readFully(temp)
temp
}
// Now test it:
val bb = ByteBuffer.wrap(data)
TestBuffer(bb)
// Second, let's create a FlatBuffer from scratch in Java, and test it also.
// We use an initial size of 1 to exercise the reallocation algorithm,
// normally a size larger than the typical FlatBuffer you generate would be
// better for performance.
val fbb = FlatBufferBuilder(1)
TestBuilderBasics(fbb, true)
TestBuilderBasics(fbb, false)
TestExtendedBuffer(fbb.dataBuffer().asReadOnlyBuffer())
TestNamespaceNesting()
TestNestedFlatBuffer()
TestCreateByteVector()
TestCreateUninitializedVector()
TestByteBufferFactory()
TestSizedInputStream()
TestVectorOfUnions()
TestSharedStringPool()
TestScalarOptional()
TestDictionaryLookup()
println("FlatBuffers test: completed successfully")
}
fun TestDictionaryLookup() {
val fbb = FlatBufferBuilder(16)
val lfIndex = LongFloatEntry.createLongFloatEntry(fbb, 0, 99.0f)
val vectorEntriesIdx = LongFloatMap.createEntriesVector(fbb, intArrayOf(lfIndex))
val rootIdx = LongFloatMap.createLongFloatMap(fbb, vectorEntriesIdx)
LongFloatMap.finishLongFloatMapBuffer(fbb, rootIdx)
val map = LongFloatMap.getRootAsLongFloatMap(fbb.dataBuffer())
assert(map.entriesLength == 1)
val e = map.entries(0)!!
assert(e.key == 0L)
assert(e.value == 99.0f)
val e2 = map.entriesByKey(0)!!
assert(e2.key == 0L)
assert(e2.value == 99.0f)
}
fun TestEnums() {
assert(Color.name(Color.Red.toInt()) == "Red")
assert(Color.name(Color.Blue.toInt()) == "Blue")
assert(Any_.name(Any_.NONE.toInt()) == "NONE")
assert(Any_.name(Any_.Monster.toInt()) == "Monster")
}
fun TestBuffer(bb: ByteBuffer) {
assert(Monster.MonsterBufferHasIdentifier(bb) == true)
val monster = Monster.getRootAsMonster(bb)
assert(monster.hp == 80.toShort())
assert(monster.mana == 150.toShort()) // default
assert(monster.name == "MyMonster")
// monster.friendly() // can't access, deprecated
val pos = monster.pos!!
assert(pos.x == 1.0f)
assert(pos.y == 2.0f)
assert(pos.z == 3.0f)
assert(pos.test1 == 3.0)
// issue: int != byte
assert(pos.test2 == Color.Green)
val t = pos.test3!!
assert(t.a == 5.toShort())
assert(t.b == 6.toByte())
assert(monster.testType == Any_.Monster)
val monster2 = Monster()
assert(monster.test(monster2) != null == true)
assert(monster2.name == "Fred")
assert(monster.inventoryLength == 5)
var invsum = 0u
for (i in 0 until monster.inventoryLength)
invsum += monster.inventory(i)
assert(invsum == 10u)
// Alternative way of accessing a vector:
val ibb = monster.inventoryAsByteBuffer
invsum = 0u
while (ibb.position() < ibb.limit())
invsum += ibb.get().toUInt()
assert(invsum == 10u)
val test_0 = monster.test4(0)!!
val test_1 = monster.test4(1)!!
assert(monster.test4Length == 2)
assert(test_0.a + test_0.b + test_1.a + test_1.b == 100)
assert(monster.testarrayofstringLength == 2)
assert(monster.testarrayofstring(0) == "test1")
assert(monster.testarrayofstring(1) == "test2")
assert(monster.testbool == true)
}
// this method checks additional fields not present in the binary buffer read from file
// these new tests are performed on top of the regular tests
fun TestExtendedBuffer(bb: ByteBuffer) {
TestBuffer(bb)
val monster = Monster.getRootAsMonster(bb)
assert(monster.testhashu32Fnv1 == (Integer.MAX_VALUE + 1L).toUInt())
}
fun TestNamespaceNesting() {
// reference / manipulate these to verify compilation
val fbb = FlatBufferBuilder(1)
TableInNestedNS.startTableInNestedNS(fbb)
TableInNestedNS.addFoo(fbb, 1234)
val nestedTableOff = TableInNestedNS.endTableInNestedNS(fbb)
TableInFirstNS.startTableInFirstNS(fbb)
TableInFirstNS.addFooTable(fbb, nestedTableOff)
}
fun TestNestedFlatBuffer() {
val nestedMonsterName = "NestedMonsterName"
val nestedMonsterHp: Short = 600
val nestedMonsterMana: Short = 1024
var fbb1: FlatBufferBuilder? = FlatBufferBuilder(16)
val str1 = fbb1!!.createString(nestedMonsterName)
Monster.startMonster(fbb1)
Monster.addName(fbb1, str1)
Monster.addHp(fbb1, nestedMonsterHp)
Monster.addMana(fbb1, nestedMonsterMana)
val monster1 = Monster.endMonster(fbb1)
Monster.finishMonsterBuffer(fbb1, monster1)
val fbb1Bytes = fbb1.sizedByteArray()
val fbb2 = FlatBufferBuilder(16)
val str2 = fbb2.createString("My Monster")
val nestedBuffer = Monster.createTestnestedflatbufferVector(fbb2, fbb1Bytes.asUByteArray())
Monster.startMonster(fbb2)
Monster.addName(fbb2, str2)
Monster.addHp(fbb2, 50.toShort())
Monster.addMana(fbb2, 32.toShort())
Monster.addTestnestedflatbuffer(fbb2, nestedBuffer)
val monster = Monster.endMonster(fbb2)
Monster.finishMonsterBuffer(fbb2, monster)
// Now test the data extracted from the nested buffer
val mons = Monster.getRootAsMonster(fbb2.dataBuffer())
val nestedMonster = mons.testnestedflatbufferAsMonster!!
assert(nestedMonsterMana == nestedMonster.mana)
assert(nestedMonsterHp == nestedMonster.hp)
assert(nestedMonsterName == nestedMonster.name)
}
fun TestCreateByteVector() {
val fbb = FlatBufferBuilder(16)
val str = fbb.createString("MyMonster")
val inventory = byteArrayOf(0, 1, 2, 3, 4)
val vec = fbb.createByteVector(inventory)
Monster.startMonster(fbb)
Monster.addInventory(fbb, vec)
Monster.addName(fbb, str)
val monster1 = Monster.endMonster(fbb)
Monster.finishMonsterBuffer(fbb, monster1)
val monsterObject = Monster.getRootAsMonster(fbb.dataBuffer())
assert(monsterObject.inventory(1) == inventory[1].toUByte())
assert(monsterObject.inventoryLength == inventory.size)
assert(ByteBuffer.wrap(inventory) == monsterObject.inventoryAsByteBuffer)
}
fun TestCreateUninitializedVector() {
val fbb = FlatBufferBuilder(16)
val str = fbb.createString("MyMonster")
val inventory = byteArrayOf(0, 1, 2, 3, 4)
val bb = fbb.createUnintializedVector(1, inventory.size, 1)
for (i in inventory) {
bb.put(i)
}
val vec = fbb.endVector()
Monster.startMonster(fbb)
Monster.addInventory(fbb, vec)
Monster.addName(fbb, str)
val monster1 = Monster.endMonster(fbb)
Monster.finishMonsterBuffer(fbb, monster1)
val monsterObject = Monster.getRootAsMonster(fbb.dataBuffer())
assert(monsterObject.inventory(1) == inventory[1].toUByte())
assert(monsterObject.inventoryLength == inventory.size)
assert(ByteBuffer.wrap(inventory) == monsterObject.inventoryAsByteBuffer)
}
fun TestByteBufferFactory() {
class MappedByteBufferFactory : FlatBufferBuilder.ByteBufferFactory() {
override fun newByteBuffer(capacity: Int): ByteBuffer? {
var bb: ByteBuffer?
try {
bb = RandomAccessFile("javatest.bin", "rw").channel.map(
FileChannel.MapMode.READ_WRITE,
0,
capacity.toLong()
).order(ByteOrder.LITTLE_ENDIAN)
} catch (e: Throwable) {
println("FlatBuffers test: couldn't map ByteBuffer to a file")
bb = null
}
return bb
}
}
val fbb = FlatBufferBuilder(1, MappedByteBufferFactory())
TestBuilderBasics(fbb, false)
}
fun TestSizedInputStream() {
// Test on default FlatBufferBuilder that uses HeapByteBuffer
val fbb = FlatBufferBuilder(1)
TestBuilderBasics(fbb, false)
val `in` = fbb.sizedInputStream()
val array = fbb.sizedByteArray()
var count = 0
var currentVal = 0
while (currentVal != -1 && count < array.size) {
try {
currentVal = `in`.read()
} catch (e: java.io.IOException) {
println("FlatBuffers test: couldn't read from InputStream")
return
}
assert(currentVal.toByte() == array[count])
count++
}
assert(count == array.size)
}
fun TestBuilderBasics(fbb: FlatBufferBuilder, sizePrefix: Boolean) {
val names = intArrayOf(fbb.createString("Frodo"), fbb.createString("Barney"), fbb.createString("Wilma"))
val off = IntArray(3)
Monster.startMonster(fbb)
Monster.addName(fbb, names[0])
off[0] = Monster.endMonster(fbb)
Monster.startMonster(fbb)
Monster.addName(fbb, names[1])
off[1] = Monster.endMonster(fbb)
Monster.startMonster(fbb)
Monster.addName(fbb, names[2])
off[2] = Monster.endMonster(fbb)
val sortMons = fbb.createSortedVectorOfTables(Monster(), off)
// We set up the same values as monsterdata.json:
val str = fbb.createString("MyMonster")
val inv = Monster.createInventoryVector(fbb, byteArrayOf(0, 1, 2, 3, 4).asUByteArray())
val fred = fbb.createString("Fred")
Monster.startMonster(fbb)
Monster.addName(fbb, fred)
val mon2 = Monster.endMonster(fbb)
Monster.startTest4Vector(fbb, 2)
Test.createTest(fbb, 10.toShort(), 20.toByte())
Test.createTest(fbb, 30.toShort(), 40.toByte())
val test4 = fbb.endVector()
val testArrayOfString =
Monster.createTestarrayofstringVector(fbb, intArrayOf(fbb.createString("test1"), fbb.createString("test2")))
Monster.startMonster(fbb)
Monster.addPos(
fbb, Vec3.createVec3(
fbb, 1.0f, 2.0f, 3.0f, 3.0,
Color.Green, 5.toShort(), 6.toByte()
)
)
Monster.addHp(fbb, 80.toShort())
Monster.addName(fbb, str)
Monster.addInventory(fbb, inv)
Monster.addTestType(fbb, Any_.Monster)
Monster.addTest(fbb, mon2)
Monster.addTest4(fbb, test4)
Monster.addTestarrayofstring(fbb, testArrayOfString)
Monster.addTestbool(fbb, true)
Monster.addTesthashu32Fnv1(fbb, (Integer.MAX_VALUE + 1L).toUInt())
Monster.addTestarrayoftables(fbb, sortMons)
val mon = Monster.endMonster(fbb)
if (sizePrefix) {
Monster.finishSizePrefixedMonsterBuffer(fbb, mon)
} else {
Monster.finishMonsterBuffer(fbb, mon)
}
// Write the result to a file for debugging purposes:
// Note that the binaries are not necessarily identical, since the JSON
// parser may serialize in a slightly different order than the above
// Java code. They are functionally equivalent though.
try {
val filename = "monsterdata_java_wire" + (if (sizePrefix) "_sp" else "") + ".mon"
val fc = FileOutputStream(filename).channel
fc.write(fbb.dataBuffer().duplicate())
fc.close()
} catch (e: java.io.IOException) {
println("FlatBuffers test: couldn't write file")
return
}
// Test it:
var dataBuffer = fbb.dataBuffer()
if (sizePrefix) {
assert(
ByteBufferUtil.getSizePrefix(dataBuffer) + SIZE_PREFIX_LENGTH ==
dataBuffer.remaining()
)
dataBuffer = ByteBufferUtil.removeSizePrefix(dataBuffer)
}
TestExtendedBuffer(dataBuffer)
// Make sure it also works with read only ByteBuffers. This is slower,
// since creating strings incurs an additional copy
// (see Table.__string).
TestExtendedBuffer(dataBuffer.asReadOnlyBuffer())
TestEnums()
//Attempt to mutate Monster fields and check whether the buffer has been mutated properly
// revert to original values after testing
val monster = Monster.getRootAsMonster(dataBuffer)
// mana is optional and does not exist in the buffer so the mutation should fail
// the mana field should retain its default value
assert(monster.mutateMana(10.toShort()) == false)
assert(monster.mana == 150.toShort())
// Accessing a vector of sorted by the key tables
assert(monster.testarrayoftables(0)!!.name == "Barney")
assert(monster.testarrayoftables(1)!!.name == "Frodo")
assert(monster.testarrayoftables(2)!!.name == "Wilma")
// Example of searching for a table by the key
assert(monster.testarrayoftablesByKey("Frodo")!!.name == "Frodo")
assert(monster.testarrayoftablesByKey("Barney")!!.name == "Barney")
assert(monster.testarrayoftablesByKey("Wilma")!!.name == "Wilma")
// testType is an existing field and mutating it should succeed
assert(monster.testType == Any_.Monster)
assert(monster.mutateTestType(Any_.NONE) == true)
assert(monster.testType == Any_.NONE)
assert(monster.mutateTestType(Any_.Monster) == true)
assert(monster.testType == Any_.Monster)
//mutate the inventory vector
assert(monster.mutateInventory(0, 1u) == true)
assert(monster.mutateInventory(1, 2u) == true)
assert(monster.mutateInventory(2, 3u) == true)
assert(monster.mutateInventory(3, 4u) == true)
assert(monster.mutateInventory(4, 5u) == true)
for (i in 0 until monster.inventoryLength) {
assert(monster.inventory(i) == (i.toUByte() + 1u).toUByte())
}
//reverse mutation
assert(monster.mutateInventory(0, 0u) == true)
assert(monster.mutateInventory(1, 1u) == true)
assert(monster.mutateInventory(2, 2u) == true)
assert(monster.mutateInventory(3, 3u) == true)
assert(monster.mutateInventory(4, 4u) == true)
// get a struct field and edit one of its fields
val pos = monster.pos!!
assert(pos.x == 1.0f)
pos.mutateX(55.0f)
assert(pos.x == 55.0f)
pos.mutateX(1.0f)
assert(pos.x == 1.0f)
}
fun TestVectorOfUnions() {
val fbb = FlatBufferBuilder()
val swordAttackDamage = 1
val characterVector = intArrayOf(Attacker.createAttacker(fbb, swordAttackDamage))
val characterTypeVector = ubyteArrayOf(Character_.MuLan)
Movie.finishMovieBuffer(
fbb,
Movie.createMovie(
fbb,
0u,
0,
Movie.createCharactersTypeVector(fbb, characterTypeVector),
Movie.createCharactersVector(fbb, characterVector)
)
)
val movie = Movie.getRootAsMovie(fbb.dataBuffer())
assert(movie.charactersTypeLength == characterTypeVector.size)
assert(movie.charactersLength == characterVector.size)
assert(movie.charactersType(0) == characterTypeVector[0])
assert((movie.characters(Attacker(), 0) as Attacker).swordAttackDamage == swordAttackDamage)
}
fun TestSharedStringPool() {
val fb = FlatBufferBuilder(1);
val testString = "My string";
val offset = fb.createSharedString(testString);
for (i in 0..10) {
assert(offset == fb.createSharedString(testString));
}
}
fun TestScalarOptional() {
val fbb = FlatBufferBuilder(1)
ScalarStuff.startScalarStuff(fbb)
var pos = ScalarStuff.endScalarStuff(fbb)
fbb.finish(pos)
var scalarStuff = ScalarStuff.getRootAsScalarStuff(fbb.dataBuffer())
assert(scalarStuff.justI8 == 0.toByte())
assert(scalarStuff.maybeI8 == null)
assert(scalarStuff.defaultI8 == 42.toByte())
assert(scalarStuff.justU8 == 0.toUByte())
assert(scalarStuff.maybeU8 == null)
assert(scalarStuff.defaultU8 == 42.toUByte())
assert(scalarStuff.justI16 == 0.toShort())
assert(scalarStuff.maybeI16 == null)
assert(scalarStuff.defaultI16 == 42.toShort())
assert(scalarStuff.justU16 == 0.toUShort())
assert(scalarStuff.maybeU16 == null)
assert(scalarStuff.defaultU16 == 42.toUShort())
assert(scalarStuff.justI32 == 0)
assert(scalarStuff.maybeI32 == null)
assert(scalarStuff.defaultI32 == 42)
assert(scalarStuff.justU32 == 0.toUInt())
assert(scalarStuff.maybeU32 == null)
assert(scalarStuff.defaultU32 == 42U)
assert(scalarStuff.justI64 == 0L)
assert(scalarStuff.maybeI64 == null)
assert(scalarStuff.defaultI64 == 42L)
assert(scalarStuff.justU64 == 0UL)
assert(scalarStuff.maybeU64 == null)
assert(scalarStuff.defaultU64 == 42UL)
assert(scalarStuff.justF32 == 0.0f)
assert(scalarStuff.maybeF32 == null)
assert(scalarStuff.defaultF32 == 42.0f)
assert(scalarStuff.justF64 == 0.0)
assert(scalarStuff.maybeF64 == null)
assert(scalarStuff.defaultF64 == 42.0)
assert(scalarStuff.justBool == false)
assert(scalarStuff.maybeBool == null)
assert(scalarStuff.defaultBool == true)
assert(scalarStuff.justEnum == OptionalByte.None)
assert(scalarStuff.maybeEnum == null)
assert(scalarStuff.defaultEnum == OptionalByte.One)
fbb.clear()
ScalarStuff.startScalarStuff(fbb)
ScalarStuff.addJustI8(fbb, 5.toByte())
ScalarStuff.addMaybeI8(fbb, 5.toByte())
ScalarStuff.addDefaultI8(fbb, 5.toByte())
ScalarStuff.addJustU8(fbb, 6.toUByte())
ScalarStuff.addMaybeU8(fbb, 6.toUByte())
ScalarStuff.addDefaultU8(fbb, 6.toUByte())
ScalarStuff.addJustI16(fbb, 7.toShort())
ScalarStuff.addMaybeI16(fbb, 7.toShort())
ScalarStuff.addDefaultI16(fbb, 7.toShort())
ScalarStuff.addJustU16(fbb, 8.toUShort())
ScalarStuff.addMaybeU16(fbb, 8.toUShort())
ScalarStuff.addDefaultU16(fbb, 8.toUShort())
ScalarStuff.addJustI32(fbb, 9)
ScalarStuff.addMaybeI32(fbb, 9)
ScalarStuff.addDefaultI32(fbb, 9)
ScalarStuff.addJustU32(fbb, 10.toUInt())
ScalarStuff.addMaybeU32(fbb, 10.toUInt())
ScalarStuff.addDefaultU32(fbb, 10.toUInt())
ScalarStuff.addJustI64(fbb, 11L)
ScalarStuff.addMaybeI64(fbb, 11L)
ScalarStuff.addDefaultI64(fbb, 11L)
ScalarStuff.addJustU64(fbb, 12UL)
ScalarStuff.addMaybeU64(fbb, 12UL)
ScalarStuff.addDefaultU64(fbb, 12UL)
ScalarStuff.addJustF32(fbb, 13.0f)
ScalarStuff.addMaybeF32(fbb, 13.0f)
ScalarStuff.addDefaultF32(fbb, 13.0f)
ScalarStuff.addJustF64(fbb, 14.0)
ScalarStuff.addMaybeF64(fbb, 14.0)
ScalarStuff.addDefaultF64(fbb, 14.0)
ScalarStuff.addJustBool(fbb, true)
ScalarStuff.addMaybeBool(fbb, true)
ScalarStuff.addDefaultBool(fbb, true)
ScalarStuff.addJustEnum(fbb, OptionalByte.Two)
ScalarStuff.addMaybeEnum(fbb, OptionalByte.Two)
ScalarStuff.addDefaultEnum(fbb, OptionalByte.Two)
pos = ScalarStuff.endScalarStuff(fbb)
fbb.finish(pos)
scalarStuff = ScalarStuff.getRootAsScalarStuff(fbb.dataBuffer())
assert(scalarStuff.justI8 == 5.toByte())
assert(scalarStuff.maybeI8 == 5.toByte())
assert(scalarStuff.defaultI8 == 5.toByte())
assert(scalarStuff.justU8 == 6.toUByte())
assert(scalarStuff.maybeU8 == 6.toUByte())
assert(scalarStuff.defaultU8 == 6.toUByte())
assert(scalarStuff.justI16 == 7.toShort())
assert(scalarStuff.maybeI16 == 7.toShort())
assert(scalarStuff.defaultI16 == 7.toShort())
assert(scalarStuff.justU16 == 8.toUShort())
assert(scalarStuff.maybeU16 == 8.toUShort())
assert(scalarStuff.defaultU16 == 8.toUShort())
assert(scalarStuff.justI32 == 9)
assert(scalarStuff.maybeI32 == 9)
assert(scalarStuff.defaultI32 == 9)
assert(scalarStuff.justU32 == 10u)
assert(scalarStuff.maybeU32 == 10u)
assert(scalarStuff.defaultU32 == 10u)
assert(scalarStuff.justI64 == 11L)
assert(scalarStuff.maybeI64 == 11L)
assert(scalarStuff.defaultI64 == 11L)
assert(scalarStuff.justU64 == 12UL)
assert(scalarStuff.maybeU64 == 12UL)
assert(scalarStuff.defaultU64 == 12UL)
assert(scalarStuff.justF32 == 13.0f)
assert(scalarStuff.maybeF32 == 13.0f)
assert(scalarStuff.defaultF32 == 13.0f)
assert(scalarStuff.justF64 == 14.0)
assert(scalarStuff.maybeF64 == 14.0)
assert(scalarStuff.defaultF64 == 14.0)
assert(scalarStuff.justBool == true)
assert(scalarStuff.maybeBool == true)
assert(scalarStuff.defaultBool == true)
assert(scalarStuff.justEnum == OptionalByte.Two)
assert(scalarStuff.maybeEnum == OptionalByte.Two)
assert(scalarStuff.defaultEnum == OptionalByte.Two)
}
}
}
| apache-2.0 | b92714b9615c333ea01eeff424a026ff | 36.305466 | 120 | 0.633253 | 3.96921 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveInJavaTest.kt | 4 | 2405 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.resolve
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiElement
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.analysis.decompiler.psi.file.KtClsFile
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.MockLibraryFacility
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.psi.KtDeclaration
import org.junit.Assert
private val FILE_WITH_KOTLIN_CODE = IDEA_TEST_DATA_DIR.resolve("resolve/referenceInJava/dependency/dependencies.kt")
abstract class AbstractReferenceResolveInJavaTest : AbstractReferenceResolveTest() {
override fun doTest(path: String) {
val fileName = fileName()
assert(fileName.endsWith(".java")) { fileName }
myFixture.configureByText("dependencies.kt", FileUtil.loadFile(FILE_WITH_KOTLIN_CODE, true))
myFixture.configureByFile(fileName)
performChecks()
}
}
abstract class AbstractReferenceToCompiledKotlinResolveInJavaTest : AbstractReferenceResolveTest() {
private val mockLibraryFacility = MockLibraryFacility(FILE_WITH_KOTLIN_CODE)
override fun doTest(path: String) {
myFixture.configureByFile(fileName())
performChecks()
}
override fun setUp() {
super.setUp()
mockLibraryFacility.setUp(module)
}
override fun tearDown() {
runAll(
ThrowableRunnable { mockLibraryFacility.tearDown(module) },
ThrowableRunnable { super.tearDown() }
)
}
override val refMarkerText: String
get() = "CLS_REF"
override fun checkResolvedTo(element: PsiElement) {
val navigationElement = element.navigationElement
Assert.assertFalse(
"Reference should not navigate to a light element\nWas: ${navigationElement::class.java.simpleName}",
navigationElement is KtLightElement<*, *>
)
Assert.assertTrue(
"Reference should navigate to a kotlin declaration\nWas: ${navigationElement::class.java.simpleName}",
navigationElement is KtDeclaration || navigationElement is KtClsFile
)
}
}
| apache-2.0 | 8da470222e84e78530377b16df703bf6 | 37.790323 | 158 | 0.727235 | 4.74359 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/multiplatform/multiPlatformSetup.kt | 2 | 13812 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.multiplatform
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.StdModuleTypes
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import org.jetbrains.kotlin.checkers.utils.clearFileFromDiagnosticMarkup
import org.jetbrains.kotlin.idea.base.platforms.KotlinCommonLibraryKind
import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptLibraryKind
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.base.plugin.artifacts.TestKotlinArtifacts
import org.jetbrains.kotlin.idea.framework.KotlinSdkType
import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest
import org.jetbrains.kotlin.idea.stubs.createMultiplatformFacetM1
import org.jetbrains.kotlin.idea.stubs.createMultiplatformFacetM3
import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.kotlin.idea.test.PluginTestCaseBase
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.sourceRoots
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.js.isJs
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.platform.konan.NativePlatforms
import org.jetbrains.kotlin.platform.konan.isNative
import org.jetbrains.kotlin.projectModel.*
import org.jetbrains.kotlin.test.TestJdkKind
import org.jetbrains.kotlin.types.typeUtil.closure
import java.io.File
// allows to configure a test mpp project
// testRoot is supposed to contain several directories which contain module sources roots
// configuration is based on those directories names
fun AbstractMultiModuleTest.setupMppProjectFromDirStructure(testRoot: File) {
assert(testRoot.isDirectory) { testRoot.absolutePath + " must be a directory" }
val dependencies = dependenciesFile(testRoot)
if (dependencies.exists()) {
setupMppProjectFromDependenciesFile(dependencies, testRoot)
return
}
val dirs = testRoot.listFiles().filter { it.isDirectory }
val rootInfos = dirs.map { parseDirName(it) }
doSetupProject(rootInfos)
}
fun AbstractMultiModuleTest.setupMppProjectFromTextFile(testRoot: File) {
assert(testRoot.isDirectory) { testRoot.absolutePath + " must be a directory" }
val dependencies = dependenciesFile(testRoot)
setupMppProjectFromDependenciesFile(dependencies, testRoot)
}
private fun dependenciesFile(testRoot: File) = File(testRoot, "dependencies.txt")
fun AbstractMultiModuleTest.setupMppProjectFromDependenciesFile(dependencies: File, testRoot: File) {
val projectModel = ProjectStructureParser(testRoot).parse(FileUtil.loadFile(dependencies))
check(projectModel.modules.isNotEmpty()) { "No modules were parsed from dependencies.txt" }
doSetup(projectModel)
}
fun AbstractMultiModuleTest.doSetup(projectModel: ProjectResolveModel) {
val resolveModulesToIdeaModules = projectModel.modules.map { resolveModule ->
val ideaModule = createModule(resolveModule.name)
addRoot(
ideaModule,
resolveModule.root,
isTestRoot = false,
transformContainedFiles = { if (it.extension == "kt") clearFileFromDiagnosticMarkup(it) }
)
if (resolveModule.testRoot != null) {
addRoot(
ideaModule,
resolveModule.testRoot,
isTestRoot = true,
transformContainedFiles = { if (it.extension == "kt") clearFileFromDiagnosticMarkup(it) }
)
}
resolveModule to ideaModule
}.toMap()
for ((resolveModule, ideaModule) in resolveModulesToIdeaModules.entries) {
val directDependencies: Set<ResolveModule> = resolveModule.dependencies.mapTo(mutableSetOf()) { it.to }
resolveModule.dependencies.closure(preserveOrder = true) { it.to.dependencies }.forEach {
when (val dependency = it.to) {
is ResolveSdk -> {
// Only set module SDK if it is specified in module's dependencies explicitly.
// Otherwise the last transitive SDK dependency will be written as Module's SDK, which doesn't happen in the real IDE
// This check is not lifted to capture an SDK dependency and avoid configuring it as a library or module one
if (dependency in directDependencies)
setUpSdkForModule(ideaModule, dependency)
}
is ResolveLibrary -> ideaModule.addLibrary(dependency.root, dependency.name, dependency.kind)
else -> ideaModule.addDependency(resolveModulesToIdeaModules[dependency]!!)
}
}
}
for ((resolveModule, ideaModule) in resolveModulesToIdeaModules.entries) {
val platform = resolveModule.platform
val pureKotlinSourceFolders = ideaModule.collectSourceFolders()
ideaModule.createMultiplatformFacetM3(
platform,
dependsOnModuleNames = resolveModule.dependencies.filter { it.kind == ResolveDependency.Kind.DEPENDS_ON }.map { it.to.name },
pureKotlinSourceFolders = pureKotlinSourceFolders
)
// New inference is enabled here as these tests are using type refinement feature that is working only along with NI
ideaModule.enableMultiPlatform(additionalCompilerArguments = "-Xnew-inference " + (resolveModule.additionalCompilerArgs ?: ""))
}
}
private fun AbstractMultiModuleTest.setUpSdkForModule(ideaModule: Module, sdk: ResolveSdk) {
when (sdk) {
FullJdk -> ConfigLibraryUtil.configureSdk(ideaModule, PluginTestCaseBase.addJdk(testRootDisposable) {
PluginTestCaseBase.jdk(TestJdkKind.FULL_JDK)
})
MockJdk -> ConfigLibraryUtil.configureSdk(ideaModule, PluginTestCaseBase.addJdk(testRootDisposable) {
PluginTestCaseBase.jdk(TestJdkKind.MOCK_JDK)
})
KotlinSdk -> {
KotlinSdkType.setUpIfNeeded(testRootDisposable)
ConfigLibraryUtil.configureSdk(
ideaModule,
runReadAction { ProjectJdkTable.getInstance() }.findMostRecentSdkOfType(KotlinSdkType.INSTANCE)
?: error("Kotlin SDK wasn't created")
)
}
else -> error("Don't know how to set up SDK of type: ${sdk::class}")
}
}
private fun Module.collectSourceFolders(): List<String> = sourceRoots.map { it.path }
private fun AbstractMultiModuleTest.doSetupProject(rootInfos: List<RootInfo>) {
val infosByModuleId = rootInfos.groupBy { it.moduleId }
val modulesById = infosByModuleId.mapValues { (moduleId, infos) ->
createModuleWithRoots(moduleId, infos)
}
infosByModuleId.entries.forEach { (id, rootInfos) ->
val module = modulesById[id]!!
rootInfos.flatMap { it.dependencies }.forEach {
val platform = id.platform
when (it) {
is ModuleDependency -> module.addDependency(modulesById[it.moduleId]!!)
is StdlibDependency -> {
when {
platform.isCommon() -> module.addLibrary(TestKotlinArtifacts.kotlinStdlibCommon, kind = KotlinCommonLibraryKind)
platform.isJvm() -> module.addLibrary(KotlinArtifacts.kotlinStdlib)
platform.isJs() -> module.addLibrary(KotlinArtifacts.kotlinStdlibJs, kind = KotlinJavaScriptLibraryKind)
else -> error("Unknown platform $this")
}
}
is FullJdkDependency -> {
ConfigLibraryUtil.configureSdk(module, PluginTestCaseBase.addJdk(testRootDisposable) {
PluginTestCaseBase.jdk(TestJdkKind.FULL_JDK)
})
}
is CoroutinesDependency -> module.enableCoroutines()
is KotlinTestDependency -> when {
platform.isJvm() -> module.addLibrary(KotlinArtifacts.kotlinTestJunit)
platform.isJs() -> module.addLibrary(KotlinArtifacts.kotlinTestJs, kind = KotlinJavaScriptLibraryKind)
}
}
}
}
modulesById.forEach { (nameAndPlatform, module) ->
val (name, platform) = nameAndPlatform
val pureKotlinSourceFolders = module.collectSourceFolders()
when {
platform.isCommon() -> {
module.createMultiplatformFacetM1(
platform,
useProjectSettings = false,
implementedModuleNames = emptyList(),
pureKotlinSourceFolders = pureKotlinSourceFolders
)
}
else -> {
val commonModuleId = ModuleId(name, CommonPlatforms.defaultCommonPlatform)
module.createMultiplatformFacetM1(
platform,
implementedModuleNames = listOf(commonModuleId.ideaModuleName()),
pureKotlinSourceFolders = pureKotlinSourceFolders
)
module.enableMultiPlatform()
modulesById[commonModuleId]?.let { commonModule ->
module.addDependency(commonModule)
}
}
}
}
}
private fun AbstractMultiModuleTest.createModuleWithRoots(
moduleId: ModuleId,
infos: List<RootInfo>
): Module {
val module = createModule(moduleId.ideaModuleName())
for ((_, isTestRoot, moduleRoot) in infos) {
addRoot(module, moduleRoot, isTestRoot)
}
return module
}
private fun AbstractMultiModuleTest.createModule(name: String): Module {
val moduleDir = KotlinTestUtils.tmpDirForReusableFolder("kotlinTest")
val module = createModule("$moduleDir/$name", StdModuleTypes.JAVA)
val root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(moduleDir)
checkNotNull(root)
module.project.executeWriteCommand("refresh") {
root.refresh(false, true)
}
return module
}
private val testSuffixes = setOf("test", "tests")
private val platformNames = mapOf(
listOf("header", "common", "expect") to CommonPlatforms.defaultCommonPlatform,
listOf("java", "jvm") to JvmPlatforms.defaultJvmPlatform,
listOf("java8", "jvm8") to JvmPlatforms.jvm8,
listOf("java6", "jvm6") to JvmPlatforms.jvm6,
listOf("js", "javascript") to JsPlatforms.defaultJsPlatform,
listOf("native") to NativePlatforms.unspecifiedNativePlatform
)
private fun parseDirName(dir: File): RootInfo {
val parts = dir.name.split("_")
return RootInfo(parseModuleId(parts), parseIsTestRoot(parts), dir, parseDependencies(parts))
}
private fun parseDependencies(parts: List<String>) =
parts.filter { it.startsWith("dep(") && it.endsWith(")") }.map {
parseDependency(it)
}
private fun parseDependency(it: String): Dependency {
val dependencyString = it.removePrefix("dep(").removeSuffix(")")
return when {
dependencyString.equals("stdlib", ignoreCase = true) -> StdlibDependency
dependencyString.equals("fulljdk", ignoreCase = true) -> FullJdkDependency
dependencyString.equals("coroutines", ignoreCase = true) -> CoroutinesDependency
dependencyString.equals("kotlin-test", ignoreCase = true) -> KotlinTestDependency
else -> ModuleDependency(parseModuleId(dependencyString.split("-")))
}
}
private fun parseModuleId(parts: List<String>): ModuleId {
val platform = parsePlatform(parts)
val name = parseModuleName(parts)
val id = parseIndex(parts) ?: 0
assert(id == 0 || !platform.isCommon())
return ModuleId(name, platform, id)
}
private fun parsePlatform(parts: List<String>) =
platformNames.entries.single { (names, _) ->
names.any { name -> parts.any { part -> part.equals(name, ignoreCase = true) } }
}.value
private fun parseModuleName(parts: List<String>) = when {
parts.size > 1 -> parts.first()
else -> "testModule"
}
private fun parseIsTestRoot(parts: List<String>) =
testSuffixes.any { suffix -> parts.any { it.equals(suffix, ignoreCase = true) } }
private fun parseIndex(parts: List<String>): Int? {
return parts.singleOrNull() { it.startsWith("id") }?.substringAfter("id")?.toInt()
}
private data class ModuleId(
val groupName: String,
val platform: TargetPlatform,
val index: Int = 0
) {
fun ideaModuleName(): String {
val suffix = "_$index".takeIf { index != 0 } ?: ""
return "${groupName}_${platform.presentableName}$suffix"
}
}
private val TargetPlatform.presentableName: String
get() = when {
isCommon() -> "Common"
isJvm() -> "JVM"
isJs() -> "JS"
isNative() -> "Native"
else -> error("Unknown platform $this")
}
private data class RootInfo(
val moduleId: ModuleId,
val isTestRoot: Boolean,
val moduleRoot: File,
val dependencies: List<Dependency>
)
private sealed class Dependency
private class ModuleDependency(val moduleId: ModuleId) : Dependency()
private object StdlibDependency : Dependency()
private object FullJdkDependency : Dependency()
private object CoroutinesDependency : Dependency()
private object KotlinTestDependency : Dependency()
| apache-2.0 | 673741ebffecf234021c4d4376d349d3 | 40.854545 | 158 | 0.688966 | 5.051939 | false | true | false | false |
stoyicker/dinger | data/src/main/kotlin/data/tinder/recommendation/RecommendationUserSpotifyThemeTrack.kt | 1 | 550 | package data.tinder.recommendation
import com.squareup.moshi.Json
internal class RecommendationUserSpotifyThemeTrack private constructor(
@field:Json(name = "artists")
val artists: Array<RecommendationUserSpotifyThemeTrackArtist>,
@field:Json(name = "album")
val album: RecommendationUserSpotifyThemeTrackAlbum,
@field:Json(name = "preview_url")
val previewUrl: String?,
@field:Json(name = "name")
val name: String,
@field:Json(name = "id")
val id: String,
@field:Json(name = "uri")
val uri: String)
| mit | df48192b8060f156456934593706ea5f | 31.352941 | 71 | 0.710909 | 3.819444 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinMPPGradleProjectResolver.kt | 1 | 51849 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleJava.configuration
import com.intellij.build.events.MessageEvent
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.*
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.normalizePath
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.toCanonicalPath
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants
import com.intellij.openapi.externalSystem.util.Order
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.PathUtil
import com.intellij.util.PathUtilRt
import com.intellij.util.PlatformUtils
import com.intellij.util.SmartList
import com.intellij.util.containers.MultiMap
import com.intellij.util.text.VersionComparatorUtil
import org.gradle.tooling.model.UnsupportedMethodException
import org.gradle.tooling.model.idea.IdeaContentRoot
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.ManualLanguageFeatureSetting
import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.codeInsight.tooling.IdePlatformKindTooling
import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils
import org.jetbrains.kotlin.idea.gradle.configuration.*
import org.jetbrains.kotlin.idea.gradle.configuration.GradlePropertiesFileFacade.Companion.KOTLIN_NOT_IMPORTED_COMMON_SOURCE_SETS_SETTING
import org.jetbrains.kotlin.idea.gradle.configuration.utils.UnsafeTestSourceSetHeuristicApi
import org.jetbrains.kotlin.idea.gradle.configuration.utils.predictedProductionSourceSetName
import org.jetbrains.kotlin.idea.gradle.ui.notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded
import org.jetbrains.kotlin.idea.gradleJava.configuration.mpp.*
import org.jetbrains.kotlin.idea.gradleJava.configuration.mpp.getCompilations
import org.jetbrains.kotlin.idea.gradleJava.configuration.mpp.populateModuleDependenciesByCompilations
import org.jetbrains.kotlin.idea.gradleJava.configuration.mpp.populateModuleDependenciesBySourceSetVisibilityGraph
import org.jetbrains.kotlin.idea.gradleJava.configuration.utils.KotlinModuleUtils.calculateRunTasks
import org.jetbrains.kotlin.idea.gradleJava.configuration.utils.KotlinModuleUtils.fullName
import org.jetbrains.kotlin.idea.gradleJava.configuration.utils.KotlinModuleUtils.getGradleModuleQualifiedName
import org.jetbrains.kotlin.idea.gradleJava.configuration.utils.KotlinModuleUtils.getKotlinModuleId
import org.jetbrains.kotlin.idea.gradleTooling.*
import org.jetbrains.kotlin.idea.gradleTooling.KotlinMPPGradleModelBuilder
import org.jetbrains.kotlin.idea.gradleTooling.arguments.CachedExtractedArgsInfo
import org.jetbrains.kotlin.idea.gradleTooling.arguments.CachedSerializedArgsInfo
import org.jetbrains.kotlin.idea.projectModel.*
import org.jetbrains.kotlin.idea.util.NotNullableCopyableDataNodeUserDataProperty
import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.util.removeSuffixIfPresent
import org.jetbrains.plugins.gradle.model.*
import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.CONFIGURATION_ARTIFACTS
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.MODULES_OUTPUTS
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil.getModuleId
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
import java.lang.reflect.Proxy
import java.util.*
import java.util.stream.Collectors
@Order(ExternalSystemConstants.UNORDERED + 1)
open class KotlinMPPGradleProjectResolver : AbstractProjectResolverExtension() {
private val cacheManager = KotlinMPPCompilerArgumentsCacheMergeManager
override fun createModule(gradleModule: IdeaModule, projectDataNode: DataNode<ProjectData>): DataNode<ModuleData>? {
return super.createModule(gradleModule, projectDataNode)?.also {
cacheManager.mergeCache(gradleModule, resolverCtx)
initializeModuleData(gradleModule, it, projectDataNode, resolverCtx)
populateSourceSetInfos(gradleModule, it, resolverCtx)
}
}
override fun getToolingExtensionsClasses(): Set<Class<out Any>> {
return setOf(KotlinMPPGradleModelBuilder::class.java, KotlinTarget::class.java, Unit::class.java)
}
override fun getExtraProjectModelClasses(): Set<Class<out Any>> {
return setOf(KotlinMPPGradleModel::class.java, KotlinTarget::class.java)
}
override fun getExtraCommandLineArgs(): List<String> =
/**
* The Kotlin Gradle plugin might want to use this intransitive metadata configuration to tell the IDE, that specific
* dependencies shall not be passed on to dependsOn source sets. (e.g. some commonized libraries).
* By default, the Gradle plugin does not use this configuration and instead places the dependencies into a previously
* supported configuration.
* This will tell the Gradle plugin that this version of the IDE plugin does support importing this special configuraiton.
*/
listOf("-Pkotlin.mpp.enableIntransitiveMetadataConfiguration=true")
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
if (ExternalSystemApiUtil.find(ideModule, BuildScriptClasspathData.KEY) == null) {
val buildScriptClasspathData = buildClasspathData(gradleModule, resolverCtx)
ideModule.createChild(BuildScriptClasspathData.KEY, buildScriptClasspathData)
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
override fun populateModuleContentRoots(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
val mppModel = resolverCtx.getMppModel(gradleModule)
if (mppModel == null) {
return super.populateModuleContentRoots(gradleModule, ideModule)
} else {
if (!nativeDebugAdvertised && mppModel.kotlinNativeHome.isNotEmpty() && !SystemInfo.isWindows) {
nativeDebugAdvertised = true
suggestNativeDebug(resolverCtx.projectPath)
}
if (!kotlinJsInspectionPackAdvertised && mppModel.targets.any { it.platform == KotlinPlatform.JS }) {
kotlinJsInspectionPackAdvertised = true
suggestKotlinJsInspectionPackPlugin(resolverCtx.projectPath)
}
if (!resolverCtx.isResolveModulePerSourceSet && !KotlinPlatformUtils.isAndroidStudio && !PlatformUtils.isMobileIde() &&
!PlatformUtils.isAppCode()
) {
notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded(resolverCtx.projectPath)
resolverCtx.report(MessageEvent.Kind.WARNING, ResolveModulesPerSourceSetInMppBuildIssue())
}
}
populateContentRoots(gradleModule, ideModule, resolverCtx)
populateExternalSystemRunTasks(gradleModule, ideModule, resolverCtx)
}
override fun populateModuleCompileOutputSettings(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
if (resolverCtx.getExtraProject(gradleModule, KotlinMPPGradleModel::class.java) == null) {
super.populateModuleCompileOutputSettings(gradleModule, ideModule)
}
val mppModel = resolverCtx.getMppModel(gradleModule) ?: return
val ideaOutDir = File(ideModule.data.linkedExternalProjectPath, "out")
val projectDataNode = ideModule.getDataNode(ProjectKeys.PROJECT)!!
val moduleOutputsMap = projectDataNode.getUserData(MODULES_OUTPUTS)!!
val outputDirs = HashSet<String>()
getCompilations(gradleModule, mppModel, ideModule, resolverCtx)
.filterNot { (_, compilation) -> shouldDelegateToOtherPlugin(compilation) }
.forEach { (dataNode, compilation) ->
var gradleOutputMap = dataNode.getUserData(GradleProjectResolver.GRADLE_OUTPUTS)
if (gradleOutputMap == null) {
gradleOutputMap = MultiMap.create()
dataNode.putUserData(GradleProjectResolver.GRADLE_OUTPUTS, gradleOutputMap)
}
val moduleData = dataNode.data
with(compilation.output) {
effectiveClassesDir?.let {
moduleData.isInheritProjectCompileOutputPath = false
moduleData.setCompileOutputPath(compilation.sourceType, it.absolutePath)
for (gradleOutputDir in classesDirs) {
recordOutputDir(gradleOutputDir, it, compilation.sourceType, moduleData, moduleOutputsMap, gradleOutputMap)
}
}
resourcesDir?.let {
moduleData.setCompileOutputPath(compilation.resourceType, it.absolutePath)
recordOutputDir(it, it, compilation.resourceType, moduleData, moduleOutputsMap, gradleOutputMap)
}
}
dataNode.createChild(KotlinOutputPathsData.KEY, KotlinOutputPathsData(gradleOutputMap.copy()))
}
if (outputDirs.any { FileUtil.isAncestor(ideaOutDir, File(it), false) }) {
excludeOutDir(ideModule, ideaOutDir)
}
}
override fun populateModuleDependencies(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>, ideProject: DataNode<ProjectData>) {
val mppModel = resolverCtx.getExtraProject(gradleModule, KotlinMPPGradleModel::class.java)
if (mppModel == null) {
resolverCtx.getExtraProject(gradleModule, ExternalProject::class.java)?.sourceSets?.values?.forEach { sourceSet ->
sourceSet.dependencies.modifyDependenciesOnMppModules(ideProject, resolverCtx)
}
super.populateModuleDependencies(gradleModule, ideModule, ideProject) //TODO add dependencies on mpp module
}
populateModuleDependencies(gradleModule, ideProject, ideModule, resolverCtx)
}
private fun recordOutputDir(
gradleOutputDir: File,
effectiveOutputDir: File,
sourceType: ExternalSystemSourceType,
moduleData: GradleSourceSetData,
moduleOutputsMap: MutableMap<String, Pair<String, ExternalSystemSourceType>>,
gradleOutputMap: MultiMap<ExternalSystemSourceType, String>
) {
val gradleOutputPath = toCanonicalPath(gradleOutputDir.absolutePath)
gradleOutputMap.putValue(sourceType, gradleOutputPath)
if (gradleOutputDir.path != effectiveOutputDir.path) {
moduleOutputsMap[gradleOutputPath] = Pair(moduleData.id, sourceType)
}
}
private fun excludeOutDir(ideModule: DataNode<ModuleData>, ideaOutDir: File) {
val contentRootDataDataNode = ExternalSystemApiUtil.find(ideModule, ProjectKeys.CONTENT_ROOT)
val excludedContentRootData: ContentRootData
if (contentRootDataDataNode == null || !FileUtil.isAncestor(File(contentRootDataDataNode.data.rootPath), ideaOutDir, false)) {
excludedContentRootData = ContentRootData(GradleConstants.SYSTEM_ID, ideaOutDir.absolutePath)
ideModule.createChild(ProjectKeys.CONTENT_ROOT, excludedContentRootData)
} else {
excludedContentRootData = contentRootDataDataNode.data
}
excludedContentRootData.storePath(ExternalSystemSourceType.EXCLUDED, ideaOutDir.absolutePath)
}
companion object {
val MPP_CONFIGURATION_ARTIFACTS =
Key.create<MutableMap<String/* artifact path */, MutableList<String> /* module ids*/>>("gradleMPPArtifactsMap")
val proxyObjectCloningCache = WeakHashMap<Any, Any>()
//flag for avoid double resolve from KotlinMPPGradleProjectResolver and KotlinAndroidMPPGradleProjectResolver
private var DataNode<ModuleData>.isMppDataInitialized
by NotNullableCopyableDataNodeUserDataProperty(Key.create<Boolean>("IS_MPP_DATA_INITIALIZED"), false)
private var nativeDebugAdvertised = false
private var kotlinJsInspectionPackAdvertised = false
private fun ExternalDependency.getDependencyArtifacts(): Collection<File> =
when (this) {
is ExternalProjectDependency -> this.projectDependencyArtifacts
is FileCollectionDependency -> this.files
else -> emptyList()
}
private fun getOrCreateAffiliatedArtifactsMap(ideProject: DataNode<ProjectData>): Map<String, List<String>>? {
val mppArtifacts = ideProject.getUserData(MPP_CONFIGURATION_ARTIFACTS) ?: return null
val configArtifacts = ideProject.getUserData(CONFIGURATION_ARTIFACTS) ?: return null
// All MPP modules are already known, we can fill configurations map
return /*ideProject.getUserData(MPP_AFFILATED_ARTIFACTS) ?:*/ HashMap<String, MutableList<String>>().also { newMap ->
mppArtifacts.forEach { (filePath, moduleIds) ->
val list2add = ArrayList<String>()
newMap[filePath] = list2add
for ((index, module) in moduleIds.withIndex()) {
if (index == 0) {
configArtifacts[filePath] = module
} else {
val affiliatedFileName = "$filePath-MPP-$index"
configArtifacts[affiliatedFileName] = module
list2add.add(affiliatedFileName)
}
}
}
//ideProject.putUserData(MPP_AFFILATED_ARTIFACTS, newMap)
}
}
// TODO move?
internal fun Collection<ExternalDependency>.modifyDependenciesOnMppModules(
ideProject: DataNode<ProjectData>,
resolverCtx: ProjectResolverContext
) {
// Add mpp-artifacts into map used for dependency substitution
val affiliatedArtifacts = getOrCreateAffiliatedArtifactsMap(ideProject)
if (affiliatedArtifacts != null) {
this.forEach { dependency ->
val existingArtifactDependencies = dependency.getDependencyArtifacts().map { normalizePath(it.absolutePath) }
val dependencies2add = existingArtifactDependencies.flatMap { affiliatedArtifacts[it] ?: emptyList() }
.filter { !existingArtifactDependencies.contains(it) }
dependencies2add.forEach {
dependency.addDependencyArtifactInternal(File(it))
}
}
}
}
private fun ExternalDependency.addDependencyArtifactInternal(file: File) {
when (this) {
is DefaultExternalProjectDependency -> this.projectDependencyArtifacts =
ArrayList<File>(this.projectDependencyArtifacts).also {
it.add(file)
}
is ExternalProjectDependency -> try {
this.projectDependencyArtifacts.add(file)
} catch (_: Exception) {
// ignore
}
is FileCollectionDependency -> this.files.add(file)
}
}
private fun populateExternalSystemRunTasks(
gradleModule: IdeaModule,
mainModuleNode: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext
) {
val mppModel = resolverCtx.getMppModel(gradleModule) ?: return
val sourceSetToRunTasks = calculateRunTasks(mppModel, gradleModule, resolverCtx)
val allKotlinSourceSets =
ExternalSystemApiUtil.findAllRecursively(mainModuleNode, KotlinSourceSetData.KEY).mapNotNull { it?.data?.sourceSetInfo } +
ExternalSystemApiUtil.find(mainModuleNode, KotlinAndroidSourceSetData.KEY)?.data?.sourceSetInfos.orEmpty()
val allKotlinSourceSetsDataWithRunTasks = allKotlinSourceSets
.associateWith {
when (val component = it.kotlinComponent) {
is KotlinCompilation -> component
.declaredSourceSets
.firstNotNullOfOrNull { sourceSetToRunTasks[it] }
.orEmpty()
is KotlinSourceSet -> sourceSetToRunTasks[component]
.orEmpty()
//TODO(chernyshevj) KotlinComponent: interface -> sealed interface
else -> error("Unsupported KotlinComponent: $component")
}
}
allKotlinSourceSetsDataWithRunTasks.forEach { (sourceSetInfo, runTasks) -> sourceSetInfo.externalSystemRunTasks = runTasks }
}
private fun populateSourceSetInfos(
gradleModule: IdeaModule,
mainModuleNode: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext
) {
val mainModuleData = mainModuleNode.data
val mainModuleConfigPath = mainModuleData.linkedExternalProjectPath
val mainModuleFileDirectoryPath = mainModuleData.moduleFileDirectoryPath
val externalProject = resolverCtx.getExtraProject(gradleModule, ExternalProject::class.java) ?: return
val mppModel = resolverCtx.getMppModel(gradleModule) ?: return
val projectDataNode = ExternalSystemApiUtil.findParent(mainModuleNode, ProjectKeys.PROJECT) ?: return
val moduleGroup: Array<String>? = if (!resolverCtx.isUseQualifiedModuleNames) {
val gradlePath = gradleModule.gradleProject.path
val isRootModule = gradlePath.isEmpty() || gradlePath == ":"
if (isRootModule) {
arrayOf(mainModuleData.internalName)
} else {
gradlePath.split(":").drop(1).toTypedArray()
}
} else null
val sourceSetMap = projectDataNode.getUserData(GradleProjectResolver.RESOLVED_SOURCE_SETS)!!
val sourceSetToCompilationData = LinkedHashMap<String, MutableSet<GradleSourceSetData>>()
for (target in mppModel.targets) {
if (shouldDelegateToOtherPlugin(target)) continue
if (target.name == KotlinTarget.METADATA_TARGET_NAME) continue
val targetData = KotlinTargetData(target.name).also {
it.archiveFile = target.jar?.archiveFile
it.konanArtifacts = target.konanArtifacts
}
mainModuleNode.createChild(KotlinTargetData.KEY, targetData)
val compilationIds = LinkedHashSet<String>()
for (compilation in target.compilations) {
val moduleId = getKotlinModuleId(gradleModule, compilation, resolverCtx)
val existingSourceSetDataNode = sourceSetMap[moduleId]?.first
if (existingSourceSetDataNode?.kotlinSourceSetData?.sourceSetInfo != null) continue
compilationIds.add(moduleId)
val moduleExternalName = getExternalModuleName(gradleModule, compilation)
val moduleInternalName = getInternalModuleName(gradleModule, externalProject, compilation, resolverCtx)
val compilationData = existingSourceSetDataNode?.data ?: createGradleSourceSetData(
moduleId, moduleExternalName, moduleInternalName, mainModuleFileDirectoryPath, mainModuleConfigPath
).also {
it.group = externalProject.group
it.version = externalProject.version
when (compilation.name) {
KotlinCompilation.MAIN_COMPILATION_NAME -> {
it.publication = ProjectId(externalProject.group, externalProject.name, externalProject.version)
}
KotlinCompilation.TEST_COMPILATION_NAME -> {
it.productionModuleId = getInternalModuleName(
gradleModule,
externalProject,
compilation,
resolverCtx,
KotlinCompilation.MAIN_COMPILATION_NAME
)
}
}
it.ideModuleGroup = moduleGroup
it.sdkName = gradleModule.jdkNameIfAny
}
val kotlinSourceSet = createSourceSetInfo(
compilation,
gradleModule,
resolverCtx
) ?: continue
/*if (compilation.platform == KotlinPlatform.JVM || compilation.platform == KotlinPlatform.ANDROID) {
compilationData.targetCompatibility = (kotlinSourceSet.compilerArguments as? K2JVMCompilerArguments)?.jvmTarget
} else */if (compilation.platform == KotlinPlatform.NATIVE) {
// Kotlin/Native target has been added to KotlinNativeCompilation only in 1.3.60,
// so 'nativeExtensions' may be null in 1.3.5x or earlier versions
compilation.nativeExtensions?.konanTarget?.let { konanTarget ->
compilationData.konanTargets = setOf(konanTarget)
}
}
for (sourceSet in compilation.declaredSourceSets) {
sourceSetToCompilationData.getOrPut(sourceSet.name) { LinkedHashSet() } += compilationData
for (dependentSourceSetName in sourceSet.allDependsOnSourceSets) {
sourceSetToCompilationData.getOrPut(dependentSourceSetName) { LinkedHashSet() } += compilationData
}
}
val compilationDataNode =
(existingSourceSetDataNode ?: mainModuleNode.createChild(GradleSourceSetData.KEY, compilationData)).also {
it.addChild(DataNode(KotlinSourceSetData.KEY, KotlinSourceSetData(kotlinSourceSet), it))
}
if (existingSourceSetDataNode == null) {
sourceSetMap[moduleId] = Pair(compilationDataNode, createExternalSourceSet(compilation, compilationData, mppModel))
}
}
targetData.moduleIds = compilationIds
}
val ignoreCommonSourceSets by lazy { externalProject.notImportedCommonSourceSets() }
for (sourceSet in mppModel.sourceSetsByName.values) {
if (shouldDelegateToOtherPlugin(sourceSet)) continue
val platform = sourceSet.actualPlatforms.platforms.singleOrNull()
if (platform == KotlinPlatform.COMMON && ignoreCommonSourceSets) continue
val moduleId = getKotlinModuleId(gradleModule, sourceSet, resolverCtx)
val existingSourceSetDataNode = sourceSetMap[moduleId]?.first
if (existingSourceSetDataNode?.kotlinSourceSetData != null) continue
val sourceSetData = existingSourceSetDataNode?.data ?: createGradleSourceSetData(
sourceSet, gradleModule, mainModuleNode, resolverCtx
).also {
it.group = externalProject.group
it.version = externalProject.version
// TODO NOW: Use TestSourceSetUtil instead!
if (sourceSet.isTestComponent) {
it.productionModuleId = getInternalModuleName(
gradleModule,
externalProject,
sourceSet,
resolverCtx,
@OptIn(UnsafeTestSourceSetHeuristicApi::class)
predictedProductionSourceSetName(sourceSet.name)
)
} else {
if (platform == KotlinPlatform.COMMON) {
val artifacts = externalProject.artifactsByConfiguration["metadataApiElements"]?.toMutableList()
if (artifacts != null) {
it.artifacts = artifacts
}
}
}
it.ideModuleGroup = moduleGroup
sourceSetToCompilationData[sourceSet.name]?.let { compilationDataRecords ->
it.targetCompatibility = compilationDataRecords
.mapNotNull { compilationData -> compilationData.targetCompatibility }
.minWithOrNull(VersionComparatorUtil.COMPARATOR)
if (sourceSet.actualPlatforms.singleOrNull() == KotlinPlatform.NATIVE) {
it.konanTargets = compilationDataRecords
.flatMap { compilationData -> compilationData.konanTargets }
.toSet()
}
}
}
val kotlinSourceSet = createSourceSetInfo(mppModel, sourceSet, gradleModule, resolverCtx) ?: continue
val sourceSetDataNode =
(existingSourceSetDataNode ?: mainModuleNode.createChild(GradleSourceSetData.KEY, sourceSetData)).also {
it.addChild(DataNode(KotlinSourceSetData.KEY, KotlinSourceSetData(kotlinSourceSet), it))
}
if (existingSourceSetDataNode == null) {
sourceSetMap[moduleId] = Pair(sourceSetDataNode, createExternalSourceSet(sourceSet, sourceSetData, mppModel))
}
}
}
private fun createGradleSourceSetData(
sourceSet: KotlinSourceSet,
gradleModule: IdeaModule,
mainModuleNode: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext,
): GradleSourceSetData {
val moduleId = getKotlinModuleId(gradleModule, sourceSet, resolverCtx)
val moduleExternalName = getExternalModuleName(gradleModule, sourceSet)
val moduleInternalName = mainModuleNode.data.internalName + "." + sourceSet.fullName()
val moduleFileDirectoryPath = mainModuleNode.data.moduleFileDirectoryPath
val linkedExternalProjectPath = mainModuleNode.data.linkedExternalProjectPath
return GradleSourceSetData(moduleId, moduleExternalName, moduleInternalName, moduleFileDirectoryPath, linkedExternalProjectPath)
}
private fun createGradleSourceSetData(
moduleId: String,
moduleExternalName: String,
moduleInternalName: String,
mainModuleFileDirectoryPath: String,
mainModuleConfigPath: String
) = GradleSourceSetData(
moduleId, moduleExternalName, moduleInternalName, mainModuleFileDirectoryPath, mainModuleConfigPath
)
private fun initializeModuleData(
gradleModule: IdeaModule,
mainModuleNode: DataNode<ModuleData>,
projectDataNode: DataNode<ProjectData>,
resolverCtx: ProjectResolverContext
) {
if (mainModuleNode.isMppDataInitialized) return
val mainModuleData = mainModuleNode.data
val externalProject = resolverCtx.getExtraProject(gradleModule, ExternalProject::class.java)
val mppModel = resolverCtx.getMppModel(gradleModule)
if (mppModel == null || externalProject == null) return
mainModuleNode.isMppDataInitialized = true
// save artifacts locations.
val userData = projectDataNode.getUserData(MPP_CONFIGURATION_ARTIFACTS) ?: HashMap<String, MutableList<String>>().apply {
projectDataNode.putUserData(MPP_CONFIGURATION_ARTIFACTS, this)
}
mppModel.targets.filter { it.jar != null && it.jar!!.archiveFile != null }.forEach { target ->
val path = toCanonicalPath(target.jar!!.archiveFile!!.absolutePath)
val currentModules = userData[path] ?: ArrayList<String>().apply { userData[path] = this }
// Test modules should not be added. Otherwise we could get dependnecy of java.mail on jvmTest
val allSourceSets = target.compilations.filter { !it.isTestComponent }.flatMap { it.declaredSourceSets }.toSet()
val availableViaDependsOn = allSourceSets.flatMap { it.allDependsOnSourceSets }.mapNotNull { mppModel.sourceSetsByName[it] }
allSourceSets.union(availableViaDependsOn).forEach { sourceSet ->
currentModules.add(getKotlinModuleId(gradleModule, sourceSet, resolverCtx))
}
}
with(projectDataNode.data) {
if (mainModuleData.linkedExternalProjectPath == linkedExternalProjectPath) {
group = mainModuleData.group
version = mainModuleData.version
}
}
KotlinGradleProjectData().apply {
kotlinNativeHome = mppModel.kotlinNativeHome
coroutines = mppModel.extraFeatures.coroutinesState
isHmpp = mppModel.extraFeatures.isHMPPEnabled
kotlinImportingDiagnosticsContainer = mppModel.kotlinImportingDiagnostics
mainModuleNode.createChild(KotlinGradleProjectData.KEY, this)
}
//TODO improve passing version of used multiplatform
}
fun populateContentRoots(
gradleModule: IdeaModule,
ideModule: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext
) {
val mppModel = resolverCtx.getMppModel(gradleModule) ?: return
val sourceSetToPackagePrefix = mppModel.targets.flatMap { it.compilations }
.flatMap { compilation ->
compilation.declaredSourceSets.map { sourceSet -> sourceSet.name to compilation.kotlinTaskProperties.packagePrefix }
}
.toMap()
if (resolverCtx.getExtraProject(gradleModule, ExternalProject::class.java) == null) return
processSourceSets(gradleModule, mppModel, ideModule, resolverCtx) { dataNode, sourceSet ->
if (dataNode == null || shouldDelegateToOtherPlugin(sourceSet)) return@processSourceSets
createContentRootData(
sourceSet.sourceDirs,
sourceSet.sourceType,
sourceSetToPackagePrefix[sourceSet.name],
dataNode
)
createContentRootData(
sourceSet.resourceDirs,
sourceSet.resourceType,
null,
dataNode
)
}
for (gradleContentRoot in gradleModule.contentRoots ?: emptySet<IdeaContentRoot?>()) {
if (gradleContentRoot == null) continue
val rootDirectory = gradleContentRoot.rootDirectory ?: continue
val ideContentRoot = ContentRootData(GradleConstants.SYSTEM_ID, rootDirectory.absolutePath).also { ideContentRoot ->
(gradleContentRoot.excludeDirectories ?: emptySet()).forEach { file ->
ideContentRoot.storePath(ExternalSystemSourceType.EXCLUDED, file.absolutePath)
}
}
ideModule.createChild(ProjectKeys.CONTENT_ROOT, ideContentRoot)
}
val mppModelPureKotlinSourceFolders = mppModel.targets.flatMap { it.compilations }
.flatMap { it.kotlinTaskProperties.pureKotlinSourceFolders ?: emptyList() }
.map { it.absolutePath }
ideModule.kotlinGradleProjectDataOrFail.pureKotlinSourceFolders.addAll(mppModelPureKotlinSourceFolders)
}
internal data class CompilationWithDependencies(
val compilation: KotlinCompilation,
val substitutedDependencies: List<ExternalDependency>
) {
private val konanTarget: String?
get() = compilation.nativeExtensions?.konanTarget
val dependencyNames: Map<String, ExternalDependency> by lazy {
substitutedDependencies.associateBy { it.name.removeSuffixIfPresent(" | $konanTarget") }
}
}
fun populateModuleDependencies(
gradleModule: IdeaModule,
ideProject: DataNode<ProjectData>,
ideModule: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext
) {
val context = createKotlinMppPopulateModuleDependenciesContext(
gradleModule = gradleModule,
ideProject = ideProject,
ideModule = ideModule,
resolverCtx = resolverCtx
) ?: return
populateModuleDependenciesByCompilations(context)
populateModuleDependenciesByPlatformPropagation(context)
populateModuleDependenciesBySourceSetVisibilityGraph(context)
}
internal fun getSiblingKotlinModuleData(
kotlinComponent: KotlinComponent,
gradleModule: IdeaModule,
ideModule: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext
): DataNode<out ModuleData>? {
val usedModuleId = getKotlinModuleId(gradleModule, kotlinComponent, resolverCtx)
return ideModule.findChildModuleById(usedModuleId)
}
private fun createContentRootData(
sourceDirs: Set<File>,
sourceType: ExternalSystemSourceType,
packagePrefix: String?,
parentNode: DataNode<*>
) {
for (sourceDir in sourceDirs) {
val contentRootData = ContentRootData(GradleConstants.SYSTEM_ID, sourceDir.absolutePath)
contentRootData.storePath(sourceType, sourceDir.absolutePath, packagePrefix)
parentNode.createChild(ProjectKeys.CONTENT_ROOT, contentRootData)
}
}
private fun processSourceSets(
gradleModule: IdeaModule,
mppModel: KotlinMPPGradleModel,
ideModule: DataNode<ModuleData>,
resolverCtx: ProjectResolverContext,
processor: (DataNode<GradleSourceSetData>?, KotlinSourceSet) -> Unit
) {
val sourceSetsMap = HashMap<String, DataNode<GradleSourceSetData>>()
for (dataNode in ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY)) {
if (dataNode.kotlinSourceSetData?.sourceSetInfo != null) {
sourceSetsMap[dataNode.data.id] = dataNode
}
}
for (sourceSet in mppModel.sourceSetsByName.values) {
val moduleId = getKotlinModuleId(gradleModule, sourceSet, resolverCtx)
val moduleDataNode = sourceSetsMap[moduleId]
processor(moduleDataNode, sourceSet)
}
}
private val IdeaModule.jdkNameIfAny
get() = try {
jdkName
} catch (e: UnsupportedMethodException) {
null
}
private fun getExternalModuleName(gradleModule: IdeaModule, kotlinComponent: KotlinComponent) =
gradleModule.name + ":" + kotlinComponent.fullName()
private fun gradlePathToQualifiedName(
rootName: String,
gradlePath: String
): String? {
return ((if (gradlePath.startsWith(":")) "$rootName." else "")
+ Arrays.stream(gradlePath.split(":".toRegex()).toTypedArray())
.filter { s: String -> s.isNotEmpty() }
.collect(Collectors.joining(".")))
}
private fun getInternalModuleName(
gradleModule: IdeaModule,
externalProject: ExternalProject,
kotlinComponent: KotlinComponent,
resolverCtx: ProjectResolverContext,
actualName: String = kotlinComponent.name
): String {
val delimiter: String
val moduleName = StringBuilder()
val buildSrcGroup = resolverCtx.buildSrcGroup
if (resolverCtx.isUseQualifiedModuleNames) {
delimiter = "."
if (StringUtil.isNotEmpty(buildSrcGroup)) {
moduleName.append(buildSrcGroup).append(delimiter)
}
moduleName.append(
gradlePathToQualifiedName(
gradleModule.project.name,
externalProject.qName
)
)
} else {
delimiter = "_"
if (StringUtil.isNotEmpty(buildSrcGroup)) {
moduleName.append(buildSrcGroup).append(delimiter)
}
moduleName.append(gradleModule.name)
}
moduleName.append(delimiter)
moduleName.append(kotlinComponent.fullName(actualName))
return PathUtilRt.suggestFileName(moduleName.toString(), true, false)
}
private fun createExternalSourceSet(
compilation: KotlinCompilation,
compilationData: GradleSourceSetData,
mppModel: KotlinMPPGradleModel
): ExternalSourceSet {
return DefaultExternalSourceSet().also { sourceSet ->
val effectiveClassesDir = compilation.output.effectiveClassesDir
val resourcesDir = compilation.output.resourcesDir
sourceSet.name = compilation.fullName()
sourceSet.targetCompatibility = compilationData.targetCompatibility
sourceSet.dependencies += compilation.dependencies.mapNotNull { mppModel.dependencyMap[it] }
//TODO after applying patch to IDEA core uncomment the following line:
// sourceSet.isTest = compilation.sourceSets.filter { isTestModule }.isNotEmpty()
// It will allow to get rid of hacks with guessing module type in DataServices and obtain properly set productionOnTest flags
val sourcesWithTypes = SmartList<kotlin.Pair<ExternalSystemSourceType, DefaultExternalSourceDirectorySet>>()
if (effectiveClassesDir != null) {
sourcesWithTypes += compilation.sourceType to DefaultExternalSourceDirectorySet().also { dirSet ->
dirSet.outputDir = effectiveClassesDir
dirSet.srcDirs = compilation.declaredSourceSets.flatMapTo(LinkedHashSet()) { it.sourceDirs }
dirSet.gradleOutputDirs += compilation.output.classesDirs
dirSet.setInheritedCompilerOutput(false)
}
}
if (resourcesDir != null) {
sourcesWithTypes += compilation.resourceType to DefaultExternalSourceDirectorySet().also { dirSet ->
dirSet.outputDir = resourcesDir
dirSet.srcDirs = compilation.declaredSourceSets.flatMapTo(LinkedHashSet()) { it.resourceDirs }
dirSet.gradleOutputDirs += resourcesDir
dirSet.setInheritedCompilerOutput(false)
}
}
sourceSet.setSources(sourcesWithTypes.toMap())
}
}
private fun createExternalSourceSet(
ktSourceSet: KotlinSourceSet,
ktSourceSetData: GradleSourceSetData,
mppModel: KotlinMPPGradleModel
): ExternalSourceSet {
return DefaultExternalSourceSet().also { sourceSet ->
sourceSet.name = ktSourceSet.name
sourceSet.targetCompatibility = ktSourceSetData.targetCompatibility
sourceSet.dependencies += ktSourceSet.dependencies.mapNotNull { mppModel.dependencyMap[it] }
sourceSet.setSources(linkedMapOf(
ktSourceSet.sourceType to DefaultExternalSourceDirectorySet().also { dirSet ->
dirSet.srcDirs = ktSourceSet.sourceDirs
},
ktSourceSet.resourceType to DefaultExternalSourceDirectorySet().also { dirSet ->
dirSet.srcDirs = ktSourceSet.resourceDirs
}
).toMap())
}
}
val KotlinComponent.sourceType
get() = if (isTestComponent) ExternalSystemSourceType.TEST else ExternalSystemSourceType.SOURCE
val KotlinComponent.resourceType
get() = if (isTestComponent) ExternalSystemSourceType.TEST_RESOURCE else ExternalSystemSourceType.RESOURCE
@OptIn(ExperimentalGradleToolingApi::class)
fun createSourceSetInfo(
mppModel: KotlinMPPGradleModel,
sourceSet: KotlinSourceSet,
gradleModule: IdeaModule,
resolverCtx: ProjectResolverContext
): KotlinSourceSetInfo? {
if (sourceSet.actualPlatforms.platforms.none { !it.isNotSupported() }) return null
return KotlinSourceSetInfo(sourceSet).also { info ->
val languageSettings = sourceSet.languageSettings
info.moduleId = getKotlinModuleId(gradleModule, sourceSet, resolverCtx)
info.gradleModuleId = getModuleId(resolverCtx, gradleModule)
info.actualPlatforms.pushPlatforms(sourceSet.actualPlatforms)
info.isTestModule = sourceSet.isTestComponent
info.dependsOn = mppModel.resolveAllDependsOnSourceSets(sourceSet).map { dependsOnSourceSet ->
getGradleModuleQualifiedName(resolverCtx, gradleModule, dependsOnSourceSet.name)
}
info.additionalVisible = sourceSet.additionalVisibleSourceSets.map { additionalVisibleSourceSetName ->
getGradleModuleQualifiedName(resolverCtx, gradleModule, additionalVisibleSourceSetName)
}.toSet()
// More precise computation of KotlinPlatform is required in the case of projects
// with enabled HMPP and Android + JVM targets.
// Early, for common source set in such project the K2MetadataCompilerArguments instance
// was creating, since `sourceSet.actualPlatforms.platforms` contains more then 1 KotlinPlatform.
val platformKinds = sourceSet.actualPlatforms.platforms
.map { IdePlatformKindTooling.getTooling(it).kind }
.toSet()
val compilerArgumentsPlatform = platformKinds.singleOrNull()?.let {
when (it) {
is JvmIdePlatformKind -> KotlinPlatform.JVM
is JsIdePlatformKind -> KotlinPlatform.JS
is NativeIdePlatformKind -> KotlinPlatform.NATIVE
else -> KotlinPlatform.COMMON
}
} ?: KotlinPlatform.COMMON
info.lazyCompilerArguments = lazy {
createCompilerArguments(emptyList(), compilerArgumentsPlatform).also {
it.multiPlatform = true
it.languageVersion = languageSettings.languageVersion
it.apiVersion = languageSettings.apiVersion
it.progressiveMode = languageSettings.isProgressiveMode
it.internalArguments = languageSettings.enabledLanguageFeatures.mapNotNull {
val feature = LanguageFeature.fromString(it) ?: return@mapNotNull null
val arg = "-XXLanguage:+$it"
ManualLanguageFeatureSetting(feature, LanguageFeature.State.ENABLED, arg)
}
it.optIn = languageSettings.optInAnnotationsInUse.toTypedArray()
it.pluginOptions = languageSettings.compilerPluginArguments
it.pluginClasspaths = languageSettings.compilerPluginClasspath.map(File::getPath).toTypedArray()
it.freeArgs = languageSettings.freeCompilerArgs.toMutableList()
}
}
}
}
@Suppress("DEPRECATION_ERROR")
// TODO: Unite with other createSourceSetInfo
// This method is used in Android side of import and it's signature could not be changed
fun createSourceSetInfo(
compilation: KotlinCompilation,
gradleModule: IdeaModule,
resolverCtx: ProjectResolverContext
): KotlinSourceSetInfo? {
if (compilation.platform.isNotSupported()) return null
if (Proxy.isProxyClass(compilation.javaClass)) {
return createSourceSetInfo(
KotlinCompilationImpl(compilation, HashMap<Any, Any>()),
gradleModule,
resolverCtx
)
}
val cacheHolder = CompilerArgumentsCacheMergeManager.compilerArgumentsCacheHolder
return KotlinSourceSetInfo(compilation).also { sourceSetInfo ->
sourceSetInfo.moduleId = getKotlinModuleId(gradleModule, compilation, resolverCtx)
sourceSetInfo.gradleModuleId = getModuleId(resolverCtx, gradleModule)
sourceSetInfo.actualPlatforms.pushPlatforms(compilation.platform)
sourceSetInfo.isTestModule = compilation.isTestComponent
sourceSetInfo.dependsOn = compilation.declaredSourceSets.flatMap { it.allDependsOnSourceSets }.map {
getGradleModuleQualifiedName(resolverCtx, gradleModule, it)
}.distinct().toList()
sourceSetInfo.additionalVisible = sourceSetInfo.additionalVisible.map {
getGradleModuleQualifiedName(resolverCtx, gradleModule, it)
}.toSet()
when (val cachedArgsInfo = compilation.cachedArgsInfo) {
is CachedExtractedArgsInfo -> {
val restoredArgs = lazy { CachedArgumentsRestoring.restoreExtractedArgs(cachedArgsInfo, cacheHolder) }
sourceSetInfo.lazyCompilerArguments = lazy { restoredArgs.value.currentCompilerArguments }
sourceSetInfo.lazyDefaultCompilerArguments = lazy { restoredArgs.value.defaultCompilerArguments }
sourceSetInfo.lazyDependencyClasspath =
lazy { restoredArgs.value.dependencyClasspath.map { PathUtil.toSystemIndependentName(it) } }
}
is CachedSerializedArgsInfo -> {
val restoredArgs =
lazy { CachedArgumentsRestoring.restoreSerializedArgsInfo(cachedArgsInfo, cacheHolder) }
sourceSetInfo.lazyCompilerArguments = lazy {
createCompilerArguments(restoredArgs.value.currentCompilerArguments.toList(), compilation.platform).also {
it.multiPlatform = true
}
}
sourceSetInfo.lazyDefaultCompilerArguments = lazy {
createCompilerArguments(restoredArgs.value.defaultCompilerArguments.toList(), compilation.platform)
}
sourceSetInfo.lazyDependencyClasspath = lazy {
restoredArgs.value.dependencyClasspath.map { PathUtil.toSystemIndependentName(it) }
}
}
}
sourceSetInfo.addSourceSets(compilation.allSourceSets, compilation.fullName(), gradleModule, resolverCtx)
}
}
/** Checks if our IDE doesn't support such platform */
private fun KotlinPlatform.isNotSupported() = IdePlatformKindTooling.getToolingIfAny(this) == null
private fun KotlinSourceSetInfo.addSourceSets(
sourceSets: Collection<KotlinComponent>,
selfName: String,
gradleModule: IdeaModule,
resolverCtx: ProjectResolverContext
) {
sourceSets
.asSequence()
.filter { it.fullName() != selfName }
.forEach { sourceSetIdsByName[it.name] = getKotlinModuleId(gradleModule, it, resolverCtx) }
}
private fun createCompilerArguments(args: List<String>, platform: KotlinPlatform): CommonCompilerArguments {
val compilerArguments = IdePlatformKindTooling.getTooling(platform).kind.argumentsClass.newInstance()
parseCommandLineArguments(args.toList(), compilerArguments)
return compilerArguments
}
private fun ExternalProject.notImportedCommonSourceSets() =
GradlePropertiesFileFacade.forExternalProject(this).readProperty(KOTLIN_NOT_IMPORTED_COMMON_SOURCE_SETS_SETTING)?.equals(
"true",
ignoreCase = true
) ?: false
internal fun shouldDelegateToOtherPlugin(compilation: KotlinCompilation): Boolean =
compilation.platform == KotlinPlatform.ANDROID
private fun shouldDelegateToOtherPlugin(kotlinTarget: KotlinTarget): Boolean =
kotlinTarget.platform == KotlinPlatform.ANDROID
internal fun shouldDelegateToOtherPlugin(kotlinSourceSet: KotlinSourceSet): Boolean =
kotlinSourceSet.actualPlatforms.platforms.singleOrNull() == KotlinPlatform.ANDROID
}
}
fun ProjectResolverContext.getMppModel(gradleModule: IdeaModule): KotlinMPPGradleModel? {
val mppModel = this.getExtraProject(gradleModule, KotlinMPPGradleModel::class.java)
return if (mppModel is Proxy) {
this.getExtraProject(gradleModule, KotlinMPPGradleModel::class.java)
?.let { kotlinMppModel ->
KotlinMPPGradleProjectResolver.proxyObjectCloningCache[kotlinMppModel] as? KotlinMPPGradleModelImpl
?: KotlinMPPGradleModelImpl(
kotlinMppModel,
KotlinMPPGradleProjectResolver.proxyObjectCloningCache
).also {
KotlinMPPGradleProjectResolver.proxyObjectCloningCache[kotlinMppModel] = it
}
}
} else {
mppModel
}
}
| apache-2.0 | 2e27c37e067cfb3599a5de8d1b62d720 | 52.015337 | 158 | 0.638161 | 6.300766 | false | false | false | false |
lucasgomes-eti/KotlinAndroidProjects | MyContacts/app/src/main/java/com/lucas/mycontacts/model/Resource.kt | 1 | 1427 | package com.lucas.mycontacts.model
/**
* Created by lucas on 14/11/2017.
*/
class Resource<T>(val status : Status, val data: T?, val message: String?
) {
override fun equals(other: Any?): Boolean {
if (this == other) {
return true
}
val resource = other as Resource<*>?
if (status != resource!!.status) {
return false
}
if (if (message != null) message != resource.message else resource.message != null) {
return false
}
return if (data != null) data == resource.data else resource.data == null
}
override fun hashCode(): Int {
var result = status.hashCode()
result = 31 * result + (message?.hashCode() ?: 0)
result = 31 * result + (data?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "Resource{" +
"status=" + status +
", message='" + message + '\'' +
", data=" + data +
'}'
}
companion object {
fun <T> success(data: T?): Resource<T> {
return Resource(Status.SUCCESS, data, null)
}
fun <T> error(msg: String, data: T?): Resource<T> {
return Resource(Status.ERROR, data, msg)
}
fun <T> loading(data: T?): Resource<T> {
return Resource(Status.LOADING, data, null)
}
}
} | cc0-1.0 | 82dec3cceb16c21b5008170ca10d1ba5 | 26.461538 | 93 | 0.510161 | 4.221893 | false | false | false | false |
vovagrechka/fucking-everything | attic/alraune/alraune-back-kotlin-2/src/AlMads.kt | 1 | 31823 | @file:Suppress("unused")
package alraune.back
import org.junit.Assert
import org.junit.Test
import vgrechka.*
import java.io.File
import java.util.*
// TODO:vgrechka last_ for file params
object AlMads {
var entropy = 10
@JvmStatic
fun main(args: Array<String>) {
val what = args[0]
clog("what = $what")
AlGlobal.initTest1()
AlGlobal.standaloneToolMode = true
AlRequestContext.threadLocal.set(AlRequestContext())
Al.rctx().traceItems.addLast(TraceItem(object: Renderable {
override fun render() = bitch()
}))
AlRequestContext.get().useConnection {
this::class.java.getMethod(what).invoke(this)
}
clog("\nOK")
}
fun recreateSchema() {
val commonColumns = """
id bigserial primary key,
createdAt timestamp not null,
updatedAt timestamp not null,
deleted boolean not null
"""
AlDB.execute("""
drop table if exists ua_order_files;
drop table if exists ua_orders;
drop table if exists user_sessions;
drop table if exists users;
drop table if exists operations;
drop table if exists bytes;
create table users (
id bigserial primary key,
createdAt timestamp not null,
updatedAt timestamp not null,
deleted boolean not null,
state text not null,
firstName text not null,
lastName text not null,
email text not null,
passwordHash text not null,
profilePhone text not null,
kind text not null,
adminNotes text not null,
profileUpdatedAt timestamp,
aboutMe text not null,
profileRejectionReason text,
wasProfileRejectionReason text,
banReason text,
writerSubscriptions jsonb
);
create table user_sessions (
$commonColumns,
uuid text not null,
userID bigint,
foreign key (userID) references users (id)
);
create index on user_sessions (userID);
create unique index on user_sessions (uuid);
create table ua_orders (
id bigserial primary key,
uuid text not null,
createdAt timestamp not null,
updatedAt timestamp not null,
deleted boolean not null,
state text not null,
email text not null,
contactName text not null,
phone text not null,
documentType text not null,
documentTitle text not null,
documentDetails text not null,
documentCategory text not null,
numPages integer not null,
numSources integer not null,
adminNotes text not null,
rejectionReason text not null,
wasRejectionReason text not null
);
create unique index on ua_orders (uuid);
create table operations (
id bigserial primary key,
dataInterpreter text not null,
data jsonb not null
);
""")
AlDB.execute("""
create table bytes (
id bigserial primary key,
storageKind text not null,
filePath text
);
create table ua_order_files (
id bigserial primary key,
uuid text not null,
orderID bigint not null references ua_orders (id),
createdAt timestamp not null,
updatedAt timestamp not null,
deleted boolean not null,
state text not null,
name text not null,
size integer not null,
title text not null,
details text not null,
bytesID bigint not null references bytes (id)
);
create index on ua_order_files (orderID);
create unique index on ua_order_files (uuid);
""")
}
// fun mad102_something() {
// recreateSchema()
// }
fun mad101_something() {
recreateSchema()
AlGlobal.queryLoggingEnabled = false
AlDB.tx {
run { // Users
val dasja = makeDasja()
// dasja.operation = AlOperationData_Rudimentary_V1(AlBasicOperationData_V1.make("Creating dasja")).toOperation()
AlDB.insertEntity(dasja)
AlDB.insert(AlParams_insertOrUpdate.ofEntity(
AlUserSession_Builder.begin()
.uuid("ade3ac8c-3a2c-4222-976f-998fd755db40")
.userID(dasja.id).end()))
}
// run { // Orders
// run {
// val op1 = AlUAOrder_Params_Operation(
// AlUAOrder_Builder.begin()
// .uuid(null ?: "a488ab2e-ed3c-490d-816e-0c6849aed89c")
// .version(1).end(),
// AlUAOrderParams_Builder.begin()
// .state(AlUAOrderState.CustomerDraft)
// .email("[email protected]")
// .contactName("Иммануил Пердондэ")
// .phone("+38 (068) 4542823")
// .documentType(AlUADocumentType.Practice)
// .documentTitle("Как я пинал хуи на практике")
// .documentDetails("Детали? Я ебу, какие там детали...")
// .documentCategory(AlUADocumentCategories.programmingID)
// .numPages(35)
// .numSources(7)
// .adminNotes("")
// .rejectionReason("")
// .wasRejectionReason("")
// .end(),
// AlOperationData_Rudimentary_V1(AlBasicOperationData_V1.make("Fucking describe me 0cf35fc0-66f7-4839-81e6-03148483fc0a")).toOperation())
// AlDB.insertEntityPO(op1)
// addPlentyOfFiles1(op1.entity)
// }
//
// generateBunchOfLousyOrders()
// }
}
}
// private fun generateBunchOfLousyOrders() {
// val random = Random(45354738)
//// val amount = 100003
//// val amount = 1023
// val amount = 123
//// val amount = 23
// for (index in 1..amount) {
// if (index % 1000 == 0)
// clog("index = $index")
//
// val entropy = nextEntropy()
// val order = AlUAOrder_Builder.begin()
// .uuid("$index--92b8b09a-e928-4bff-9716-33f4ee1526ec")
// .version(1).end()
//
// val states = listOf(AlUAOrderState.WaitingAdminApproval,
// AlUAOrderState.CustomerDraft,
// AlUAOrderState.ReturnedToCustomerForFixing)
// val contactName = FakeShit.bunchOfNames[random.nextInt(FakeShit.bunchOfNames.size)]
// val state = states[random.nextInt(states.size)]
// val params = AlUAOrderParams_Builder.begin()
// .state(state)
// .email(FakeShit.nameToEmail(contactName))
// .contactName(contactName)
// .phone(FakeShit.randomPhone(random))
// .documentType(AlUADocumentType.values()[random.nextInt(AlUADocumentType.values().size)])
// .documentTitle("Йобаное задание $entropy")
// .documentDetails("($entropy) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." +
// "\n Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?")
// .documentCategory(AlUADocumentCategories.idsForTests[random.nextInt(AlUADocumentCategories.idsForTests.size)])
// .numPages(10 + random.nextInt(300))
// .numSources(2 + random.nextInt(20))
// .adminNotes("")
// .rejectionReason(when {
// state == AlUAOrderState.ReturnedToCustomerForFixing -> "От пидаров заказы не принимаем"
// else -> ""
// })
// .wasRejectionReason("")
// .end()
// val operation = AlOperationData_Rudimentary_V1(AlBasicOperationData_V1.make("Describe me dab3f68f-1bd3-4e39-9a63-5eec844b8d93")).toOperation()
// AlDB.insertEntityPO(AlUAOrder_Params_Operation(order, params, operation))
// addFile10(order, "$index--f086a8b2-b2ba-43c7-9fd6-25f68310f6ce")
//
// val bytes = AlBytes_Builder.begin()
// .storageKind(AlStorageKind.FileSystem)
// .filePath(fuckingShitContentPath).end()
// AlDB.insert(AlParams_insertOrUpdate.ofEntity(bytes))
// val fuckingParams = AlUAOrderFileParams_Builder.begin()
// .state(AlUAOrderFileState.UNKNOWN)
// .name("fucking-shit-$index.rtf")
// .size(Math.toIntExact(File(fuckingContent10Path).length()))
// .title("The Fucking Shit $index")
// .details("The gory details $index")
// .bytesID(bytes.id)
// .end()
// val fp = AlUAOrderFileWithParams(
// AlUAOrderFile_Builder.begin()
// .uuid("$index--bbfbdfdb-50e1-40d4-833a-be170c8ea925")
// .orderID(order.id)
// .end(),
// fuckingParams,
// AlOperationData_Rudimentary_V1(AlBasicOperationData_V1.make("Describe me 91ae2ec3-aaba-410a-9811-47cd30c94add")).toOperation())
// AlDB.insertOrderFile(fp)
//
// addFile10(order, "$index--6d4bbef9-fd86-4577-8d2a-a9363ce2a9b3")
//
// fuckingParams.also {
// it.title = "The Big Fucking Shit $index"
// it.details = "The little gory details $index"
// }
//
// addFile10(order, "$index--76c9ab1c-d066-4698-a039-f7ea903d0273")
// }
// }
// private fun createOrderWaitingApproval20(uuid: String) =
// createOrder10(uuid, AlUAOrderState.WaitingAdminApproval, AlUADocumentType.Lab, AlUADocumentCategories.programmingID)
// private fun createOrder10(uuid: String, state: AlUAOrderState, type: AlUADocumentType, category: String): AlUAOrder {
// val entropy = nextEntropy()
// val random = Random(entropy.toLong())
// val order = AlUAOrder_Builder.begin()
// .uuid(uuid)
// .version(1)
// .end()
// val params = AlUAOrderParams_Builder.begin()
// .state(state)
// .email("[email protected]")
// .contactName("Мудила $entropy")
// .phone("+38 (068) $entropy-6553943")
// .documentType(type)
// .documentTitle("Йобаное задание $entropy")
// .documentDetails(" ($entropy) Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." +
// "\n Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?")
// .documentCategory(category)
// .numPages(10 + random.nextInt(300))
// .numSources(2 + random.nextInt(20))
// .adminNotes("")
// .rejectionReason("")
// .wasRejectionReason("")
// .end()
// val operation = AlOperationData_Rudimentary_V1(AlBasicOperationData_V1.make("Describe me fea13a74-1f0e-4fe9-b67f-cdf99fc67f6c")).toOperation()
// AlDB.insertEntityPO(AlUAOrder_Params_Operation(order, params, operation))
// return order
// }
fun nextEntropy(): Int {
val res = entropy
entropy += 10
return res
}
val fuckingShitContentPath = AlBackPile0.testContentRoot + "/fucking-shit.rtf"
val fuckingContent10Path = AlBackPile0.testContentRoot + "/Женщина в песках.rtf"
// private fun addFile10(order: AlUAOrder, uuid: String, operationDescription: String? = null) {
// val entropy = nextEntropy()
// val bytes = AlBytes_Builder.begin()
// .storageKind(AlStorageKind.FileSystem)
// .filePath(fuckingContent10Path).end()
// AlDB.insert(AlParams_insertOrUpdate.ofEntity(bytes))
// AlDB.insertOrderFile(AlUAOrderFileWithParams(
// AlUAOrderFile_Builder.begin()
// .uuid(uuid)
// .orderID(order.id).end(),
// AlUAOrderFileParams_Builder.begin()
// .state(AlUAOrderFileState.UNKNOWN)
// .name("($entropy) Женщина в песках.rtf")
// .size(Math.toIntExact(File(fuckingContent10Path).length()))
// .title("($entropy) Абэ Кобо. Женщина в песках")
// .details(" В один из августовских дней пропал человек. Он решил использовать свой отпуск для поездки на побережье, до которого поездом было полдня пути, и с тех пор о нем ничего не слышали. Ни розыски полиции, ни объявления в газетах не дали никаких результатов.\n" +
// " Исчезновение людей - явление, в общем, не такое уж и редкое. Согласно статистике, ежегодно публикуется несколько сот сообщений о пропавших без вести. И, как ни странно, процент найденных весьма невелик. Убийства и несчастные случаи оставляют улики; когда случаются похищения, мотивы их можно установить. Но если исчезновение имеет какую-то другую причину, напасть на след пропавшего очень трудно. Правда, стоит назвать исчезновение побегом, как сразу же очень многие из них можно будет, видимо, причислить к этим самым обыкновенным побегам. ")
// .bytesID(bytes.id).end(),
// AlOperationData_Rudimentary_V1(AlBasicOperationData_V1.make(operationDescription)).toOperation()))
// }
internal fun makeDasja(): AlUser {
return AlUser_Builder.begin()
.state(AlUserState.Cool)
.firstName("Дася")
.lastName("Админовна")
.email("[email protected]")
.passwordHash(Al.hashPassword("dasja-secret"))
.profilePhone("123-456")
.kind(AlUserKind.Admin)
.adminNotes("")
.profileUpdatedAt(null)
.aboutMe("I am the mighty admin. I fucking ban everyone!")
.profileRejectionReason(null)
.wasProfileRejectionReason("")
.banReason(null)
.writerSubscriptions(null)
.end()
}
// internal fun addPlentyOfFiles1(order: AlUAOrder) {
// for (i in 1..23) {
// val file = File(AlBackPile0.testContentRoot + "/lbxproxy-$i.rtf")
// val bytes = AlBytes_Builder.begin()
// .storageKind(AlStorageKind.FileSystem)
// .filePath(file.path).end()
// AlDB.insert(AlParams_insertOrUpdate.ofEntity(bytes))
//
// AlDB.insertOrderFile(AlUAOrderFileWithParams(
// AlUAOrderFile_Builder.begin()
// .uuid("$i--f1cdbb11-f7a0-4a63-9c63-12920df5bfee")
// .orderID(order.id).end(),
// AlUAOrderFileParams_Builder.begin()
// .state(AlUAOrderFileState.UNKNOWN)
// .name("lbxproxy-$i.rtf")
// .size(Math.toIntExact(file.length()))
// .title("($i) Low Bandwidth X (LBX) proxy server configuration file")
// .details("($i) Applications that would like to take advantage of the Low Bandwidth extension to X (LBX) must make their connections to an lbxproxy. These applications need know nothing about LBX, they simply connect to the lbxproxy as if it were a regular X server. The lbxproxy accepts client connections, multiplexes them over a single connection to the X server, and performs various optimizations on the X protocol to make it faster over low bandwidth and/or high latency connections. It should be noted that such compression will not increase the pace of rendering all that much. Its primary purpose is to reduce network load and thus increase overall network latency. A competing project called DXPC (Differential X Protocol Compression) has been found to be more efficient at this task. Studies have shown though that in almost all cases ssh tunneling of X will produce far better results than through any of these specialised pieces of software.")
// .bytesID(bytes.id).end(),
// AlOperationData_Rudimentary_V1(AlBasicOperationData_V1.make("Describe me 537ea031-1d39-4e39-baaa-ebd8ab9d749e")).toOperation()))
// }
// }
}
object FakeShit {
fun nameToSurname(name: String): String {
return name.substringBefore(" ")
}
fun nameToEmail(name: String): String {
val surname = nameToSurname(name)
return transliterate(surname).toLowerCase() + "@mail.com"
}
fun transliterate(ru: String): String {
val map = mapOf('а' to "a",
'б' to "b",
'в' to "v",
'г' to "g",
'д' to "d",
'е' to "e",
'ё' to "e",
'ж' to "zh",
'з' to "z",
'и' to "i",
'й' to "j",
'к' to "k",
'л' to "l",
'м' to "m",
'н' to "n",
'о' to "o",
'п' to "p",
'р' to "r",
'с' to "s",
'т' to "t",
'у' to "u",
'ф' to "f",
'х' to "h",
'ц' to "c",
'ч' to "ch",
'ш' to "sh",
'щ' to "tsh",
'ъ' to "",
'ы' to "y",
'ь' to "",
'э' to "e",
'ю' to "yu",
'я' to "ya")
return ru.map {
var enCombo = map[it.toLowerCase()] ?: wtf()
if (it.isUpperCase())
enCombo = enCombo.capitalize()
enCombo
}.joinToString("")
}
private val bunchOfNamesString = """
Акматов Таштанбек; Алдабергенов Нурмолда; Александров Александр Петрович; Алиев Гейдар Алиевич; Амбарцумян Виктор Амазаспович; Анаров Алля; Ангелина Прасковья Никитична; Афанасьев Сергей Александрович; Ахунова Турсуной; Багирова Басти Масим кызы;
Байда Григорий Иванович; Балиманов Джабай; Баркова Ульяна Спиридоновна; Басов Николай Геннадиевич; Бедуля Владимир Леонтьевич; Белобородов Иван Фёдорович; Беляков Ростислав Аполлосович; Бешуля Спиридон Ерофеевич; Благонравов Анатолий Аркадьевич;
Блажевский Евгений Викторович; Боголюбов Николай Николаевич; Бойко Давид Васильевич; Бочвар Андрей Анатольевич; Брага Марк Андронович;
Бридько Иван Иванович; Брынцева Мария Александровна; Бугаев Борис Павлович; Бункин Борис Васильевич; Буркацкая Галина Евгеньевна; Буянов Иван Андреевич;
Вдовенко Пётр Фёдорович; Ведута Павел Филиппович; Виноградов Александр Павлович; Виштак Степанида Демидовна; Воловиков Пётр Митрофанович;
Воронин Павел Андреевич; Ганчев Иван Дмитриевич; Гасанова Шамама Махмудали кызы; Гвоздков Прокофий Захарович; Генералов Фёдор Степанович; Гиталов Александр Васильевич; Глушко Валентин Петрович; Головацкий Николай Никитич; Голубева Валентина Николаевна;
Гонтарь Дмитрий Иванович; Горбань Григорий Яковлевич; Горин Василий Яковлевич; Горшков Аким Васильевич; Грехова Евдокия Исаевна; Гришин Виктор Васильевич; Громыко Андрей Андреевич; Грушин Пётр Дмитриевич; Дементьев Пётр Васильевич; Диптан Ольга Климентьевна; Долгих Владимир Иванович;
Долинюк Евгения Алексеевна; Доллежаль Николай Антонович; Дроздецкий Егор Иванович; Дубковецкий Фёдор Иванович; Жахаев Ибрай; Желюк Филипп Алексеевич; Жуков Борис Петрович; Завенягин Авраамий Павлович; Зернов Павел Михайлович; Злобин Николай Анатольевич; Иванова Лидия Павловна; Исанин Николай Никитич; Исмаилов Карим; Кайназарова Суракан;
Калашников Михаил Тимофеевич; Капица Пётр Леонидович; Кикоин Исаак Константинович; Ким Пён Хва; Кириленко Андрей Павлович; Клепиков Михаил Иванович; Климов Владимир Яковлевич;
Князева Мария Даниловна; Ковалёв Сергей Никитич; Коваленко Александр Власович; Коврова Прасковья Николаевна; Козлов Дмитрий Ильич; Королёв Сергей Павлович; Коротков Сергей Ксенофонтович; Косыгин Алексей Николаевич;
Котельников Владимир Александрович; Кочарянц Самвел Григорьевич; Куанышбаев Жазылбек; Кузнецов Николай Дмитриевич; Купуния Тамара Андреевна; Кухарь Иван Иванович;
Лавочкин Семён Алексеевич; Ладани Анна Михайловна; Лиеберг Эндель Аугустович; Литвиненко Василий Тимофеевич; Литвинов Виктор Яковлевич; Лобытов Михаил Григорьевич; Лукьяненко Павел Пантелеймонович; Лычук Юстин Тодорович; Люльев Лев Вениаминович;
Макаров Александр Максимович; Макеев Виктор Петрович; Максимов Фёдор Павлович; Малинина Прасковья Андреевна; Мальцев Терентий Семёнович; Марков Георгий Мокеевич; Марцин Татьяна Филипповна;
Марцун Мария Антоновна; Микоян Артём Иванович; Михалёв Афанасий Прокопьевич ; Могильченко Григорий Сергеевич; Морозов Александр Александрович; Моторный Дмитрий Константинович; Музруков Борис Глебович;
Надирадзе Александр Давидович; Насыров Хамракул; Наумкин Василий Дмитриевич; Несмеянов Александр Николаевич; Нилова Аграфена Васильевна; Новожилов Генрих Васильевич; Нудельман Александр Эммануилович; Панфилов Михаил Панфилович;
Парубок Емельян Никонович; Патоличев Николай Семёнович; Патон Борис Евгеньевич; Пельше Арвид Янович; Петров Фёдор Николаевич; Петухова Ксения Куприяновна; Пилюгин Николай Алексеевич;
Питра Юрий Юрьевич; Плютинский Владимир Антонович; Подгорный Николай Викторович; Попов Павел Васильевич; Посмитный Макар Анисимович; Прозоров Пётр Алексеевич; Прохоров Александр Михайлович; Пустовойт Василий Степанович;
Пушкин Геннадий Александрович; Ралько Владимир Антонович; Рашидов Шараф Рашидович; Резников Вадим Федотович; Ремесло Василий Николаевич; Рогава Антимоз Михайлович; Романенко Прокофий Каленикович; Савченко Мария Харитоновна;
Садовников Владимир Геннадьевич; Саматов Абдугафур; Сванидзе Прокофий Николаевич; Свищёв Георгий Петрович; Семёнов Николай Николаевич; Семуле Марта Альмовна; Сергеев Владимир Григорьевич; Смирнов Василий Александрович;
Смирнова Анна Ивановна; Соколов Виктор Фадеевич; Соломенцев Михаил Сергеевич; Старовойтов Василий Константинович; Стрельченко Иван Иванович; Строев Николай Сергеевич;
Суслов Михаил Андреевич; Сухаренко Михаил Фёдорович; Сухой Павел Осипович; Таширов Хайтахун; Терещенко Николай Дмитриевич; Тихонов Николай Александрович; Ткачук Григорий Иванович; Трашутин Иван Яковлевич; Уланова Галина Сергеевна;
Улесов Алексей Александрович; Урунходжаев Саидходжа; Устинов Дмитрий Фёдорович; Уткин Владимир Фёдорович; Филатов Олег Васильевич; Целиков Александр Иванович; Цицин Николай Васильевич;
Челомей Владимир Николаевич; Червяков Александр Дмитриевич; Чердинцев Василий Макарович; Чих Михаил Павлович; Чичеров Владимир Степанович; Чуев Алексей Васильевич; Шлифер Леонид Иосифович;
Шокин Александр Иванович; Шолар Мария Дмитриевна; Шолохов Михаил Александрович; Штепо Виктор Иванович; Щербицкий Владимир Васильевич; Щукин Александр Николаевич; Эрсарыев Оразгельды;
Юрьев Василий Яковлевич; Яковлев Александр Сергеевич; Янгель Михаил Кузьмич; Ярыгин Владимир Михайлович;
"""
val bunchOfNames = bunchOfNamesString.split(";").map{it.trim()}.filter{it.isNotBlank()}
fun randomPhone(random: Random): String {
fun d() = ('0'.toInt() + random.nextInt(10)).toChar()
return "+38 (0${d()}${d()}) ${d()}${d()}${d()}-${d()}${d()}-${d()}${d()}"
}
class Tests {
@Test fun testNoDuplicateSurnames() {
val existing = mutableSetOf<String>()
for (name in bunchOfNames) {
val surname = nameToSurname(name)
if (existing.contains(surname))
Assert.fail("Bloody duplicate: $surname")
existing += surname
}
}
@Test fun testNameToEmail_noAssertions() {
for (name in bunchOfNames) {
val email = nameToEmail(name)
clog("$name --> $email")
}
}
@Test fun testRandomPhone_noAssertions() {
val random = Random()
for (i in 1..10)
clog(randomPhone(random))
}
}
}
| apache-2.0 | c93706aeb4f89c13f7dd01c75620b7d8 | 53.164969 | 977 | 0.635495 | 2.964222 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/statistics/ExternalSystemStatUtil.kt | 2 | 2400 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.statistics
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.utils.PluginInfo
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.statistics.ExternalSystemActionsCollector.Companion.EXTERNAL_SYSTEM_ID
import com.intellij.openapi.externalSystem.statistics.ProjectImportCollector.Companion.IMPORT_ACTIVITY
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.project.Project
fun getAnonymizedSystemId(systemId: ProjectSystemId): String {
val manager = ExternalSystemApiUtil.getManager(systemId) ?: return "undefined.system"
return if (getPluginInfo(manager.javaClass).isDevelopedByJetBrains()) systemId.readableName else "third.party"
}
fun addExternalSystemId(data: FeatureUsageData,
systemId: ProjectSystemId?) {
data.addData("system_id", anonymizeSystemId(systemId))
}
fun anonymizeSystemId(systemId: ProjectSystemId?) =
systemId?.let { getAnonymizedSystemId(it) } ?: "undefined.system"
fun findPluginInfoBySystemId(systemId: ProjectSystemId?): PluginInfo? {
if (systemId == null) return null
val manager = ExternalSystemApiUtil.getManager(systemId) ?: return null
val pluginInfo = getPluginInfo(manager.javaClass)
return if (pluginInfo.isDevelopedByJetBrains()) pluginInfo else null
}
fun importActivityStarted(project: Project, externalSystemId: ProjectSystemId,
dataSupplier: (() -> List<EventPair<*>>)?): StructuredIdeActivity {
return IMPORT_ACTIVITY.started(project){
val data: MutableList<EventPair<*>> = mutableListOf(EXTERNAL_SYSTEM_ID.with(anonymizeSystemId(externalSystemId)))
val pluginInfo = findPluginInfoBySystemId(externalSystemId)
if (pluginInfo != null) {
data.add(EventFields.PluginInfo.with(pluginInfo))
}
if(dataSupplier != null) {
data.addAll(dataSupplier())
}
data
}
} | apache-2.0 | f3203c37abdc1b53b8fbd47da44d2ac3 | 48 | 140 | 0.79125 | 4.780876 | false | false | false | false |
ianhanniballake/muzei | main/src/main/java/com/google/android/apps/muzei/quicksettings/NextArtworkTileService.kt | 1 | 6655 | /*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.quicksettings
import android.app.WallpaperManager
import android.content.ActivityNotFoundException
import android.content.ComponentName
import android.content.Intent
import android.graphics.drawable.Icon
import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.lifecycleScope
import com.google.android.apps.muzei.MuzeiWallpaperService
import com.google.android.apps.muzei.legacy.LegacySourceManager
import com.google.android.apps.muzei.legacy.allowsNextArtwork
import com.google.android.apps.muzei.room.MuzeiDatabase
import com.google.android.apps.muzei.room.Provider
import com.google.android.apps.muzei.util.launchWhenStartedIn
import com.google.android.apps.muzei.util.toast
import com.google.android.apps.muzei.wallpaper.WallpaperActiveState
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import net.nurik.roman.muzei.R
/**
* Quick Settings Tile which allows users quick access to the 'Next Artwork' command, if supported.
* In cases where Muzei is not activated, the tile also allows users to activate Muzei directly
* from the tile
*/
@OptIn(ExperimentalCoroutinesApi::class)
@RequiresApi(Build.VERSION_CODES.N)
class NextArtworkTileService : TileService(), LifecycleOwner {
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
private var currentProvider: Provider? = null
override fun onCreate() {
super.onCreate()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
WallpaperActiveState.onEach {
updateTile()
}.launchWhenStartedIn(this)
// Start listening for source changes, which will include when a source
// starts or stops supporting the 'Next Artwork' command
val database = MuzeiDatabase.getInstance(this)
database.providerDao().currentProvider.onEach { provider ->
currentProvider = provider
updateTile()
}.launchWhenStartedIn(this)
}
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
override fun onTileAdded() {
Firebase.analytics.logEvent("tile_next_artwork_added", null)
}
override fun onStartListening() {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
}
private suspend fun updateTile() {
val context = this
qsTile?.takeIf { !WallpaperActiveState.value || currentProvider != null }?.apply {
when {
!WallpaperActiveState.value -> {
// If the wallpaper isn't active, the quick tile will activate it
state = Tile.STATE_INACTIVE
label = getString(R.string.action_activate)
icon = Icon.createWithResource(context, R.drawable.ic_stat_muzei)
}
currentProvider.allowsNextArtwork(context) -> {
state = Tile.STATE_ACTIVE
label = getString(R.string.action_next_artwork)
icon = Icon.createWithResource(context, R.drawable.ic_notif_next_artwork)
}
else -> {
state = Tile.STATE_UNAVAILABLE
label = getString(R.string.action_next_artwork)
icon = Icon.createWithResource(context, R.drawable.ic_notif_next_artwork)
}
}
}?.updateTile()
}
override fun onClick() {
val context = this
qsTile?.run {
when (state) {
Tile.STATE_ACTIVE -> { // Active means we send the 'Next Artwork' command
lifecycleScope.launch(NonCancellable) {
Firebase.analytics.logEvent("next_artwork") {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "tile")
}
LegacySourceManager.getInstance(context).nextArtwork()
}
}
else -> unlockAndRun {
// Inactive means we attempt to activate Muzei
Firebase.analytics.logEvent("tile_next_artwork_activate", null)
try {
startActivityAndCollapse(Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER)
.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
ComponentName(context,
MuzeiWallpaperService::class.java))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
} catch (_: ActivityNotFoundException) {
try {
startActivityAndCollapse(Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
} catch (e: ActivityNotFoundException) {
context.toast(R.string.error_wallpaper_chooser, Toast.LENGTH_LONG)
}
}
}
}
}
}
override fun onStopListening() {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
}
override fun onTileRemoved() {
Firebase.analytics.logEvent("tile_next_artwork_removed", null)
}
override fun onDestroy() {
super.onDestroy()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
}
}
| apache-2.0 | de011d344eb452e64964506944430c65 | 40.59375 | 107 | 0.650939 | 5.115296 | false | false | false | false |
smmribeiro/intellij-community | uast/uast-common/src/org/jetbrains/uast/qualifiedUtils.kt | 10 | 9090 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmMultifileClass
@file:JvmName("UastUtils")
package org.jetbrains.uast
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiType
import com.intellij.psi.util.PsiMethodUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.visitor.UastVisitor
/**
* Get the topmost parent qualified expression for the call expression.
*
* Example 1:
* Code: variable.call(args)
* Call element: E = call(args)
* Qualified parent (return value): Q = [getQualifiedCallElement](E) = variable.call(args)
*
* Example 2:
* Code: call(args)
* Call element: E = call(args)
* Qualified parent (return value): Q = [getQualifiedCallElement](E) = call(args) (no qualifier)
*
* @return containing qualified expression if the call is a child of the qualified expression, call element otherwise.
*/
fun UExpression.getQualifiedParentOrThis(): UExpression {
fun findParent(current: UExpression?, previous: UExpression): UExpression? = when (current) {
is UQualifiedReferenceExpression -> {
if (current.selector == previous)
findParent(current.uastParent as? UExpression, current) ?: current
else
previous
}
is UParenthesizedExpression -> findParent(current.expression, previous) ?: previous
else -> null
}
return findParent(uastParent as? UExpression, this) ?: this
}
fun UExpression.asQualifiedPath(): List<String>? {
if (this is USimpleNameReferenceExpression) {
return listOf(this.identifier)
}
else if (this !is UQualifiedReferenceExpression) {
return null
}
var error = false
val list = mutableListOf<String>()
fun addIdentifiers(expr: UQualifiedReferenceExpression) {
val receiver = expr.receiver.unwrapParenthesis()
val selector = expr.selector as? USimpleNameReferenceExpression ?: run { error = true; return }
when (receiver) {
is UQualifiedReferenceExpression -> addIdentifiers(receiver)
is USimpleNameReferenceExpression -> list += receiver.identifier
else -> {
error = true
return
}
}
list += selector.identifier
}
addIdentifiers(this)
return if (error) null else list
}
/**
* Return the list of qualified expressions.
*
* Example:
* Code: obj.call(param).anotherCall(param2).getter
* Qualified chain: [obj, call(param), anotherCall(param2), getter]
*
* @return list of qualified expressions, or the empty list if the received expression is not a qualified expression.
*/
fun UExpression?.getQualifiedChain(): List<UExpression> {
fun collect(expr: UQualifiedReferenceExpression, chains: MutableList<UExpression>) {
val receiver = expr.receiver.unwrapParenthesis()
if (receiver is UQualifiedReferenceExpression) {
collect(receiver, chains)
}
else {
chains += receiver
}
val selector = expr.selector.unwrapParenthesis()
if (selector is UQualifiedReferenceExpression) {
collect(selector, chains)
}
else {
chains += selector
}
}
if (this == null) return emptyList()
val qualifiedExpression = this as? UQualifiedReferenceExpression ?: return listOf(this)
val chains = mutableListOf<UExpression>()
collect(qualifiedExpression, chains)
return chains
}
/**
* Return the outermost qualified expression.
*
* @return the outermost qualified expression,
* this element if the parent expression is not a qualified expression,
* or null if the element is not a qualified expression.
*
* Example:
* Code: a.b.c(asd).g
* Call element: c(asd)
* Outermost qualified (return value): a.b.c(asd).g
*/
fun UExpression.getOutermostQualified(): UQualifiedReferenceExpression? {
tailrec fun getOutermostQualified(current: UElement?, previous: UExpression): UQualifiedReferenceExpression? = when (current) {
is UQualifiedReferenceExpression -> getOutermostQualified(current.uastParent, current)
is UParenthesizedExpression -> getOutermostQualified(current.uastParent, previous)
else -> if (previous is UQualifiedReferenceExpression) previous else null
}
return getOutermostQualified(this.uastParent, this)
}
/**
* Checks if the received expression is a qualified chain of identifiers, and the trailing part of such chain is [fqName].
*
* @param fqName the chain part to check against. Sequence of identifiers, separated by dot ('.'). Example: "com.example".
* @return true, if the received expression is a qualified chain of identifiers, and the trailing part of such chain is [fqName].
*/
fun UExpression.matchesQualified(fqName: String): Boolean {
val identifiers = this.asQualifiedPath() ?: return false
val passedIdentifiers = fqName.trim('.').split('.')
return identifiers == passedIdentifiers
}
/**
* Checks if the received expression is a qualified chain of identifiers, and the leading part of such chain is [fqName].
*
* @param fqName the chain part to check against. Sequence of identifiers, separated by dot ('.'). Example: "com.example".
* @return true, if the received expression is a qualified chain of identifiers, and the leading part of such chain is [fqName].
*/
fun UExpression.startsWithQualified(fqName: String): Boolean {
val identifiers = this.asQualifiedPath() ?: return false
val passedIdentifiers = fqName.trim('.').split('.')
if (identifiers.size < passedIdentifiers.size) return false
passedIdentifiers.forEachIndexed { i, passedIdentifier ->
if (passedIdentifier != identifiers[i]) return false
}
return true
}
/**
* Checks if the received expression is a qualified chain of identifiers, and the trailing part of such chain is [fqName].
*
* @param fqName the chain part to check against. Sequence of identifiers, separated by dot ('.'). Example: "com.example".
* @return true, if the received expression is a qualified chain of identifiers, and the trailing part of such chain is [fqName].
*/
fun UExpression.endsWithQualified(fqName: String): Boolean {
val identifiers = this.asQualifiedPath()?.asReversed() ?: return false
val passedIdentifiers = fqName.trim('.').split('.').asReversed()
if (identifiers.size < passedIdentifiers.size) return false
passedIdentifiers.forEachIndexed { i, passedIdentifier ->
if (passedIdentifier != identifiers[i]) return false
}
return true
}
@JvmOverloads
fun UElement.asRecursiveLogString(render: (UElement) -> String = { it.asLogString() }): String {
val stringBuilder = StringBuilder()
val indent = " "
accept(object : UastVisitor {
private var level = 0
override fun visitElement(node: UElement): Boolean {
stringBuilder.append(indent.repeat(level))
stringBuilder.append(render(node))
stringBuilder.append('\n')
level++
return false
}
override fun afterVisitElement(node: UElement) {
super.afterVisitElement(node)
level--
}
})
return stringBuilder.toString()
}
/**
* @return method's containing class if the given method is main method,
* or companion object's containing class if the given method is main method annotated with [kotlin.jvm.JvmStatic] in companion object,
* otherwise *null*.
*/
fun getMainMethodClass(uMainMethod: UMethod): PsiClass? {
if ("main" != uMainMethod.name) return null
val containingClass = uMainMethod.uastParent as? UClass ?: return null
val mainMethod = uMainMethod.javaPsi
if (PsiMethodUtil.isMainMethod(mainMethod)) return containingClass.javaPsi
//a workaround for KT-33956
if (isKotlinParameterlessMain(mainMethod)) return containingClass.javaPsi
// Check for @JvmStatic main method in companion object
val parentClassForCompanionObject = (containingClass.uastParent as? UClass)?.javaPsi ?: return null
val mainInClass = PsiMethodUtil.findMainInClass(parentClassForCompanionObject)
if (mainMethod.manager.areElementsEquivalent(mainMethod, mainInClass)) {
return parentClassForCompanionObject
}
return null
}
private fun isKotlinParameterlessMain(mainMethod: PsiMethod) =
mainMethod.language.id == "kotlin"
&& mainMethod.parameterList.parameters.isEmpty()
&& PsiType.VOID == mainMethod.returnType
&& mainMethod.hasModifierProperty(PsiModifier.STATIC)
@ApiStatus.Experimental
fun findMainInClass(uClass: UClass?): PsiMethod? {
val javaPsi = uClass?.javaPsi ?: return null
PsiMethodUtil.findMainInClass(javaPsi)?.let { return it }
//a workaround for KT-33956
javaPsi.methods.find(::isKotlinParameterlessMain)?.let { return it }
return null
} | apache-2.0 | 808227419285d2ec95f57f15ad01b791 | 34.932806 | 135 | 0.734433 | 4.473425 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/embedded/grizzly/GrizzlyHttpContainer.kt | 1 | 15247 | package org.maxur.mserv.frame.embedded.grizzly
import org.glassfish.grizzly.CompletionHandler
import org.glassfish.grizzly.http.server.HttpHandler
import org.glassfish.grizzly.http.server.Request
import org.glassfish.grizzly.http.server.Response
import org.glassfish.hk2.api.ServiceLocator
import org.glassfish.hk2.api.TypeLiteral
import org.glassfish.hk2.utilities.binding.AbstractBinder
import org.glassfish.jersey.grizzly2.httpserver.internal.LocalizationMessages.EXCEPTION_SENDING_ERROR_RESPONSE
import org.glassfish.jersey.internal.PropertiesDelegate
import org.glassfish.jersey.internal.inject.ReferencingFactory
import org.glassfish.jersey.internal.util.collection.Ref
import org.glassfish.jersey.process.internal.RequestScoped
import org.glassfish.jersey.server.ApplicationHandler
import org.glassfish.jersey.server.ContainerException
import org.glassfish.jersey.server.ContainerRequest
import org.glassfish.jersey.server.ContainerResponse
import org.glassfish.jersey.server.ResourceConfig
import org.glassfish.jersey.server.ServerProperties
import org.glassfish.jersey.server.ServerProperties.REDUCE_CONTEXT_PATH_SLASHES_ENABLED
import org.glassfish.jersey.server.ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR
import org.glassfish.jersey.server.internal.ContainerUtils
import org.glassfish.jersey.server.spi.Container
import org.glassfish.jersey.server.spi.ContainerResponseWriter
import org.glassfish.jersey.server.spi.RequestScopedInitializer
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.IOException
import java.io.OutputStream
import java.net.URI
import java.net.URISyntaxException
import java.util.UUID
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Provider
import javax.ws.rs.core.Application
import javax.ws.rs.core.SecurityContext
import kotlin.reflect.KClass
/**
* Jersey {@code Container} implementation based on Grizzly {@link org.glassfish.grizzly.http.server.HttpHandler}.
*/
class GrizzlyHttpContainer internal constructor(
@Volatile private var appHandler: ApplicationHandler
) : HttpHandler(), Container {
companion object {
val log: Logger = LoggerFactory.getLogger(GrizzlyHttpContainer::class.java)
val requestRef: TypeLiteral<Ref<Request>> = object : TypeLiteral<Ref<Request>>() {}
val responseRef: TypeLiteral<Ref<Response>> = object : TypeLiteral<Ref<Response>>() {}
}
private val containerRequestFactory = ContainerRequestFactory(appHandler.configuration!!)
private var isDestroyed: Boolean = false
/**
* Create a new Grizzly HTTP container.
* @param application JAX-RS / Jersey application to be deployed on Grizzly HTTP container.
* @param parentLocator parent HK2 service locator.
*/
constructor(application: Application, parentLocator: ServiceLocator)
: this(ApplicationHandler(application, GrizzlyBinder(), parentLocator))
/**
* An internal binder to enable Grizzly HTTP container specific types injection.
*
* This binder allows to inject underlying Grizzly HTTP request and response instances.
* Note that since Grizzly `Request` class is not proxiable as it does not expose an empty constructor,
* the injection of Grizzly request instance into singleton JAX-RS and Jersey providers is only supported via
* [injection provider][javax.inject.Provider].
*/
internal class GrizzlyBinder : AbstractBinder() {
/**
* Referencing factory for Grizzly request.
*/
private class GrizzlyRequestReferencingFactory @Inject
constructor(referenceFactory: Provider<Ref<Request>>) : ReferencingFactory<Request>(referenceFactory)
/**
* Referencing factory for Grizzly response.
*/
private class GrizzlyResponseReferencingFactory @Inject
constructor(referenceFactory: Provider<Ref<Response>>) : ReferencingFactory<Response>(referenceFactory)
override fun configure() {
bindFactories(GrizzlyRequestReferencingFactory::class, Request::class, requestRef)
bindFactories(GrizzlyResponseReferencingFactory::class, Response::class, responseRef)
}
private fun <T : Any> bindFactories(
refFactoryClass: KClass<out ReferencingFactory<T>>,
clazz: KClass<T>,
ref: TypeLiteral<Ref<T>>
) {
bindFactory(refFactoryClass.java).to(clazz.java).proxy(false).`in`(RequestScoped::class.java)
bindFactory(ReferencingFactory.referenceFactory<T>()).to(ref).`in`(RequestScoped::class.java)
}
}
/** {@inheritDoc} */
override fun start() {
super.start()
appHandler.onStartup(this)
}
/** {@inheritDoc} */
override fun service(request: Request, response: Response) = try {
log.debug("GrizzlyHttpContainer.service(...) started")
appHandler.handle(containerRequestFactory.make(request, response))
} finally {
log.debug("GrizzlyHttpContainer.service(...) finished")
}
/** {@inheritDoc} */
override fun getConfiguration() = appHandler.configuration!!
/** {@inheritDoc} */
override fun reload() = reload(appHandler.configuration)
/** {@inheritDoc} */
override fun reload(configuration: ResourceConfig) {
appHandler.onShutdown(this)
appHandler = ApplicationHandler(configuration, GrizzlyBinder())
appHandler.onReload(this)
appHandler.onStartup(this)
containerRequestFactory.refreshProperty(configuration)
}
/** {@inheritDoc} */
override fun getApplicationHandler() = if (isDestroyed) null else appHandler
/** {@inheritDoc} */
override fun destroy() {
super.destroy()
appHandler.onShutdown(this)
isDestroyed = true
}
}
/**
* Grizzly container {@link PropertiesDelegate properties delegate}.
*/
private class RequestPropertiesDelegate(private val request: Request) : PropertiesDelegate {
/** {@inheritDoc} */
override fun getProperty(name: String): Any? = request.getAttribute(name)
/** {@inheritDoc} */
override fun getPropertyNames(): Collection<String>? = request.attributeNames
/** {@inheritDoc} */
override fun setProperty(name: String, value: Any) = request.setAttribute(name, value)
/** {@inheritDoc} */
override fun removeProperty(name: String) = request.removeAttribute(name)
}
private class ContainerRequestFactory(val configuration: ResourceConfig) {
/**
* Cached value of configuration property
* [org.glassfish.jersey.server.ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR].
* If `true` method [org.glassfish.grizzly.http.server.Response.setStatus] is used over
* [org.glassfish.grizzly.http.server.Response.sendError].
*/
private var configSetStatusOverSendError: Boolean? = null
/**
* Cached value of configuration property
* [org.glassfish.jersey.server.ServerProperties.REDUCE_CONTEXT_PATH_SLASHES_ENABLED].
* If `true` method [org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.getRequestUri]
* will reduce the of leading context-path slashes to only one.
*/
private var configReduceContextPathSlashesEnabled: Boolean? = null
init {
refreshProperty(configuration)
}
fun refreshProperty(configuration: ResourceConfig) {
configSetStatusOverSendError = configuration.propertyBy(RESPONSE_SET_STATUS_OVER_SEND_ERROR)
configReduceContextPathSlashesEnabled = configuration.propertyBy(REDUCE_CONTEXT_PATH_SLASHES_ENABLED)
}
private fun ResourceConfig.propertyBy(key: String) = ServerProperties.getValue(
configuration.properties, key, false, Boolean::class.javaObjectType
)
/**
* Make ContainerRequest by Request and Response
*/
fun make(request: Request, response: Response): ContainerRequest {
val requestContext = ContainerRequest(
request.baseUri(),
request.requestUri(),
request.method.methodString,
request.securityContext(),
RequestPropertiesDelegate(request)
)
requestContext.entityStream = request.inputStream
for (headerName in request.headerNames) {
requestContext.headers(headerName, request.getHeaders(headerName))
}
requestContext.setWriter(ResponseWriter(response, configSetStatusOverSendError!!))
requestContext.requestScopedInitializer = RequestScopedInitializer { locator ->
locator.getService<Ref<Request>>(GrizzlyHttpContainer.requestRef.type).set(request)
locator.getService<Ref<Response>>(GrizzlyHttpContainer.responseRef.type).set(response)
}
return requestContext
}
private fun Request.securityContext(): SecurityContext = object : SecurityContext {
/** {@inheritDoc} */
override fun isUserInRole(role: String) = false
/** {@inheritDoc} */
override fun isSecure() = [email protected]
/** {@inheritDoc} */
override fun getUserPrincipal() = [email protected]
/** {@inheritDoc} */
override fun getAuthenticationScheme() = [email protected]
}
private fun Request.baseUri(): URI = try {
this.uri(basePath())
} catch (ex: URISyntaxException) {
throw IllegalArgumentException(ex)
}
private fun Request.basePath(): String {
return when {
contextPath.isNullOrEmpty() -> "/"
contextPath.endsWith('/').not() -> contextPath + "/"
else -> contextPath
}
}
private fun Request.requestUri(): URI = try {
val serverAddress = uri().toString()
var uri = if (configReduceContextPathSlashesEnabled!! && !contextPath.isNullOrEmpty()) {
ContainerUtils.reduceLeadingSlashes(requestURI)
} else {
requestURI
}
val queryString = queryString
if (queryString != null) {
uri = uri + "?" + ContainerUtils.encodeUnsafeCharacters(queryString)
}
URI(serverAddress + uri)
} catch (ex: URISyntaxException) {
throw IllegalArgumentException(ex)
}
private fun Request.uri(basePath: String? = null): URI =
URI(scheme, null, serverName, serverPort, basePath, null, null)
private class ResponseWriter internal constructor(
private val grizzlyResponse: Response,
private val configSetStatusOverSendError: Boolean
) : ContainerResponseWriter {
private val emptyCompletionHandler = object : CompletionHandler<Response> {
/** {@inheritDoc} */
override fun cancelled() = Unit
/** {@inheritDoc} */
override fun failed(throwable: Throwable) = Unit
/** {@inheritDoc} */
override fun completed(result: Response) = Unit
/** {@inheritDoc} */
override fun updated(result: Response) = Unit
}
private val name: String = if (GrizzlyHttpContainer.log.isDebugEnabled) {
"ResponseWriter {id=${UUID.randomUUID()}, grizzlyResponse=${grizzlyResponse.hashCode()}}"
.also { GrizzlyHttpContainer.log.debug("{0} - init", it) }
} else {
"ResponseWriter"
}
/** {@inheritDoc} */
override fun toString() = name
/** {@inheritDoc} */
override fun commit() {
try {
if (grizzlyResponse.isSuspended) {
grizzlyResponse.resume()
}
} finally {
GrizzlyHttpContainer.log.debug("{0} - commit() called", name)
}
}
/** {@inheritDoc} */
override fun suspend(
timeOut: Long,
timeUnit: TimeUnit,
timeoutHandler: ContainerResponseWriter.TimeoutHandler?
): Boolean = try {
grizzlyResponse.suspend(timeOut, timeUnit, emptyCompletionHandler) {
timeoutHandler?.onTimeout(this@ResponseWriter)
// TODO should we return true in some cases instead?
// Returning false relies on the fact that the timeoutHandler will resume the response.
false
}
true
} catch (ex: IllegalStateException) {
false
} finally {
GrizzlyHttpContainer.log.debug("{0} - suspend(...) called", name)
}
/** {@inheritDoc} */
@Throws(IllegalStateException::class)
override fun setSuspendTimeout(timeOut: Long, timeUnit: TimeUnit) {
try {
grizzlyResponse.suspendContext.setTimeout(timeOut, timeUnit)
} finally {
GrizzlyHttpContainer.log.debug("{0} - setTimeout(...) called", name)
}
}
/** {@inheritDoc} */
@Throws(ContainerException::class)
override fun writeResponseStatusAndHeaders(
contentLength: Long,
responseContext: ContainerResponse
): OutputStream =
try {
val statusInfo = responseContext.statusInfo
when {
statusInfo.reasonPhrase == null -> grizzlyResponse.status = statusInfo.statusCode
else -> grizzlyResponse.setStatus(statusInfo.statusCode, statusInfo.reasonPhrase)
}
grizzlyResponse.contentLengthLong = contentLength
for ((key, values) in responseContext.stringHeaders) {
for (value in values) {
grizzlyResponse.addHeader(key, value)
}
}
grizzlyResponse.outputStream
} finally {
GrizzlyHttpContainer.log.debug("{0} - writeResponseStatusAndHeaders() called", name)
}
/** {@inheritDoc} */
override fun failure(error: Throwable) {
if (grizzlyResponse.isCommitted) return
try {
try {
if (configSetStatusOverSendError) {
grizzlyResponse.reset()
grizzlyResponse.setStatus(500, "Request failed.")
} else {
grizzlyResponse.sendError(500, "Request failed.")
}
} catch (ex: IllegalStateException) {
// a race condition externally committing the response can still occur...
GrizzlyHttpContainer.log.trace("Unable to reset failed response.", ex)
} catch (ex: IOException) {
throw ContainerException(EXCEPTION_SENDING_ERROR_RESPONSE(500, "Request failed."), ex)
}
} finally {
GrizzlyHttpContainer.log.debug("{0} - failure(...) called", name)
rethrow(error)
}
}
/** {@inheritDoc} */
override fun enableResponseBuffering() = true
/** {@inheritDoc} */
private fun rethrow(error: Throwable) {
when (error) {
is RuntimeException -> throw error
else -> throw ContainerException(error)
}
}
}
}
| apache-2.0 | a050d69b2015c1481d0ba52572fd5594 | 38.195373 | 114 | 0.65403 | 4.844932 | false | true | false | false |
sksamuel/ktest | kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/cli/ArgParseTest.kt | 1 | 1961 | package com.sksamuel.kotest.engine.cli
import io.kotest.core.spec.style.FunSpec
import io.kotest.engine.cli.parseArgs
import io.kotest.matchers.shouldBe
class ArgParseTest : FunSpec() {
init {
test("parsing args happy path") {
val args = listOf("--reporter", "taycan", "--package", "com.foo.bar.baz", "--spec", "FooBarTest")
parseArgs(args) shouldBe mapOf(
"reporter" to "taycan",
"package" to "com.foo.bar.baz",
"spec" to "FooBarTest",
)
}
test("parsing args with spaces in a value mid stream") {
val args = listOf("--reporter", "taycan", "--testname", "my test should be great", "--spec", "FooBarTest")
parseArgs(args) shouldBe mapOf(
"reporter" to "taycan",
"testname" to "my test should be great",
"spec" to "FooBarTest",
)
}
test("parsing args with spaces in the final element") {
val args = listOf("--reporter", "taycan", "--spec", "FooBarTest", "--testname", "my test should be great")
parseArgs(args) shouldBe mapOf(
"reporter" to "taycan",
"spec" to "FooBarTest",
"testname" to "my test should be great",
)
}
test("parsing args with non alpha") {
val args = listOf("--reporter", "taycan", "--spec", "FooBarTest", "--tags", "(Linux || Windows) && Hive")
parseArgs(args) shouldBe mapOf(
"reporter" to "taycan",
"spec" to "FooBarTest",
"tags" to "(Linux || Windows) && Hive",
)
}
test("parsing args with empty value") {
val args = listOf("--reporter", "taycan", "--spec", "FooBarTest", "--tags", "--testname", "wibble test")
parseArgs(args) shouldBe mapOf(
"reporter" to "taycan",
"spec" to "FooBarTest",
"tags" to "",
"testname" to "wibble test",
)
}
}
}
| mit | 5bec11fc279e6bf7f6a3b4bda951addf | 34.654545 | 115 | 0.539521 | 4.010225 | false | true | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-core/src/jvmTest/kotlin/com/sksamuel/kotest/FailuresTest.kt | 1 | 2216 | package com.sksamuel.kotest
import io.kotest.assertions.Actual
import io.kotest.assertions.Expected
import io.kotest.assertions.failure
import io.kotest.assertions.show.Printed
import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldStartWith
import io.kotest.matchers.types.shouldBeInstanceOf
import org.opentest4j.AssertionFailedError
class FailuresTest : StringSpec({
"failure(msg) should create a AssertionError on the JVM" {
val t = failure("msg")
t.shouldBeInstanceOf<AssertionError>()
t.message shouldBe "msg"
}
"failure(msg, cause) should create a AssertionError with the given cause on the JVM" {
val cause = RuntimeException()
val t = failure("msg", cause)
t.shouldBeInstanceOf<AssertionError>()
t.message shouldBe "msg"
t.cause shouldBe cause
}
"failure(expected, actual) should create a org.opentest4j.AssertionFailedError with JVM" {
val expected = Expected(Printed("1"))
val actual = Actual(Printed("2"))
val t = failure(expected, actual)
t.shouldBeInstanceOf<AssertionFailedError>()
t.message shouldBe "expected:<1> but was:<2>"
}
"failure(msg) should filter the stack trace removing io.kotest" {
val failure = failure("msg")
failure.stackTrace[0].className.shouldStartWith("com.sksamuel.kotest.FailuresTest")
}
"failure(msg, cause) should filter the stack trace removing io.kotest" {
val cause = RuntimeException()
val t = failure("msg", cause)
t.cause shouldBe cause
t.stackTrace[0].className.shouldStartWith("com.sksamuel.kotest.FailuresTest")
}
"failure(expected, actual) should filter the stack trace removing io.kotest" {
val expected = Expected(Printed("1"))
val actual = Actual(Printed("2"))
val t = failure(expected, actual)
t.stackTrace[0].className.shouldStartWith("com.sksamuel.kotest.FailuresTest")
}
"filters stacktrace when called by shouldBe" {
val t = shouldThrowAny { 1 shouldBe 2 }
t.stackTrace[0].className.shouldStartWith("com.sksamuel.kotest.FailuresTest")
}
})
| mit | 433f2da349f1d7aab8b86da32490242f | 35.327869 | 93 | 0.717509 | 4.220952 | false | true | false | false |
Magneticraft-Team/ModelLoader | src/main/kotlin/com/cout970/modelloader/MLCustomModelLoader.kt | 1 | 3254 | package com.cout970.modelloader
import net.minecraft.block.BlockState
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.model.*
import net.minecraft.client.renderer.texture.ISprite
import net.minecraft.client.renderer.texture.TextureAtlasSprite
import net.minecraft.client.renderer.vertex.VertexFormat
import net.minecraft.resources.IResourceManager
import net.minecraft.util.Direction
import net.minecraft.util.ResourceLocation
import net.minecraftforge.client.model.ICustomModelLoader
import java.util.*
import java.util.function.Function
/**
* Allows minecraft to load glTF and mcx model from blockstate json files
* It also allow to register empty models with "modelloader:empty"
*/
object MLCustomModelLoader : ICustomModelLoader {
private lateinit var resourceManager: IResourceManager
private val validDomains = mutableSetOf<String>()
/**
* Registers a modId, so this class is allowed to load models from that mod
*/
@JvmStatic
fun registerDomain(domain: String) {
validDomains += domain
}
override fun loadModel(modelLocation: ResourceLocation): IUnbakedModel {
if (modelLocation.namespace == "modelloader" && (modelLocation.path == "empty" || modelLocation.path == "models/empty")) {
return EmptyUnbakedModel
}
return ModelFormatRegistry.loadUnbakedModel(resourceManager, modelLocation)
}
override fun accepts(modelLocation: ResourceLocation): Boolean {
// Allow empty models with keys modelloader:empty or modelloader:models/empty
if (modelLocation.namespace == "modelloader" &&
(modelLocation.path == "empty" || modelLocation.path == "models/empty")) {
return true
}
val extension = modelLocation.path.substringAfterLast('.')
return modelLocation.namespace in validDomains && ModelFormatRegistry.supportsExtension(extension)
}
override fun onResourceManagerReload(resourceManager: IResourceManager) {
this.resourceManager = resourceManager
}
}
object EmptyUnbakedModel : IUnbakedModel {
override fun bake(bakery: ModelBakery, spriteGetter: Function<ResourceLocation, TextureAtlasSprite>,
sprite: ISprite, format: VertexFormat): IBakedModel? {
return EmptyBakedModel
}
override fun getTextures(modelGetter: Function<ResourceLocation, IUnbakedModel>,
missingTextureErrors: MutableSet<String>): MutableCollection<ResourceLocation> {
return mutableListOf()
}
override fun getDependencies(): MutableCollection<ResourceLocation> = mutableListOf()
}
object EmptyBakedModel : IBakedModel {
override fun getQuads(state: BlockState?, side: Direction?, rand: Random): MutableList<BakedQuad> {
return mutableListOf()
}
override fun isBuiltInRenderer(): Boolean = false
override fun isAmbientOcclusion(): Boolean = true
override fun isGui3d(): Boolean = true
override fun getOverrides(): ItemOverrideList = ItemOverrideList.EMPTY
override fun getParticleTexture(): TextureAtlasSprite {
val rl = ResourceLocation("modelloader", "empty")
return Minecraft.getInstance().textureMap.getSprite(rl)
}
} | gpl-2.0 | 56863308425d959729db5152a78a4e7e | 36.848837 | 130 | 0.730486 | 4.990798 | false | false | false | false |
BILLyTheLiTTle/KotlinExperiments | src/main/kotlin/koin/ModuleNamespace.kt | 1 | 1650 | package koin
import koin.components.*
import org.koin.dsl.module.module
import org.koin.standalone.KoinComponent
import org.koin.standalone.StandAloneContext
import org.koin.standalone.inject
// --- START ---
val moduleMN = module ("module.namespace") {
module ("a") { single { ComponentImplA("MN ComponentImplA") as Component } }
module ("b") { single { ComponentImplB("MN ComponentImplB", 0) as Component } }
}
// OR
// Uncomment this to see that there is no difference
/*val moduleMN = module ("module") {
module ("namespace") {
module("a") { single { ComponentImplA("MN ComponentImplA") as Component } }
module("b") { single { ComponentImplB("MN ComponentImplB", 0) as Component } }
}
// Uncomment below to see the error (Component for "module.namespace.a or b" is not visible in module.another.c
/*module ("another") {
module("c") { single { BabushkaComponent(get()) } }
}*/
}*/
// --- END ---
class ModuleNamespace: KoinComponent {
// --- START ---
private val comp: Component by inject(module = "module.namespace.a")
// OR
// Uncomment this to see that there is no difference
// private val comp: Component by inject(module = "a")
// --- END ---
// Uncomment also here to see the visibility error
// private val babComp: BabushkaComponent by inject(module = "module.another.c")
fun printInfo(){
println(comp.name)
// Uncomment also here to see the visibility error
// println(babComp.comp.name)
}
}
fun main(args: Array<String>) {
StandAloneContext.startKoin(listOf(moduleMN))
ModuleNamespace().printInfo()
} | gpl-3.0 | 7c302f852d97244d9c19c6657c81bab7 | 29.574074 | 115 | 0.658788 | 3.846154 | false | false | false | false |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/encoding/XCoderFactory.kt | 1 | 1972 | package io.oversec.one.crypto.encoding
import android.annotation.SuppressLint
import android.content.Context
import io.oversec.one.crypto.proto.Outer
import java.util.ArrayList
class XCoderFactory private constructor(context: Context) {
private val ALL = ArrayList<IXCoder>()
val base64XCoder = Base64XCoder(context).also { add(it) }
val zeroWidthXCoder = ZeroWidthXCoder(context).also { add(it) }
val asciiArmouredGpgXCoder = AsciiArmouredGpgXCoder(context).also { add(it) }
private fun add(coder: IXCoder) {
ALL.add(coder)
}
@Synchronized
fun decode(s: String): Outer.Msg? {
for (coder in ALL) {
try {
val m = coder.decode(s)
if (m != null) {
return m
}
} catch (e: Exception) {
//
}
}
return null
}
@Synchronized
fun getEncodingInfo(s: String): String {
for (coder in ALL) {
try {
val msg = coder.decode(s)
if (msg != null) {
return msg.msgDataCase.name + " (" + coder.getLabel(null) + ")"
}
} catch (e: Exception) {
//
}
}
return "N/A"
}
fun isEncodingCorrupt(s: String): Boolean {
for (coder in ALL) {
try {
coder.decode(s)
} catch (e: Exception) {
e.printStackTrace()
return true
}
}
return false
}
companion object {
@SuppressLint("StaticFieldLeak") // note that we're storing *Application*context
@Volatile
private var INSTANCE: XCoderFactory? = null
fun getInstance(ctx: Context): XCoderFactory =
INSTANCE ?: synchronized(this) {
INSTANCE ?: XCoderFactory(ctx.applicationContext).also { INSTANCE = it }
}
}
}
| gpl-3.0 | 5aec7c31e7abc2b10203530be1709a8b | 24.947368 | 88 | 0.523327 | 4.343612 | false | false | false | false |
collave/workbench-android-common | library/src/main/kotlin/com/collave/workbench/common/android/fragment/UIDialogFragment.kt | 1 | 1396 | package com.collave.workbench.common.android.fragment
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.View
import android.view.ViewGroup
import com.collave.workbench.common.android.base.BaseUI
import org.jetbrains.anko.AnkoContext
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.wrapContent
/**
* Created by Andrew on 6/7/2017.
*/
abstract class UIDialogFragment : DialogFragment() {
lateinit var ui: BaseUI
open var isFullWidth = false
open var isFullHeight = false
abstract fun onCreateUI(): BaseUI
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
ui = onCreateUI()
val dialog = Dialog(activity)
val view = ui.createView(AnkoContext.Companion.create(context!!, this))
view.layoutParams = ViewGroup.LayoutParams(matchParent, matchParent)
onViewCreated(view, savedInstanceState)
dialog.setContentView(view)
dialog.window.setLayout(if (isFullWidth) matchParent else wrapContent, if (isFullHeight) matchParent else wrapContent)
return dialog
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ui.fillView()
}
override fun onDestroyView() {
super.onDestroyView()
ui.destroyView()
}
} | gpl-3.0 | 7380958c521d3c8d2822aa310174dd79 | 29.369565 | 126 | 0.729943 | 4.562092 | false | false | false | false |
kmruiz/sonata | middle-end/src/main/kotlin/io/sonatalang/snc/middleEnd/domain/node/FunctionCallNode.kt | 1 | 2570 | package io.sonatalang.snc.middleEnd.domain.node
import io.sonatalang.snc.frontend.domain.token.*
import io.sonatalang.snc.middleEnd.domain.type.ObjectType
import io.sonatalang.snc.middleEnd.domain.type.Type
import io.sonatalang.snc.middleEnd.domain.type.TypeResolver
import io.sonatalang.snc.middleEnd.domain.type.exceptions.ParserTypeCastException
class ExpressingFunctionCallNode(val receiver: TypedNode, val parameters: List<TypedNode> = emptyList()) : FlowNode {
override fun consume(token: Token) = when {
token is SeparatorToken && token.value == ")" -> ResolveFunctionCallNode(receiver, parameters)
token is SeparatorToken && token.value == "," && parameters.isEmpty() -> throw IllegalArgumentException("Unexpected token")
else -> ExpressingFunctionCallInParameterNode(receiver, parameters, EmptyNode.consume(token))
}
}
class ExpressingFunctionCallInParameterNode(val receiver: TypedNode, val parameters: List<TypedNode> = emptyList(), val currentNode: Node) : FlowNode {
override fun consume(token: Token) = try {
ExpressingFunctionCallInParameterNode(receiver, parameters, currentNode.consume(token))
} catch (a: Throwable) {
when {
token is SeparatorToken && token.value == "," -> ExpressingFunctionCallNode(receiver, parameters + (currentNode as TypedNode))
token is SeparatorToken && token.value == ")" -> ResolveFunctionCallNode(receiver, parameters + currentNode)
else -> throw a
}
}
}
fun ResolveFunctionCallNode(receiver: Node, parameters: List<Node> = emptyList()): Node {
when {
receiver is TermNode && receiver.type != null -> if (parameters.isEmpty()) {
return receiver
} else {
throw ParserTypeCastException("Can't cast a literal to a n-ary function.")
}
else -> return FunctionCallNode(receiver, parameters)
}
}
class FunctionCallNode(val receiver: Node, val parameters: List<Node> = emptyList(), val expressionType: String? = null) : TypedNode {
override fun consume(token: Token) = when {
token is OperatorToken || token is IdentifierToken -> InExpressionOperatorNode(this).consume(token)
token is NewLineToken -> this
else -> throw IllegalStateException(token.toString() + " is an unexpected token")
}
override fun getType(typeResolver: TypeResolver) = if (expressionType != null) typeResolver.resolveTypeByName(expressionType) else ObjectType
override fun toString() = "<call> $receiver(${parameters.joinToString()}) </call>"
}
| gpl-2.0 | e6c4ca2eeba701a349b81932e718fe39 | 50.4 | 151 | 0.714008 | 4.516696 | false | false | false | false |
facebook/fresco | vito/litho/src/main/java/com/facebook/fresco/vito/litho/InViewportWorkingRange.kt | 1 | 1150 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.fresco.vito.litho
import com.facebook.litho.WorkingRange
/**
* Working range targeting components that are in the viewport (i.e., components that are visible).
*/
class InViewportWorkingRange : WorkingRange {
@Suppress("ConvertTwoComparisonsToRangeCheck")
private fun isInRange(position: Int, firstVisibleIndex: Int, lastVisibleIndex: Int): Boolean =
position >= firstVisibleIndex && position <= lastVisibleIndex
override fun shouldEnterRange(
position: Int,
firstVisibleIndex: Int,
lastVisibleIndex: Int,
firstFullyVisibleIndex: Int,
lastFullyVisibleIndex: Int
): Boolean = isInRange(position, firstVisibleIndex, lastVisibleIndex)
override fun shouldExitRange(
position: Int,
firstVisibleIndex: Int,
lastVisibleIndex: Int,
firstFullyVisibleIndex: Int,
lastFullyVisibleIndex: Int
): Boolean = !isInRange(position, firstVisibleIndex, lastVisibleIndex)
}
| mit | 572b91e6c2649f874b23c8db12d3122b | 30.944444 | 99 | 0.73913 | 4.423077 | false | false | false | false |
Maxr1998/MaxLock | app/src/main/java/de/Maxr1998/xposed/maxlock/ui/settings/applist/AppListAdapter.kt | 1 | 8306 | /*
* MaxLock, an Xposed applock module for Android
* Copyright (C) 2014-2018 Max Rumpf alias Maxr1998
*
* 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 any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Maxr1998.xposed.maxlock.ui.settings.applist
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import androidx.appcompat.app.AlertDialog
import androidx.core.content.edit
import androidx.recyclerview.widget.RecyclerView
import com.haibison.android.lockpattern.LockPatternActivity
import de.Maxr1998.xposed.maxlock.Common
import de.Maxr1998.xposed.maxlock.MLImplementation
import de.Maxr1998.xposed.maxlock.R
import de.Maxr1998.xposed.maxlock.ui.settings.LockSetupFragment
import de.Maxr1998.xposed.maxlock.ui.settings.MaxLockPreferenceFragment
import de.Maxr1998.xposed.maxlock.util.KUtil.getPatternCode
import de.Maxr1998.xposed.maxlock.util.MLPreferences
import de.Maxr1998.xposed.maxlock.util.Util
import de.Maxr1998.xposed.maxlock.util.asReference
import java.util.*
class AppListAdapter(val appListModel: AppListModel, context: Context) : RecyclerView.Adapter<AppListViewHolder>(), Filterable {
private val prefs = MLPreferences.getPreferences(context)
private val prefsApps = MLPreferences.getPrefsApps(context)
private var prefsKeysPerApp = MLPreferences.getPreferencesKeysPerApp(context)
private val filter = AppFilter(this, prefs, prefsApps)
init {
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppListViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.app_list_item, parent, false)
return AppListViewHolder(v)
}
override fun onBindViewHolder(holder: AppListViewHolder, position: Int) {
val appInfo = appListModel.appList[position]
holder.bind(appInfo, appListModel.iconCache)
holder.options.setOnClickListener {
var items = it.resources.getTextArray(R.array.dialog_multi_select_items_options)
if (MLImplementation.getImplementation(prefs) != MLImplementation.DEFAULT)
items = Arrays.copyOf<CharSequence>(items, items.size - 2)
val optionsDialog = AlertDialog.Builder(it.context)
.setTitle(it.resources.getString(R.string.dialog_title_options))
.setIcon(appListModel.iconCache[appInfo.packageName] ?: appInfo.loadIcon())
.setMultiChoiceItems(items, booleanArrayOf(
prefsKeysPerApp.contains(appInfo.packageName),
prefsApps.getBoolean(appInfo.packageName + Common.APP_FAKE_CRASH_PREFERENCE, false),
prefsApps.getBoolean(appInfo.packageName + Common.APP_HIDE_NOTIFICATIONS_PREFERENCE, false),
prefsApps.getBoolean(appInfo.packageName + Common.APP_HIDE_NOTIFICATION_CONTENT_PREFERENCE, false)))
{ dialog, which, isChecked ->
var prefKey: String? = null
when (which) {
0 -> {
handleCustomLockingType(it.context, appInfo.packageName, isChecked, dialog, holder.adapterPosition)
return@setMultiChoiceItems
}
1 -> prefKey = appInfo.packageName + Common.APP_FAKE_CRASH_PREFERENCE
2 -> prefKey = appInfo.packageName + Common.APP_HIDE_NOTIFICATIONS_PREFERENCE
3 -> prefKey = appInfo.packageName + Common.APP_HIDE_NOTIFICATION_CONTENT_PREFERENCE
}
prefKey?.let { key ->
prefsApps.edit {
if (isChecked) putBoolean(key, true)
else remove(key)
}
}
}
.setPositiveButton(android.R.string.ok, null)
if (MLImplementation.getImplementation(MLPreferences.getPreferences(it.context)) == MLImplementation.DEFAULT)
optionsDialog.setNeutralButton(R.string.dialog_button_exclude_activities) { _, _ ->
showActivities(appListModel, it.context.asReference(), appInfo.packageName)
}
optionsDialog.create().let { dialog -> appListModel.dialogDispatcher.call(dialog) }
}
}
override fun onViewRecycled(holder: AppListViewHolder) {
holder.appIcon.setImageDrawable(null)
}
override fun getItemId(position: Int) = appListModel.appList[position].id.toLong()
override fun getItemCount() = appListModel.appList.size()
override fun getItemViewType(position: Int) = R.layout.app_list_item
override fun getFilter(): Filter = filter
@Suppress("unused")
fun getSectionName(position: Int): String {
fun transformLetter(c: Char): String {
return if (c.isDigit()) {
"#"
} else c.toString()
}
return appListModel.appList.run {
val pos = if (position < size()) position else if (size() > 0) size() - 1 else 0
transformLetter(get(pos).name[0])
}
}
private fun handleCustomLockingType(context: Context, packageName: String, checked: Boolean, dialog: DialogInterface, adapterPosition: Int) {
if (checked) {
dialog.dismiss()
AlertDialog.Builder(context)
.setItems(arrayOf(
context.getString(R.string.pref_locking_type_password),
context.getString(R.string.pref_locking_type_pin),
context.getString(R.string.pref_locking_type_knockcode),
context.getString(R.string.pref_locking_type_pattern)))
{ typeDialog, i ->
typeDialog.dismiss()
val extras = Bundle(2)
when (i) {
0 -> {
Util.setPassword(context, packageName)
return@setItems
}
1 -> extras.putString(Common.LOCKING_TYPE, Common.LOCKING_TYPE_PIN)
2 -> extras.putString(Common.LOCKING_TYPE, Common.LOCKING_TYPE_KNOCK_CODE)
3 -> {
val intent = Intent(LockPatternActivity.ACTION_CREATE_PATTERN, null, context, LockPatternActivity::class.java)
appListModel.fragmentFunctionDispatcher.value = {
startActivityForResult(intent, getPatternCode(adapterPosition))
}
return@setItems
}
}
extras.putString(Common.INTENT_EXTRAS_CUSTOM_APP, packageName)
LockSetupFragment().let {
it.arguments = extras
appListModel.fragmentFunctionDispatcher.value = {
MaxLockPreferenceFragment.launchFragment(this, it, false)
}
}
}.create().let { appListModel.dialogDispatcher.call(it) }
} else {
prefsKeysPerApp.edit {
remove(packageName)
remove(packageName + Common.APP_KEY_PREFERENCE)
}
}
}
} | gpl-3.0 | 83f85ce5dfd725840625a18f20d1dcd2 | 48.742515 | 145 | 0.605225 | 4.935235 | false | false | false | false |
Fondesa/RecyclerViewDivider | recycler-view-divider/src/main/kotlin/com/fondesa/recyclerviewdivider/CreateGrid.kt | 1 | 2632 | /*
* Copyright (c) 2020 Giorgio Antonioli
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fondesa.recyclerviewdivider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
/**
* Creates a [Grid] from a [LinearLayoutManager]/[GridLayoutManager].
*
* @param itemCount the number of the items in the [RecyclerView].
* @return the grid layout of the given layout manager.
* @see Grid
*/
internal fun LinearLayoutManager.grid(itemCount: Int): Grid =
if (this is GridLayoutManager && spanCount > 1) multipleSpanGrid(itemCount) else singleSpanGrid(itemCount)
private fun LinearLayoutManager.singleSpanGrid(itemCount: Int): Grid {
val rows = List(itemCount) { Line(cells = listOf(Cell(spanSize = 1))) }
return Grid(spanCount = 1, orientation = layoutOrientation, layoutDirection = obtainLayoutDirection(), lines = rows)
}
private fun GridLayoutManager.multipleSpanGrid(itemCount: Int): Grid {
val spanCount = spanCount
val spanSizeLookup = spanSizeLookup
val lines = mutableListOf<Line>()
var cellsInLine = mutableListOf<Cell>()
(0 until itemCount).forEach { index ->
// The span-index is always 0 on the first item so it should be skipped, otherwise an empty row would be added.
if (index != 0 && spanSizeLookup.getSpanIndex(index, spanCount) == 0) {
// The item with index [index] is in a new row so the previous row is created with the old cells.
lines += Line(cells = cellsInLine)
// Since it's a new row, the cells list must be reset.
cellsInLine = mutableListOf()
}
// Every item consists in a new cell.
cellsInLine.add(Cell(spanSize = spanSizeLookup.getSpanSize(index)))
// The last row must be created with the collected cells.
if (index == itemCount - 1) {
lines += Line(cells = cellsInLine)
}
}
return Grid(spanCount = spanCount, orientation = layoutOrientation, layoutDirection = obtainLayoutDirection(), lines = lines)
}
| apache-2.0 | 56e2070af0f27fa9423ecd3a817c05df | 43.610169 | 129 | 0.711626 | 4.537931 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/economy/RPKEconomyServiceImpl.kt | 1 | 5146 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.economy.bukkit.economy
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.core.service.Services
import com.rpkit.economy.bukkit.RPKEconomyBukkit
import com.rpkit.economy.bukkit.currency.RPKCurrency
import com.rpkit.economy.bukkit.currency.RPKCurrencyService
import com.rpkit.economy.bukkit.database.table.RPKWalletTable
import com.rpkit.economy.bukkit.event.economy.RPKBukkitBalanceChangeEvent
import com.rpkit.economy.bukkit.exception.NegativeBalanceException
import com.rpkit.economy.bukkit.wallet.RPKWallet
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.logging.Level
/**
* Economy service implementation.
*/
class RPKEconomyServiceImpl(override val plugin: RPKEconomyBukkit) : RPKEconomyService {
private val balance: MutableMap<Int, MutableMap<RPKCurrency, Int>> = ConcurrentHashMap()
override fun getPreloadedBalance(character: RPKCharacter, currency: RPKCurrency): Int? {
val characterId = character.id?.value ?: return null
return balance[characterId]?.get(currency)
}
override fun loadBalances(character: RPKCharacter): CompletableFuture<Void> {
val characterId = character.id?.value ?: return CompletableFuture.completedFuture(null)
val currencyService = Services[RPKCurrencyService::class.java] ?: return CompletableFuture.completedFuture(null)
return CompletableFuture.runAsync {
val characterBalances = balance[characterId] ?: ConcurrentHashMap()
currencyService.currencies.forEach { currency ->
characterBalances[currency] = getBalance(character, currency).join()
}
balance[characterId] = characterBalances
}
}
override fun unloadBalances(character: RPKCharacter) {
val characterId = character.id?.value ?: return
balance.remove(characterId)
}
override fun getBalance(character: RPKCharacter, currency: RPKCurrency): CompletableFuture<Int> {
val preloadedBalance = getPreloadedBalance(character, currency)
if (preloadedBalance != null) return CompletableFuture.completedFuture(preloadedBalance)
return plugin.database.getTable(RPKWalletTable::class.java).get(character, currency).thenApply { it?.balance ?: currency.defaultAmount }
}
override fun setBalance(character: RPKCharacter, currency: RPKCurrency, amount: Int): CompletableFuture<Void> {
return CompletableFuture.runAsync {
val event = RPKBukkitBalanceChangeEvent(character, currency, getBalance(character, currency).join(), amount, true)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return@runAsync
if (event.newBalance < 0) throw NegativeBalanceException()
val walletTable = plugin.database.getTable(RPKWalletTable::class.java)
walletTable.get(event.character, event.currency).thenAcceptAsync { fetchedWallet ->
val wallet = fetchedWallet ?: RPKWallet(event.character, event.currency, event.newBalance).also { walletTable.insert(it).join() }
wallet.balance = event.newBalance
walletTable.update(wallet).join()
val characterId = event.character.id?.value
if (characterId != null) {
val characterBalances = balance[characterId]
if (characterBalances != null) {
characterBalances[currency] = amount
}
}
}.join()
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to set balance", exception)
throw exception
}
}
override fun transfer(from: RPKCharacter, to: RPKCharacter, currency: RPKCurrency, amount: Int): CompletableFuture<Void> {
return CompletableFuture.runAsync {
setBalance(from, currency, getBalance(from, currency).join() - amount).join()
setBalance(to, currency, getBalance(to, currency).join() + amount).join()
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to transfer", exception)
throw exception
}
}
override fun getRichestCharacters(currency: RPKCurrency, amount: Int): CompletableFuture<List<RPKCharacter>> {
return plugin.database.getTable(RPKWalletTable::class.java).getTop(amount, currency).thenApply { wallets ->
wallets.map(RPKWallet::character)
}
}
} | apache-2.0 | 33b281a731dd833148366e950291e629 | 46.657407 | 145 | 0.702876 | 4.769231 | false | false | false | false |
systemallica/ValenBisi | app/src/main/kotlin/com/systemallica/valenbisi/activities/DonateActivity.kt | 1 | 5630 | package com.systemallica.valenbisi.activities
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.android.billingclient.api.*
import com.systemallica.valenbisi.R
import com.systemallica.valenbisi.databinding.ActivityDonateBinding
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
class DonateActivity : AppCompatActivity(), PurchasesUpdatedListener, CoroutineScope {
private lateinit var billingClient: BillingClient
private var job: Job = Job()
private lateinit var binding: ActivityDonateBinding
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDonateBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
val mToolbar = findViewById<Toolbar>(R.id.toolbarDonate)
setSupportActionBar(mToolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowTitleEnabled(false)
setClickListeners()
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
private fun setClickListeners() {
binding.cardViewOne.setOnClickListener { startBuyProcess("donation_upgrade") }
binding.cardViewThree.setOnClickListener { startBuyProcess("donation_upgrade_3") }
binding.cardViewFive.setOnClickListener { startBuyProcess("donation_upgrade_5") }
}
private fun startBuyProcess(sku: String) {
billingClient = BillingClient.newBuilder(applicationContext).setListener(this).enablePendingPurchases().build()
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
// The BillingClient is ready
// Start buy process
launch {
val result = querySkuDetails(sku)
onResult(result)
}
}
}
override fun onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
Snackbar.make(binding.donateView, R.string.donation_cancelled, Snackbar.LENGTH_SHORT)
.show()
}
})
}
private fun onResult(skuDetailsLis: SkuDetailsResult) {
// Only one item at a time
val skuDetails = skuDetailsLis.skuDetailsList!![0]
// Set params of the purchase
val flowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetails)
.build()
// Launch purchase
billingClient.launchBillingFlow(this@DonateActivity, flowParams)
}
private suspend fun querySkuDetails(sku: String): SkuDetailsResult {
val skuList = ArrayList<String>()
skuList.add(sku)
val params = SkuDetailsParams.newBuilder()
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP)
// Return SkuDetails
return withContext(Dispatchers.IO) {
billingClient.querySkuDetails(params.build())
}
}
override fun onPurchasesUpdated(billingResult: BillingResult, purchases: List<Purchase>?) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
// Acknowledge purchase
launch {
handlePurchase(purchases[0])
}
// Consume it so it can be purchased again
launch {
consumePurchase(purchases[0])
}
} else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
Snackbar.make(binding.donateView, R.string.donation_cancelled, Snackbar.LENGTH_SHORT).show()
} else {
// Handle any other error codes.
Snackbar.make(binding.donateView, R.string.donation_cancelled, Snackbar.LENGTH_SHORT).show()
}
}
private suspend fun handlePurchase(purchase: Purchase) {
if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED) {
// Grant entitlement to the user.
Snackbar.make(binding.donateView, "Thank you!", Snackbar.LENGTH_SHORT).show()
// Acknowledge the purchase if it hasn't already been acknowledged.
if (!purchase.isAcknowledged) {
val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.purchaseToken)
withContext(Dispatchers.IO) {
billingClient.acknowledgePurchase(acknowledgePurchaseParams.build())
}
}
}
}
private suspend fun consumePurchase(purchase: Purchase) {
val consumeParams =
ConsumeParams.newBuilder()
.setPurchaseToken(purchase.purchaseToken)
.build()
withContext(Dispatchers.IO) {
billingClient.consumePurchase(consumeParams)
}
}
}
| gpl-3.0 | 39f4dd307a4cfff009b39d0e5f079aeb | 37.040541 | 119 | 0.646536 | 5.439614 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/history/ChangedParameter.kt | 1 | 2029 | /*
Tickle
Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.tickle.editor.scene.history
import uk.co.nickthecoder.paratask.parameters.ValueParameter
import uk.co.nickthecoder.tickle.editor.resources.DesignActorResource
import uk.co.nickthecoder.tickle.editor.resources.ModificationType
import uk.co.nickthecoder.tickle.editor.scene.SceneEditor
/**
* Added to History when a parameter on the ActorAttributesForm changes.
* Note, unlike most Changes, these are created AFTER the change has occurred.
*/
class ChangedParameter<T> (
private val actorResource: DesignActorResource,
private val parameter: ValueParameter<T>,
private val oldValue: T)
: Change {
private var newValue = parameter.value
override fun redo(sceneEditor: SceneEditor) {
if ( parameter.value != newValue ) {
parameter.value = newValue
sceneEditor.sceneResource.fireChange(actorResource, ModificationType.CHANGE)
}
}
override fun undo(sceneEditor: SceneEditor) {
parameter.value = oldValue
sceneEditor.sceneResource.fireChange(actorResource, ModificationType.CHANGE)
}
/*
override fun mergeWith(other: Change): Boolean {
if (other is ChangedParameter<*> && other.actorResource == actorResource) {
other.newValue = newValue
return true
}
return false
}
*/
}
| gpl-3.0 | 1590609b4600fbcf15e82623051534ee | 33.389831 | 88 | 0.729916 | 4.549327 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/economy/LoraffleCommand.kt | 1 | 7739 | package net.perfectdreams.loritta.morenitta.commands.vanilla.economy
import com.github.kevinsawicki.http.HttpRequest
import com.github.salomonbrys.kotson.get
import com.github.salomonbrys.kotson.int
import com.github.salomonbrys.kotson.jsonObject
import com.github.salomonbrys.kotson.long
import com.github.salomonbrys.kotson.nullString
import com.github.salomonbrys.kotson.string
import com.google.gson.JsonParser
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.threads.RaffleThread
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.DateUtils
import net.perfectdreams.loritta.morenitta.utils.MiscUtils
import net.perfectdreams.loritta.morenitta.utils.gson
import net.perfectdreams.loritta.morenitta.utils.stripCodeMarks
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.utils.AccountUtils
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.utils.GACampaigns
import net.perfectdreams.loritta.morenitta.LorittaBot
class LoraffleCommand(loritta: LorittaBot) : AbstractCommand(loritta, "loraffle", listOf("rifa", "raffle", "lorifa"), net.perfectdreams.loritta.common.commands.CommandCategory.ECONOMY) {
companion object {
const val MAX_TICKETS_BY_USER_PER_ROUND = 100_000
}
override fun getDescriptionKey() = LocaleKeyData("commands.command.raffle.description")
override fun getExamplesKey() = LocaleKeyData("commands.command.raffle.examples")
override suspend fun run(context: CommandContext,locale: BaseLocale) {
val arg0 = context.args.getOrNull(0)
if (arg0 == "clear" && loritta.isOwner(context.userHandle.id)) {
context.reply(
LorittaReply(
"Limpando ${RaffleThread.userIds.size}..."
)
)
RaffleThread.userIds.clear()
context.reply(
LorittaReply(
"Limpo! ${RaffleThread.userIds.size}"
)
)
return
}
val shard = loritta.config.loritta.clusters.instances.first { it.id == 1 }
if (arg0 == "comprar" || arg0 == "buy") {
val quantity = Math.max(context.args.getOrNull(1)?.toIntOrNull() ?: 1, 1)
val dailyReward = AccountUtils.getUserTodayDailyReward(loritta, context.lorittaUser.profile)
if (dailyReward == null) { // Nós apenas queremos permitir que a pessoa aposte na rifa caso já tenha pegado sonhos alguma vez hoje
context.reply(
LorittaReply(
locale["commands.youNeedToGetDailyRewardBeforeDoingThisAction", context.config.commandPrefix],
Constants.ERROR
)
)
return
}
if (quantity > MAX_TICKETS_BY_USER_PER_ROUND) {
context.reply(
LorittaReply(
"Você só pode apostar no máximo $MAX_TICKETS_BY_USER_PER_ROUND tickets por rodada!",
Constants.ERROR
)
)
return
}
val body = HttpRequest.post("${shard.getUrl(loritta)}/api/v1/loritta/raffle")
.userAgent(loritta.lorittaCluster.getUserAgent(loritta))
.header("Authorization", loritta.lorittaInternalApiKey.name)
.connectTimeout(loritta.config.loritta.clusterConnectionTimeout)
.readTimeout(loritta.config.loritta.clusterReadTimeout)
.send(
gson.toJson(
jsonObject(
"userId" to context.userHandle.id,
"quantity" to quantity,
"localeId" to context.config.localeId
)
)
)
.body()
val json = JsonParser.parseString(body)
val status = BuyRaffleTicketStatus.valueOf(json["status"].string)
if (status == BuyRaffleTicketStatus.THRESHOLD_EXCEEDED) {
context.reply(
LorittaReply(
"Você já tem tickets demais! Guarde um pouco do seu dinheiro para a próxima rodada!",
Constants.ERROR
)
)
return
}
if (status == BuyRaffleTicketStatus.TOO_MANY_TICKETS) {
context.reply(
LorittaReply(
"Você não pode apostar tantos tickets assim! Você pode apostar, no máximo, mais ${MAX_TICKETS_BY_USER_PER_ROUND - json["ticketCount"].int} tickets!",
Constants.ERROR
)
)
return
}
if (status == BuyRaffleTicketStatus.NOT_ENOUGH_MONEY) {
context.reply(
LorittaReply(
context.locale["commands.command.raffle.notEnoughMoney", json["canOnlyPay"].int, quantity, if (quantity == 1) "" else "s"],
Constants.ERROR
),
LorittaReply(
GACampaigns.sonhosBundlesUpsellDiscordMessage(
"https://loritta.website/", // Hardcoded, woo
"loraffle-legacy",
"buy-tickets-not-enough-sonhos"
),
prefix = Emotes.LORI_RICH.asMention,
mentionUser = false
)
)
return
}
if (status == BuyRaffleTicketStatus.STALE_RAFFLE_DATA) {
context.reply(
LorittaReply(
"O resultado da rifa demorou tanto para sair que já começou uma nova rifa enquanto você comprava!",
Constants.ERROR
)
)
return
}
context.reply(
LorittaReply(
context.locale["commands.command.raffle.youBoughtAnTicket", quantity, if (quantity == 1) "" else "s", quantity.toLong() * 250],
"\uD83C\uDFAB"
),
LorittaReply(
context.locale["commands.command.raffle.wantMoreChances", context.config.commandPrefix],
mentionUser = false
)
)
return
}
val body = HttpRequest.get("${shard.getUrl(loritta)}/api/v1/loritta/raffle")
.userAgent(loritta.lorittaCluster.getUserAgent(loritta))
.header("Authorization", loritta.lorittaInternalApiKey.name)
.connectTimeout(loritta.config.loritta.clusterConnectionTimeout)
.readTimeout(loritta.config.loritta.clusterReadTimeout)
.body()
val json = JsonParser.parseString(body)
val lastWinnerId = json["lastWinnerId"].nullString
?.toLongOrNull()
val currentTickets = json["currentTickets"].int
val usersParticipating = json["usersParticipating"].int
val started = json["started"].long
val lastWinnerPrize = json["lastWinnerPrize"].long
val lastWinner = if (lastWinnerId != null) {
loritta.lorittaShards.retrieveUserInfoById(lastWinnerId.toLong())
} else {
null
}
val nameAndDiscriminator = if (lastWinner != null) {
(lastWinner.name + "#" + lastWinner.discriminator).let {
if (MiscUtils.hasInvite(it))
"¯\\_(ツ)_/¯"
else
it
}
} else {
"\uD83E\uDD37"
}.stripCodeMarks()
context.reply(
LorittaReply(
"**Lorifa**",
"<:loritta:331179879582269451>"
),
LorittaReply(
context.locale["commands.command.raffle.currentPrize", (currentTickets * 250).toString()],
"<:starstruck:540988091117076481>",
mentionUser = false
),
LorittaReply(
context.locale["commands.command.raffle.boughtTickets", currentTickets],
"\uD83C\uDFAB",
mentionUser = false
),
LorittaReply(
context.locale["commands.command.raffle.usersParticipating", usersParticipating],
"\uD83D\uDC65",
mentionUser = false
),
LorittaReply(
context.locale["commands.command.raffle.lastWinner", "$nameAndDiscriminator (${lastWinner?.id})", lastWinnerPrize],
"\uD83D\uDE0E",
mentionUser = false
),
LorittaReply(
context.locale["commands.command.raffle.resultsIn", DateUtils.formatDateWithRelativeFromNowAndAbsoluteDifference(started + 3600000, locale)],
prefix = "\uD83D\uDD52",
mentionUser = false
),
LorittaReply(
context.locale["commands.command.raffle.buyAnTicketFor", context.config.commandPrefix],
prefix = "\uD83D\uDCB5",
mentionUser = false
)
)
}
enum class BuyRaffleTicketStatus {
SUCCESS,
THRESHOLD_EXCEEDED,
TOO_MANY_TICKETS,
NOT_ENOUGH_MONEY,
STALE_RAFFLE_DATA
}
} | agpl-3.0 | a1d7000075448a10efe3a3c47f350744 | 31.037344 | 186 | 0.718135 | 3.477477 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/message/MessengerViewModel.kt | 1 | 5210 | package me.proxer.app.chat.prv.message
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import com.gojuno.koptional.rxjava2.filterSome
import com.gojuno.koptional.toOptional
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.schedulers.Schedulers
import me.proxer.app.base.PagedViewModel
import me.proxer.app.chat.prv.LocalConference
import me.proxer.app.chat.prv.LocalMessage
import me.proxer.app.chat.prv.sync.MessengerDao
import me.proxer.app.chat.prv.sync.MessengerErrorEvent
import me.proxer.app.chat.prv.sync.MessengerWorker
import me.proxer.app.exception.ChatMessageException
import me.proxer.app.util.ErrorUtils
import me.proxer.app.util.data.ResettingMutableLiveData
import me.proxer.app.util.extension.safeInject
import me.proxer.app.util.extension.subscribeAndLogErrors
/**
* @author Ruben Gees
*/
class MessengerViewModel(initialConference: LocalConference) : PagedViewModel<LocalMessage>() {
override val itemsOnPage = MessengerWorker.MESSAGES_ON_PAGE
@Suppress("UNUSED_PARAMETER")
override var hasReachedEnd
get() = safeConference.isFullyLoaded
set(value) = Unit
override val data = MediatorLiveData<List<LocalMessage>>()
val conference = MediatorLiveData<LocalConference>()
val draft = ResettingMutableLiveData<String?>()
val deleted = MutableLiveData<Unit?>()
override val dataSingle: Single<List<LocalMessage>>
get() = Single.fromCallable { validators.validateLogin() }
.flatMap {
when (page) {
0 -> messengerDao.markConferenceAsRead(safeConference.id)
else -> if (!hasReachedEnd) MessengerWorker.enqueueMessageLoad(safeConference.id)
}
Single.never()
}
private val dataSource: (List<LocalMessage>?) -> Unit = {
if (it != null && storageHelper.isLoggedIn) {
if (it.isEmpty()) {
if (!hasReachedEnd) {
MessengerWorker.enqueueMessageLoad(safeConference.id)
}
} else {
if (error.value == null) {
dataDisposable?.dispose()
page = it.size / itemsOnPage
isLoading.value = false
error.value = null
data.value = it
Completable.fromAction { messengerDao.markConferenceAsRead(safeConference.id) }
.subscribeOn(Schedulers.io())
.subscribeAndLogErrors()
}
}
}
}
private val conferenceSource: (LocalConference?) -> Unit = {
if (it != null) conference.value = it
else deleted.value = Unit
}
private val messengerDao by safeInject<MessengerDao>()
private val safeConference: LocalConference
get() = requireNotNull(conference.value)
private var draftDisposable: Disposable? = null
init {
conference.value = initialConference
data.addSource(messengerDao.getMessagesLiveDataForConference(initialConference.id), dataSource)
conference.addSource(messengerDao.getConferenceLiveData(initialConference.id), conferenceSource)
disposables += bus.register(MessengerErrorEvent::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { event: MessengerErrorEvent ->
if (event.error is ChatMessageException) {
dataDisposable?.dispose()
isLoading.value = false
error.value = ErrorUtils.handle(event.error)
}
}
}
override fun onCleared() {
draftDisposable?.dispose()
draftDisposable = null
super.onCleared()
}
fun loadDraft() {
draftDisposable?.dispose()
draftDisposable = Single
.fromCallable { storageHelper.getMessageDraft(safeConference.id.toString()).toOptional() }
.filterSome()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { draft.value = it }
}
fun updateDraft(draft: String) {
draftDisposable?.dispose()
draftDisposable = Single
.fromCallable {
if (draft.isBlank()) {
storageHelper.deleteMessageDraft(safeConference.id.toString())
} else {
storageHelper.putMessageDraft(safeConference.id.toString(), draft)
}
}
.subscribeOn(Schedulers.io())
.subscribe()
}
fun sendMessage(text: String) {
val safeUser = requireNotNull(storageHelper.user)
disposables += Single
.fromCallable { messengerDao.insertMessageToSend(safeUser, text, safeConference.id) }
.doOnSuccess { if (!MessengerWorker.isRunning) MessengerWorker.enqueueSynchronization() }
.subscribeOn(Schedulers.io())
.subscribeAndLogErrors()
}
}
| gpl-3.0 | 665dc2f794cb120d67ade136accca6d6 | 34.442177 | 104 | 0.639923 | 5.143139 | false | false | false | false |
appnexus/mobile-sdk-android | tests/AppNexusSDKTestApp/app/src/androidTest/java/appnexus/com/appnexussdktestapp/util/Utility.kt | 1 | 2654 | package appnexus.com.appnexussdktestapp.util
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import org.junit.Assert
import java.lang.ref.WeakReference
import java.util.concurrent.CopyOnWriteArrayList
class Utility {
companion object {
fun checkVisibilityDetectorMap(checkZero: Int, context: Context) {
Handler(Looper.getMainLooper()).post {
val vDetector = Class.forName("com.appnexus.opensdk.VisibilityDetector")
val getInstance = vDetector.getDeclaredMethod("getInstance")
getInstance.isAccessible = true
val viewReference = View(context)
val vDetInst = getInstance.invoke(null)
val addVisibilityListener = vDetector.getDeclaredMethod("addVisibilityListener", View::class.java)
addVisibilityListener.isAccessible = true
addVisibilityListener.invoke(vDetInst, viewReference)
val destroy = vDetector.getDeclaredMethod("destroy", View::class.java)
destroy.isAccessible = true
destroy.invoke(vDetInst, viewReference)
val declaredField = vDetector.getDeclaredField("viewList")
declaredField.isAccessible = true
var list = declaredField.get(vDetInst) as List<Object>
Log.e("VISIBILITY", " Size: ${checkZero} ${list.size}");
Assert.assertEquals(checkZero, list.size)
}
}
fun resetVisibilityDetector() {
Handler(Looper.getMainLooper()).post {
val vDetector = Class.forName("com.appnexus.opensdk.VisibilityDetector")
val getInstance = vDetector.getDeclaredMethod("getInstance")
getInstance.isAccessible = true
val vDetInst = getInstance.invoke(null)
val destroy = vDetector.getDeclaredMethod("destroy", View::class.java)
destroy.isAccessible = true
val declaredField = vDetector.getDeclaredField("viewList")
declaredField.isAccessible = true
var listInstance = declaredField.get(vDetInst)
var list = if (listInstance != null) {
listInstance as List<WeakReference<View>>
} else {
emptyList<WeakReference<View>>()
}
var asyncList = CopyOnWriteArrayList(list)
asyncList.forEach {
destroy.invoke(vDetInst, it.get())
}
}
}
}
} | apache-2.0 | a50acd8d64cd711f69b9631607a2a0c9 | 38.626866 | 114 | 0.609269 | 5.245059 | false | false | false | false |
simonorono/pradera_baja | farmacia/src/main/kotlin/pb/farmacia/window/FormArticulo.kt | 1 | 745 | package pb.farmacia.window
import javafx.fxml.FXMLLoader
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.stage.Stage
import pb.farmacia.controller.FormArticulo
import pb.farmacia.data.Articulo
class FormArticulo(articulo: Articulo?) {
constructor(): this(null)
val stage = Stage()
init {
val loader = FXMLLoader(javaClass.classLoader.getResource("fxml/form_articulo.fxml"))
val root: Parent = loader.load()
val formArticulo = loader.getController<FormArticulo>()
formArticulo.articulo = articulo
val scene = Scene(root)
stage.scene = scene
stage.isResizable = false
stage.title = "Artículo"
}
fun showAndWait() = stage.showAndWait()
}
| apache-2.0 | 3c45a9f96ebde838b32f4b5355d73867 | 25.571429 | 93 | 0.697581 | 3.683168 | false | false | false | false |
DUCodeWars/TournamentFramework | src/main/java/org/DUCodeWars/framework/server/tournament/CombinationStage.kt | 2 | 1796 | package org.DUCodeWars.framework.server.tournament
import org.DUCodeWars.framework.server.AbstractGame
import org.DUCodeWars.framework.server.net.PlayerConnection
import org.DUCodeWars.framework.server.net.server.Server
import org.DUCodeWars.framework.server.shuffle
import org.paukov.combinatorics.Factory
class CombinationStage(val gameCreator: (List<PlayerConnection>, TournamentStage) -> AbstractGame,
val gameSize: Int,
server: Server,
childStage: ChildStage?,
numberOfPlayersProgressing: Int) :
TournamentStage(server = server,
childStage = childStage,
numberOfPlayersProgressing = numberOfPlayersProgressing) {
override fun getGameIterator(players: Set<PlayerConnection>): Iterator<AbstractGame> {
return CombinationStageIterator(gameSize, players, gameCreator, this)
}
override fun toString(): String {
return javaClass.simpleName
}
class CombinationStageIterator(gameSize: Int,
val players: Set<PlayerConnection>,
val gameCreator: (List<PlayerConnection>, TournamentStage) -> AbstractGame,
val tournamentStage: TournamentStage) : Iterator<AbstractGame> {
val playerListIterator = Factory
.createSimpleCombinationGenerator(
Factory.createVector(players.toTypedArray()), gameSize)
.generateAllObjects()
.iterator()
override fun hasNext(): Boolean = playerListIterator.hasNext()
override fun next(): AbstractGame = gameCreator(playerListIterator.next().toList().shuffle(), tournamentStage)
}
} | mit | 8c8de0472e0f04be90a142bdca136415 | 42.829268 | 118 | 0.64588 | 5.560372 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/sdk/datastore/user/Form.kt | 1 | 951 | package mil.nga.giat.mage.sdk.datastore.user
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
@DatabaseTable(tableName = "forms")
class Form {
@DatabaseField(generatedId = true)
var _id: Long? = null
@DatabaseField(canBeNull = false)
var formId: Long = 0
@DatabaseField(canBeNull = false, foreign = true, columnName = COLUMN_NAME_EVENT_ID)
lateinit var event: Event
@DatabaseField
var primaryMapField: String? = null
@DatabaseField
var secondaryMapField: String? = null
@DatabaseField
var primaryFeedField: String? = null
@DatabaseField
var secondaryFeedField: String? = null
@DatabaseField
var style: String? = null
@DatabaseField(canBeNull = false)
lateinit var json: String
companion object {
private const val COLUMN_NAME_EVENT_ID = "event_id"
@JvmStatic
fun getColumnNameEventId(): String = COLUMN_NAME_EVENT_ID
}
} | apache-2.0 | fc49788c40e10d30e2bba3fe881d62a9 | 21.139535 | 87 | 0.709779 | 3.897541 | false | false | false | false |
DUCodeWars/TournamentFramework | src/main/java/org/DUCodeWars/framework/server/net/Server/Server.kt | 2 | 2959 | package org.DUCodeWars.framework.server.net.server
import org.DUCodeWars.framework.server.net.PlayerConnection
import org.DUCodeWars.framework.server.net.packets.notifications.broadcast.BroadcastDrop
import org.DUCodeWars.framework.server.net.packets.notifications.broadcast.BroadcastNotificationDrop
import org.DUCodeWars.framework.server.net.packets.notifications.packets.AliveRequest
import org.DUCodeWars.framework.server.net.packets.notifications.packets.IdRequest
import org.DUCodeWars.framework.server.net.packets.packets.NameRequest
import java.net.ServerSocket
class Server(private val port: Int) {
val connections: MutableSet<PlayerConnection> = mutableSetOf()
internal val serverSocket = ServerSocket(port)
private val gui = ServerGUI()
private val acceptorThread = AcceptorThread(this, gui, connections)
/**
* Start the [acceptorThread], allowing new connections to the [serverSocket]
*/
fun startAccepting() {
acceptorThread.start()
}
fun guiAcceptor() {
startAccepting()
gui.showBlocking()
stopAccepting()
}
/**
* Stop the [acceptorThread], disallowing new connections to the [serverSocket]
*/
fun stopAccepting() {
acceptorThread.interrupt()
DeadSocket("127.0.0.1", port)
//We add this so that the socket.accept() call in AcceptorThread will stop blocking,
//so the while loop condition will be evaluated. If we didn't add this,
//the server would still accept one more client after we stopped accepting.
}
/**
* Removes all dead connections from [connections]
*/
fun validateClients() {
BroadcastNotificationDrop(this, connections, AliveRequest()).send()
}
fun idClients() {
BroadcastNotificationDrop(
server = this,
connections = connections,
requestCreator = { connection ->
IdRequest(connection.playerId)
}
).send()
}
fun nameClients() {
BroadcastDrop(
server = this,
connections = connections,
request = NameRequest(),
responseHandler = { connection, _, response ->
connection.name = "${response.name} by ${response.creator}"
}
).send()
}
fun shutdown() {
//By closing the server sockets all client sockets will close too
serverSocket.close()
}
fun initialiseConnections() {
guiAcceptor()
validateClients()
idClients()
nameClients()
}
fun dropConnection(connection: PlayerConnection, reason: Exception) {
connection.socket.close()
connections.remove(connection)
gui.remove(connection)
println("Closed connection $connection, violated spec")
reason.printStackTrace()
}
} | mit | 21e34c348b9e50d6c4aa7c6a1bdd6fd9 | 30.157895 | 100 | 0.639743 | 4.923461 | false | false | false | false |
sta-szek/squash-zg | src/main/kotlin/pl/pojo/squash/zg/api/UsersApiDoc.kt | 1 | 993 | package pl.pojo.squash.zg.api
import io.swagger.annotations.Api
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.context.request.async.DeferredResult
import pl.pojo.squash.zg.model.User
@Api(consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
tags = arrayOf("users")
)
interface UsersApiDoc {
@ApiResponses(
ApiResponse(code = 200, message = "List of users"),
ApiResponse(code = 204, message = "Empty list")
)
fun getAllUsers(): DeferredResult<Iterable<User>>
@ApiResponses(
ApiResponse(code = 201, message = "User created"),
ApiResponse(code = 409, message = "User with given email already exist")
)
fun createUser(@RequestBody createUserBody: CreateUserBody): DeferredResult<User>
} | gpl-3.0 | 84afe0e1d122404c0711bd2f73fd6052 | 33.275862 | 85 | 0.72709 | 4.172269 | false | false | false | false |
mallowigi/a-file-icon-idea | common/src/main/java/com/mallowigi/tree/ArrowIconsComponent.kt | 1 | 3537 | /*
* 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.tree
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.plugins.DynamicPluginListener
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.ui.LafManagerListener
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.mallowigi.config.AtomFileIconsConfig.Companion.instance
import com.mallowigi.config.listeners.AtomConfigNotifier
import javax.swing.SwingUtilities
import javax.swing.UIManager
/** Arrow icons component: replace arrows. */
class ArrowIconsComponent : DynamicPluginListener, AppLifecycleListener {
/** Dispose on app closing. */
override fun appClosing(): Unit = disposeComponent()
/** Init on app started. */
override fun appStarted(): Unit = initComponent()
/** Init on plugin loaded. */
override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor): Unit = initComponent()
/** Dispose on plugin unloaded. */
override fun pluginUnloaded(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean): Unit = disposeComponent()
private fun disposeComponent() = ApplicationManager.getApplication().messageBus.connect().disconnect()
private fun initComponent() {
replaceArrowIcons()
val connect = ApplicationManager.getApplication().messageBus.connect()
connect.run {
subscribe(AtomConfigNotifier.TOPIC, AtomConfigNotifier { replaceArrowIcons() })
subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(project: Project) = replaceArrowIcons()
})
subscribe(LafManagerListener.TOPIC, LafManagerListener { replaceArrowIcons() })
}
}
private fun replaceArrowIcons() {
val defaults = UIManager.getLookAndFeelDefaults()
val arrowsStyle = instance.arrowsStyle
defaults["Tree.collapsedIcon"] = arrowsStyle.expandIcon
defaults["Tree.expandedIcon"] = arrowsStyle.collapseIcon
defaults["Tree.collapsedSelectedIcon"] = arrowsStyle.selectedExpandIcon
defaults["Tree.expandedSelectedIcon"] = arrowsStyle.selectedCollapseIcon
SwingUtilities.invokeLater { ActionToolbarImpl.updateAllToolbarsImmediately() }
}
}
| mit | 86125284f753f38286f36870a7d03e72 | 43.2125 | 115 | 0.776364 | 4.799186 | false | true | false | false |
devknightz/MinimalWeatherApp | app/src/main/java/you/devknights/minimalweather/network/ApiResponse.kt | 1 | 3261 | /*
* Copyright 2017 vinayagasundar
* Copyright 2017 randhirgupta
*
* 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 you.devknights.minimalweather.network
import android.support.v4.util.ArrayMap
import java.io.IOException
import java.util.Collections
import java.util.regex.Matcher
import java.util.regex.Pattern
import retrofit2.Response
/**
* Common class used by API responses.
*
* @param <T>
</T> */
class ApiResponse<T> {
val code: Int
val body: T?
val errorMessage: String?
val links: MutableMap<String, String>
val isSuccessful: Boolean
get() = code >= 200 && code < 300
// Timber.w("cannot parse next page from %s", next);
val nextPage: Int?
get() {
val next = links[NEXT_LINK] ?: return null
val matcher = PAGE_PATTERN.matcher(next)
if (!matcher.find() || matcher.groupCount() != 1) {
return null
}
try {
return Integer.parseInt(matcher.group(1))
} catch (ex: NumberFormatException) {
return null
}
}
constructor(error: Throwable) {
code = 500
body = null
errorMessage = error.message
links = mutableMapOf()
}
constructor(response: Response<T>) {
code = response.code()
if (response.isSuccessful) {
body = response.body()
errorMessage = null
} else {
var message: String? = null
if (response.errorBody() != null) {
try {
message = response.errorBody()?.string()
} catch (ignored: IOException) {
// Timber.e(ignored, "error while parsing response");
}
}
if (message == null || message.trim { it <= ' ' }.length == 0) {
message = response.message()
}
errorMessage = message
body = null
}
val linkHeader = response.headers().get("link")
if (linkHeader == null) {
links = mutableMapOf()
} else {
links = ArrayMap()
val matcher = LINK_PATTERN.matcher(linkHeader)
while (matcher.find()) {
val count = matcher.groupCount()
if (count == 2) {
links[matcher.group(2)] = matcher.group(1)
}
}
}
}
companion object {
private val LINK_PATTERN = Pattern
.compile("<([^>]*)>[\\s]*;[\\s]*rel=\"([a-zA-Z0-9]+)\"")
private val PAGE_PATTERN = Pattern.compile("\\bpage=(\\d+)")
private val NEXT_LINK = "next"
}
} | apache-2.0 | 491391cebcc5aab668b3e93fada9938f | 28.926606 | 92 | 0.547991 | 4.442779 | false | false | false | false |
EyeBody/EyeBody | EyeBody2/app/src/main/java/com/example/android/eyebody/MainActivity.kt | 1 | 9076 | package com.example.android.eyebody
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import com.example.android.eyebody.dialog.EnterGalleryDialog
import com.example.android.eyebody.init.InitActivity
import com.example.android.eyebody.camera.CameraActivity
import com.example.android.eyebody.gallery.GalleryActivity
import io.vrinda.kotlinpermissions.PermissionCallBack
import io.vrinda.kotlinpermissions.PermissionsActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : PermissionsActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
checkSMSPermission()
//TODO : 문자내역을 가져오기 위한 통화내역 읽어오기 read_SMS 퍼미션.
//TODO : 문자내역을 가져오기 위한 통화내역 읽어오기 read_SMS 퍼미션.
fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.menu_sel, menu)
return true
}
fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.btn_activity_func2) {
val settingPage = Intent(this, SettingActivity::class.java)
startActivity(settingPage)
}
return super.onOptionsItemSelected(item)
}
// TODO ----- 바탕화면에 toggle icon?? 형식으로 간단하게 클릭만으로 메인 액티비티를 접근할 수 있게 설정하기 (백그라운드?)
// TODO ----- 메모리 릭 문제 해결 (점점 메모리 사용량이 증가한다.)
/* lazy initializing (지연 선언)
해당 변수를 사용하기 바로 직전에 부르기 때문에 처음 실행시 과부하가 적음.
***리스너에 넣으면 매번 Intent 함수를 사용하기 때문에 부하가 심할 거 같은데
이렇게하면 속도가 빨라지는 효과가 있는지는 모르겠다.***
*/
val cameraPage by lazy { Intent(this, CameraActivity::class.java) }
val exercisePage by lazy { Intent(this, ExerciseActivity::class.java) }
val settingPage by lazy { Intent(this, SettingActivity::class.java) }
val galleryPage by lazy { Intent(this, GalleryActivity::class.java) }
/* Listener (이벤트 리스너)
클릭하면 반응
*/
fun checkCAMERAPermission(): Boolean {
var result: Int = ContextCompat.checkSelfPermission(applicationContext, android.Manifest.permission.CAMERA)
return result == PackageManager.PERMISSION_GRANTED
}
btn_activity_photo.setOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!checkCAMERAPermission()) {
requestPermissions(arrayOf(android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE), object : PermissionCallBack {
override fun permissionGranted() {
super.permissionGranted()
startActivity(cameraPage)
Log.v("Camera permissions", "Granted")
}
override fun permissionDenied() {
super.permissionDenied()
Log.v("Camera permissions", "Denied")
}
})
} else startActivity(cameraPage)
} else startActivity(cameraPage)
}
btn_activity_gallery.setOnClickListener {
val sharedPref: SharedPreferences = getSharedPreferences(
getString(R.string.getSharedPreference_initSetting), Context.MODE_PRIVATE)
val sharedPref_hashedPW = sharedPref.getString(
getString(R.string.sharedPreference_hashedPW), getString(R.string.sharedPreference_default_hashedPW))
if (sharedPref_hashedPW == getString(R.string.sharedPreference_default_hashedPW)) {
Log.d("mydbg_main", "SharedPreferences.isSetting is false or null / hacked or 유저가 앱 실행 중 데이터를 지운 경우")
Toast.makeText(this, "에러 : 초기비밀번호가 설정되어있지 않습니다.", Toast.LENGTH_LONG).show()
} else {
val enterGalleryDialog = EnterGalleryDialog()
enterGalleryDialog.show(fragmentManager, "enter_gallery")
//overridePendingTransition(0,0)
}
}
btn_activity_func1.setOnClickListener {
startActivity(exercisePage)
}
btn_activity_func2.setOnClickListener {
startActivity(settingPage)
finish()
}
}
private fun checkSMSPReadPermission(): Boolean {
var result: Int = ContextCompat.checkSelfPermission(applicationContext, android.Manifest.permission.READ_SMS)
return result == PackageManager.PERMISSION_GRANTED
}
private fun checkSMSReceivePermission():Boolean{
var result:Int=ContextCompat.checkSelfPermission(applicationContext,android.Manifest.permission.RECEIVE_SMS)
return result==PackageManager.PERMISSION_GRANTED
}
private fun checkCAMERAPermission(): Boolean {
var result: Int = ContextCompat.checkSelfPermission(applicationContext, android.Manifest.permission.CAMERA)
return result == PackageManager.PERMISSION_GRANTED
}
private fun checkSMSPermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!checkSMSPReadPermission() || !checkSMSReceivePermission()) {
requestPermissions(arrayOf(android.Manifest.permission.READ_SMS, android.Manifest.permission.RECEIVE_SMS), object : PermissionCallBack {
override fun permissionGranted() {
super.permissionGranted()
}
override fun permissionDenied() {
super.permissionDenied()
}
})
}
}
}
/* onCreateOptionMenu
액션바에 옵션메뉴를 띄우게 함. xml 긁어서
*/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.menu_sel, menu)
return true
}
/* onOptionItemSelected
옵션메뉴에서 아이템이 선택됐을 때 발생하는 이벤트
*/
@SuppressLint("ApplySharedPref")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// TODO ----- 아예 싹 갈아 없고 네비게이션 뷰 구성하기" - fun onCreateOptionMenu 와 onOptionSelected 를 엎어야 함.
val id by lazy { item.itemId }
val toast by lazy { Toast.makeText(this, "", Toast.LENGTH_SHORT) }
when (id) {
// TODO ----- intent 전환효과 바꾸기 :: overridePendingTransition(int, int) / xml 파일 같이 쓰면 더 예쁘게 가능.
// 사진찍기 같은 경우 드래그로 동그란거 샤악~ ????
R.id.Actionbar_Reset -> {
// init 으로 감 (sharedPreference가 채워져 있으면 init에서 저절로 main으로 오므로 clear작업을 해줌)
// debug용임.
getSharedPreferences(getString(R.string.getSharedPreference_initSetting), Context.MODE_PRIVATE)
.edit()
.clear()
.commit()
val initActivityIntent = Intent(this, InitActivity::class.java)
startActivity(initActivityIntent)
finish()
}
R.id.Actionbar_PWmodify -> {
// TODO ----- 비밀번호 수정에 대하여 새로운 액티비티 구성
toast.setText("TODO : pw modify")
toast.show()
}
R.id.Actionbar_PWfind -> {
// TODO ----- 비밀번호 찾기에 대하여 새로운 액티비티 구성
toast.setText("TODO : pw find")
toast.show()
}
R.id.Actionbar_reDesire -> {
// TODO ----- 목표 설정에 대하여 새로운 액티비티 구성
toast.setText("TODO : re Desire")
toast.show()
}
R.id.Actionbar_AlarmSetting -> {
// TODO ----- 알람 세팅에 대하여 새로운 액티비티 구성
toast.setText("TODO : Alarm Setting")
toast.show()
}
}
return super.onOptionsItemSelected(item)
}
}
| mit | 7cb61b7a4249f0c85867ec7686afafda | 39.623762 | 165 | 0.604436 | 4.028473 | false | false | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/backup/BackupCreatorJob.kt | 1 | 1914 | package eu.kanade.tachiyomi.data.backup
import android.content.Context
import androidx.core.net.toUri
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import eu.kanade.tachiyomi.data.backup.full.FullBackupManager
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.concurrent.TimeUnit
class BackupCreatorJob(private val context: Context, workerParams: WorkerParameters) :
Worker(context, workerParams) {
override fun doWork(): Result {
val preferences = Injekt.get<PreferencesHelper>()
val uri = preferences.backupsDirectory().get().toUri()
val flags = BackupCreateService.BACKUP_ALL
return try {
FullBackupManager(context).createBackup(uri, flags, true)
Result.success()
} catch (e: Exception) {
Result.failure()
}
}
companion object {
private const val TAG = "BackupCreator"
fun setupTask(context: Context, prefInterval: Int? = null) {
val preferences = Injekt.get<PreferencesHelper>()
val interval = prefInterval ?: preferences.backupInterval().get()
if (interval > 0) {
val request = PeriodicWorkRequestBuilder<BackupCreatorJob>(
interval.toLong(),
TimeUnit.HOURS,
10,
TimeUnit.MINUTES
)
.addTag(TAG)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.REPLACE, request)
} else {
WorkManager.getInstance(context).cancelAllWorkByTag(TAG)
}
}
}
}
| apache-2.0 | 77b0e47584cc6da70b87ee99200f2ac3 | 35.113208 | 124 | 0.652038 | 5.131367 | false | false | false | false |
unbroken-dome/gradle-testsets-plugin | src/main/kotlin/org/unbrokendome/gradle/plugins/testsets/dsl/PredefinedUnitTestSet.kt | 1 | 944 | package org.unbrokendome.gradle.plugins.testsets.dsl
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.tasks.SourceSet
import org.gradle.testing.jacoco.plugins.JacocoPlugin
internal class PredefinedUnitTestSet(container: TestSetContainer, sourceSet: SourceSet)
: AbstractTestSetBase(container, "unitTest", sourceSet), TestSet {
override val testTaskName: String
get() = JavaPlugin.TEST_TASK_NAME
override val jarTaskName: String
get() = "testJar"
override var classifier: String = "tests"
override var environment: Map<String, Any> = mutableMapOf()
set(value) {
field = value
notifyObservers { it.environmentVariablesChanged(this, value) }
}
override var systemProperties: Map<String, Any?> = mutableMapOf()
set(value) {
field = value
notifyObservers { it.systemPropertiesChanged(this, value) }
}
}
| mit | 193d79866ca6158a06eaf781f382a220 | 26.764706 | 87 | 0.686441 | 4.516746 | false | true | false | false |
mrebollob/LoteriadeNavidad | shared/src/commonMain/kotlin/com/mrebollob/loteria/di/Koin.kt | 1 | 1424 | package com.mrebollob.loteria.di
import com.mrebollob.loteria.data.SettingsRepositoryImp
import com.mrebollob.loteria.data.TicketsRepositoryImp
import com.mrebollob.loteria.data.mapper.TicketMapper
import com.mrebollob.loteria.data.preferences.Preferences
import com.mrebollob.loteria.domain.repository.SettingsRepository
import com.mrebollob.loteria.domain.repository.TicketsRepository
import com.mrebollob.loteria.domain.usecase.GetDaysToLotteryDraw
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import org.koin.core.context.startKoin
import org.koin.dsl.KoinAppDeclaration
import org.koin.dsl.module
fun initKoin(enableNetworkLogs: Boolean = false, appDeclaration: KoinAppDeclaration = {}) =
startKoin {
appDeclaration()
modules(commonModule(enableNetworkLogs = enableNetworkLogs), platformModule())
}
// called by iOS etc
fun initKoin() = initKoin(enableNetworkLogs = false) {}
fun commonModule(enableNetworkLogs: Boolean) = module {
single { CoroutineScope(Dispatchers.Default + SupervisorJob()) }
// Preferences
single { Preferences("lottery_app") }
// Repository
single<TicketsRepository> { TicketsRepositoryImp(get(), get()) }
single<SettingsRepository> { SettingsRepositoryImp(get()) }
// Use case
single { GetDaysToLotteryDraw() }
// Mapper
single { TicketMapper() }
}
| apache-2.0 | e9173d51e5b3d14332fe2c737c3b5a47 | 33.731707 | 91 | 0.780197 | 4.381538 | false | false | false | false |
sephiroth74/Material-BottomNavigation | bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/BottomBehavior.kt | 1 | 12874 | package it.sephiroth.android.library.bottomnavigation
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.util.Log.VERBOSE
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup.MarginLayoutParams
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import androidx.core.view.ViewPropertyAnimatorCompat
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator
import com.google.android.material.snackbar.Snackbar.SnackbarLayout
import it.sephiroth.android.library.bottomnavigation.BottomNavigation.Companion.PENDING_ACTION_ANIMATE_ENABLED
import it.sephiroth.android.library.bottomnavigation.BottomNavigation.Companion.PENDING_ACTION_NONE
import it.sephiroth.android.library.bottonnavigation.R
import timber.log.Timber
/**
* Created by alessandro crugnola on 4/2/16.
* [email protected]
*/
open class BottomBehavior constructor(context: Context, attrs: AttributeSet) :
VerticalScrollingBehavior<BottomNavigation>(context, attrs) {
var isScrollable: Boolean = false
private val scrollEnabled: Boolean
private var enabled: Boolean = false
/**
* show/hide animation duration
*/
private val animationDuration: Int
/**
* bottom inset when TRANSLUCENT_NAVIGATION is turned on
*/
private var bottomInset: Int = 0
/**
* bottom navigation real height
*/
private var height: Int = 0
/**
* maximum scroll offset
*/
private var maxOffset: Int = 0
/**
* true if the current configuration has the TRANSLUCENT_NAVIGATION turned on
*/
private var translucentNavigation: Boolean = false
/**
* Minimum touch distance
*/
private val scaledTouchSlop: Int
/**
* hide/show animator
*/
private var animator: ViewPropertyAnimatorCompat? = null
/**
* current visibility status
*/
private var hidden = false
/**
* current Y offset
*/
private var offset: Int = 0
private var listener: OnExpandStatusChangeListener? = null
protected var snackbarDependentView: SnackBarDependentView? = null
val isExpanded: Boolean
get() = !hidden
init {
val array = context.obtainStyledAttributes(attrs, R.styleable.BottomNavigationBehavior)
this.isScrollable = array.getBoolean(R.styleable.BottomNavigationBehavior_bbn_scrollEnabled, true)
this.scrollEnabled = true
this.animationDuration =
array.getInt(R.styleable.BottomNavigationBehavior_bbn_animationDuration, context.resources.getInteger(R.integer.bbn_hide_animation_duration))
this.scaledTouchSlop = ViewConfiguration.get(context).scaledTouchSlop * 2
this.offset = 0
array.recycle()
Timber.v("scrollable: $isScrollable, duration: $animationDuration, touchSlop: $scaledTouchSlop")
}
fun setOnExpandStatusChangeListener(listener: OnExpandStatusChangeListener) {
this.listener = listener
}
fun setLayoutValues(bottomNavHeight: Int, bottomInset: Int) {
Timber.v("setLayoutValues($bottomNavHeight, $bottomInset)")
this.height = bottomNavHeight
this.bottomInset = bottomInset
this.translucentNavigation = bottomInset > 0
this.maxOffset = height + if (translucentNavigation) bottomInset else 0
this.enabled = true
Timber.v("height: $height, translucent: $translucentNavigation, maxOffset: $maxOffset, bottomInset: $bottomInset")
}
override fun layoutDependsOn(parent: CoordinatorLayout, child: BottomNavigation, dependency: View): Boolean {
Timber.v("layoutDependsOn: $dependency")
return if (!enabled) {
false
} else isSnackbar(dependency)
}
private fun isSnackbar(view: View): Boolean {
return view is SnackbarLayout
}
override fun onLayoutChild(parent: CoordinatorLayout, abl: BottomNavigation, layoutDirection: Int): Boolean {
val handled = super.onLayoutChild(parent, abl, layoutDirection)
val pendingAction = abl.pendingAction
if (pendingAction != PENDING_ACTION_NONE) {
val animate = pendingAction and PENDING_ACTION_ANIMATE_ENABLED != 0
if (pendingAction and BottomNavigation.PENDING_ACTION_COLLAPSED != 0) {
setExpanded(parent, abl, false, animate)
} else {
if (pendingAction and BottomNavigation.PENDING_ACTION_EXPANDED != 0) {
setExpanded(parent, abl, true, animate)
}
}
// Finally reset the pending state
abl.resetPendingAction()
}
return handled
}
override fun onDependentViewRemoved(parent: CoordinatorLayout, child: BottomNavigation, dependency: View) {
if (isSnackbar(dependency)) {
if (null != snackbarDependentView) {
snackbarDependentView!!.onDestroy()
}
snackbarDependentView = null
}
}
override fun onDependentViewChanged(parent: CoordinatorLayout, child: BottomNavigation, dependency: View): Boolean {
if (isSnackbar(dependency)) {
if (null == snackbarDependentView) {
snackbarDependentView = SnackBarDependentView(dependency as SnackbarLayout, height, bottomInset)
}
return snackbarDependentView!!.onDependentViewChanged(parent, child)
}
return super.onDependentViewChanged(parent, child, dependency)
}
override fun onStartNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: BottomNavigation,
directTargetChild: View, target: View,
nestedScrollAxes: Int, @ViewCompat.NestedScrollType type: Int): Boolean {
offset = 0
if (!isScrollable || !scrollEnabled) {
return false
}
if (nestedScrollAxes and ViewCompat.SCROLL_AXIS_VERTICAL != 0) {
Timber.v("isScrollContainer: ${target.isScrollContainer}, canScrollUp: ${target.canScrollVertically(-1)}, canScrollDown: ${target.canScrollVertically(1)}")
if (target.isScrollContainer && !target.canScrollVertically(-1) && !target.canScrollVertically(1)) {
return false
}
}
return super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes, type)
}
override fun onStopNestedScroll(
coordinatorLayout: CoordinatorLayout, child: BottomNavigation, target: View,
@ViewCompat.NestedScrollType type: Int) {
super.onStopNestedScroll(coordinatorLayout, child, target, type)
offset = 0
}
override fun onDirectionNestedPreScroll(
coordinatorLayout: CoordinatorLayout,
child: BottomNavigation,
target: View, dx: Int, dy: Int, consumed: IntArray,
@ScrollDirection scrollDirection: Int) {
// stop nested scroll if target is not scrollable
// FIXME: not yet verified
if (target.isScrollContainer && !target.canScrollVertically(scrollDirection)) {
Timber.w("stopNestedScroll")
ViewCompat.stopNestedScroll(target)
}
offset += dy
if (BottomNavigation.DEBUG) {
Timber.v("onDirectionNestedPreScroll($scrollDirection, $target, ${target.canScrollVertically(scrollDirection)})")
}
if (offset > scaledTouchSlop) {
handleDirection(coordinatorLayout, child, VerticalScrollingBehavior.ScrollDirection.SCROLL_DIRECTION_UP)
offset = 0
} else if (offset < -scaledTouchSlop) {
handleDirection(coordinatorLayout, child, VerticalScrollingBehavior.ScrollDirection.SCROLL_DIRECTION_DOWN)
offset = 0
}
}
override fun onNestedDirectionFling(
coordinatorLayout: CoordinatorLayout, child: BottomNavigation, target: View, velocityX: Float, velocityY: Float,
@ScrollDirection scrollDirection: Int): Boolean {
Timber.v("onNestedDirectionFling($velocityY, $scrollDirection)")
if (Math.abs(velocityY) > 1000) {
handleDirection(coordinatorLayout, child, scrollDirection)
}
return true
}
override fun onNestedVerticalOverScroll(
coordinatorLayout: CoordinatorLayout, child: BottomNavigation, @ScrollDirection direction: Int, currentOverScroll: Int,
totalOverScroll: Int) {
}
private fun handleDirection(coordinatorLayout: CoordinatorLayout, child: BottomNavigation, scrollDirection: Int) {
if (!enabled || !isScrollable || !scrollEnabled) {
return
}
if (scrollDirection == VerticalScrollingBehavior.ScrollDirection.SCROLL_DIRECTION_DOWN && hidden) {
setExpanded(coordinatorLayout, child, true, true)
} else if (scrollDirection == VerticalScrollingBehavior.ScrollDirection.SCROLL_DIRECTION_UP && !hidden) {
setExpanded(coordinatorLayout, child, false, true)
}
}
protected fun setExpanded(
coordinatorLayout: CoordinatorLayout, child: BottomNavigation, expanded: Boolean, animate: Boolean) {
Timber.v("setExpanded($expanded)")
animateOffset(coordinatorLayout, child, if (expanded) 0 else maxOffset, animate)
listener?.onExpandStatusChanged(expanded, animate)
}
private fun animateOffset(
coordinatorLayout: CoordinatorLayout,
child: BottomNavigation,
offset: Int,
animate: Boolean) {
Timber.v("animateOffset($offset)")
hidden = offset != 0
ensureOrCancelAnimator(coordinatorLayout, child)
if (animate) {
animator?.translationY(offset.toFloat())?.start()
} else {
child.translationY = offset.toFloat()
}
}
@Suppress("UNUSED_PARAMETER")
private fun ensureOrCancelAnimator(coordinatorLayout: CoordinatorLayout, child: BottomNavigation) {
if (animator == null) {
animator = ViewCompat.animate(child)
animator!!.duration = animationDuration.toLong()
animator!!.interpolator = INTERPOLATOR
} else {
animator!!.cancel()
}
}
abstract class DependentView<V : View> internal constructor(protected val child: V, protected var height: Int,
protected val bottomInset: Int) {
protected val layoutParams: MarginLayoutParams = child.layoutParams as MarginLayoutParams
protected val bottomMargin: Int
protected val originalPosition: Float = child.translationY
init {
this.bottomMargin = layoutParams.bottomMargin
}
protected open fun onDestroy() {
layoutParams.bottomMargin = bottomMargin
child.translationY = originalPosition
child.requestLayout()
}
internal abstract fun onDependentViewChanged(parent: CoordinatorLayout, navigation: BottomNavigation): Boolean
}
class SnackBarDependentView internal constructor(child: SnackbarLayout, height: Int,
bottomInset: Int) : DependentView<SnackbarLayout>(child, height, bottomInset) {
@Suppress("SpellCheckingInspection")
private var snackbarHeight = -1
override fun onDependentViewChanged(parent: CoordinatorLayout, navigation: BottomNavigation): Boolean {
Timber.v("onDependentViewChanged")
if (Build.VERSION.SDK_INT < 21) {
val index1 = parent.indexOfChild(child)
val index2 = parent.indexOfChild(navigation)
if (index1 > index2) {
MiscUtils.log(VERBOSE, "swapping children")
navigation.bringToFront()
}
} else {
}
if (snackbarHeight == -1) {
snackbarHeight = child.height
}
val maxScroll = Math.max(0f, navigation.translationY - bottomInset)
val newBottomMargin = (height + bottomInset - maxScroll).toInt()
if (layoutParams.bottomMargin != newBottomMargin) {
layoutParams.bottomMargin = newBottomMargin
child.requestLayout()
return true
}
return false
}
public override fun onDestroy() {
super.onDestroy()
}
}
interface OnExpandStatusChangeListener {
fun onExpandStatusChanged(expanded: Boolean, animate: Boolean)
}
companion object {
/**
* default hide/show interpolator
*/
private val INTERPOLATOR = LinearOutSlowInInterpolator()
}
} | mit | 143eff3d58ecf1d80027f1456fc71ddf | 36.103746 | 167 | 0.656206 | 5.317637 | false | false | false | false |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/kotlin/KSExpectActualImpl.kt | 1 | 2476 | /*
* 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.impl.kotlin
import com.google.devtools.ksp.processing.impl.ResolverImpl
import com.google.devtools.ksp.processing.impl.findActualsInKSDeclaration
import com.google.devtools.ksp.processing.impl.findExpectsInKSDeclaration
import com.google.devtools.ksp.symbol.KSDeclaration
import com.google.devtools.ksp.symbol.KSExpectActual
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier
class KSExpectActualImpl(val declaration: KtDeclaration) : KSExpectActual {
/**
* "All actual declarations that match any part of an expected declaration need to be marked as actual."
*/
override val isActual: Boolean = declaration.hasActualModifier()
private fun KtDeclaration.isExpect(): Boolean = hasExpectModifier() || containingClassOrObject?.isExpect() == true
override val isExpect: Boolean = declaration.isExpect()
private val expects: Sequence<KSDeclaration> by lazy {
descriptor?.findExpectsInKSDeclaration() ?: emptySequence()
}
override fun findExpects(): Sequence<KSDeclaration> {
if (!isActual)
return emptySequence()
return expects
}
private val actuals: Sequence<KSDeclaration> by lazy {
descriptor?.findActualsInKSDeclaration() ?: emptySequence()
}
override fun findActuals(): Sequence<KSDeclaration> {
if (!isExpect)
return emptySequence()
return actuals
}
private val descriptor: DeclarationDescriptor? by lazy {
ResolverImpl.instance!!.resolveDeclaration(declaration)
}
}
| apache-2.0 | 8e8888d5075ee5fdde0a24d64d993413 | 37.6875 | 118 | 0.754039 | 4.743295 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/editor/resources/GitHubCollapseInCommentScriptProvider.kt | 1 | 1689 | // 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.resources
import com.vladsch.md.nav.MdBundle
import com.vladsch.md.nav.editor.javafx.JavaFxHtmlPanelProvider
import com.vladsch.md.nav.editor.util.HtmlCssResource
import com.vladsch.md.nav.editor.util.HtmlScriptResource
import com.vladsch.md.nav.editor.util.HtmlScriptResourceProvider
import com.vladsch.md.nav.settings.MdPreviewSettings
import org.intellij.lang.annotations.Language
object GitHubCollapseInCommentScriptProvider : HtmlScriptResourceProvider() {
val NAME = MdBundle.message("editor.github-collapse-in-comment.html.script.provider.name")
val ID = "com.vladsch.md.nav.editor.github-collapse-in-comment.html.script"
override val HAS_PARENT = false
override val INFO = HtmlScriptResourceProvider.Info(ID, NAME)
override val COMPATIBILITY = JavaFxHtmlPanelProvider.COMPATIBILITY
@Language("HTML")
override val scriptResource: HtmlScriptResource = GitHubCollapseInCommentsScriptResource(INFO, "", """
<script>
(function() {
var elemList = window.document.getElementsByTagName("details");
for (var i = 0; i < elemList.length; i++) {
elemList[i].setAttribute('open','');
}
})();
</script>
""")
override val cssResource: HtmlCssResource? = null
override fun isSupportedSetting(settingName: String): Boolean {
return when (settingName) {
MdPreviewSettings.PERFORMANCE_WARNING -> false
MdPreviewSettings.EXPERIMENTAL_WARNING -> false
else -> false
}
}
}
| apache-2.0 | e71cd244cb96f758c20f93a082ecfa16 | 40.195122 | 177 | 0.745411 | 4.06988 | false | false | false | false |
MyDogTom/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/internal/McCabeVisitor.kt | 1 | 1844 | package io.gitlab.arturbosch.detekt.api.internal
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtLoopExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtTryExpression
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.psiUtil.getCallNameExpression
/**
* @author Artur Bosch
*/
class McCabeVisitor : DetektVisitor() {
var mcc = 0
private fun inc() {
mcc++
}
override fun visitNamedFunction(function: KtNamedFunction) {
inc()
super.visitNamedFunction(function)
}
override fun visitIfExpression(expression: KtIfExpression) {
inc()
if (expression.`else` != null) {
inc()
}
super.visitIfExpression(expression)
}
override fun visitLoopExpression(loopExpression: KtLoopExpression) {
inc()
super.visitLoopExpression(loopExpression)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
mcc += expression.entries.size
super.visitWhenExpression(expression)
}
override fun visitTryExpression(expression: KtTryExpression) {
inc()
mcc += expression.catchClauses.size
expression.finallyBlock?.let { inc() }
super.visitTryExpression(expression)
}
override fun visitCallExpression(expression: KtCallExpression) {
if (expression.isUsedForNesting()) {
val lambdaArguments = expression.lambdaArguments
if (lambdaArguments.size > 0) {
val lambdaArgument = lambdaArguments[0]
lambdaArgument.getLambdaExpression().bodyExpression?.let {
inc()
}
}
}
super.visitCallExpression(expression)
}
}
fun KtCallExpression.isUsedForNesting(): Boolean = when (getCallNameExpression()?.text) {
"run", "let", "apply", "with", "use", "forEach" -> true
else -> false
}
| apache-2.0 | e8c411147736fd0cbdf1fa8e57ca70ae | 25.342857 | 89 | 0.760846 | 4.017429 | false | false | false | false |
yuyashuai/SurfaceViewFrameAnimation | frameanimation/src/main/java/com/yuyashuai/frameanimation/FrameAnimation.kt | 1 | 15503 | package com.yuyashuai.frameanimation
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.RectF
import android.os.Handler
import android.os.SystemClock
import android.util.Log
import android.view.SurfaceView
import android.view.TextureView
import android.view.View
import com.yuyashuai.frameanimation.drawer.BitmapDrawer
import com.yuyashuai.frameanimation.drawer.SurfaceViewBitmapDrawer
import com.yuyashuai.frameanimation.drawer.TextureBitmapDrawer
import com.yuyashuai.frameanimation.io.AnimationInteractionListener
import com.yuyashuai.frameanimation.io.DefaultBitmapPool
import com.yuyashuai.frameanimation.repeatmode.*
import java.io.File
import kotlin.concurrent.thread
/**
* @author yuyashuai 2019-04-25.
*/
open class FrameAnimation private constructor(
private var mTextureView: TextureView?,
private var mSurfaceView: SurfaceView?,
private var isTextureViewMode: Boolean?,
private val mContext: Context) : AnimationController, AnimationInteractionListener {
constructor(surfaceView: SurfaceView) : this(null, surfaceView, false, surfaceView.context)
constructor(textureView: TextureView) : this(textureView, null, true, textureView.context)
constructor(context: Context) : this(null, null, null, context)
private lateinit var mBitmapDrawer: BitmapDrawer
private val TAG = javaClass.simpleName
private val mBitmapPool = DefaultBitmapPool(mContext).apply {
setInteractionListener(this@FrameAnimation)
}
/**
* Indicates whether the animation is playing
*/
@Volatile
private var isPlaying = false
/**
* Milliseconds interval between two frames
* 42ms≈24fps
*/
private var frameInterval = 42
/**
* The thread responsible for drawing
*/
private var drawThread: Thread? = null
private var relayDraw = false
private var mRepeatStrategy: RepeatStrategy = RepeatOnce()
/**
* Whether to clear the view when the animation finished
* if false the view will display the last frame
*/
private var clearViewAfterStop = true
private val MSG_STOP = 0X01
private val MSG_ANIMATION_START = 0X02
private val mHandler = Handler(Handler.Callback { msg ->
if (msg.what == MSG_STOP) {
stopAnimation()
} else if (msg.what == MSG_ANIMATION_START) {
animationListener?.onAnimationStart()
}
return@Callback true
})
/**
* support the reuse of bitmap
* Turn off this option if the picture resolution is inconsistent
*/
private var supportInBitmap = true
/**
* the animation drawing frame index
*/
private var drawIndex = 0
init {
if (isTextureViewMode == true) {
mBitmapDrawer = TextureBitmapDrawer(mTextureView!!)
} else if (isTextureViewMode == false) {
mBitmapDrawer = SurfaceViewBitmapDrawer(mSurfaceView!!)
}
}
override fun isPlaying(): Boolean {
return isPlaying
}
override fun getFrameInterval(): Int {
return frameInterval
}
override fun setFrameInterval(frameInterval: Int) {
this.frameInterval = if (frameInterval <= 0) {
0
} else {
frameInterval
}
}
/**
* only use for delegation
*/
fun bindView(textureView: TextureView) {
isTextureViewMode = true
mTextureView = textureView
mBitmapDrawer = TextureBitmapDrawer(textureView)
}
/**
* only use for delegation
*/
fun bindView(surfaceView: SurfaceView) {
isTextureViewMode = false
mSurfaceView = surfaceView
mBitmapDrawer = SurfaceViewBitmapDrawer(surfaceView)
}
override fun supportInBitmap(): Boolean {
return supportInBitmap
}
override fun setSupportInBitmap(supportInBitmap: Boolean) {
this.supportInBitmap = supportInBitmap
}
override fun clearViewAfterStop(clearViewAfterStop: Boolean) {
this.clearViewAfterStop = clearViewAfterStop
}
override fun clearViewAfterStop(): Boolean {
return clearViewAfterStop
}
/**
* play animation from assets files
* @param assetsPath must be a directory
*/
override fun playAnimationFromAssets(assetsPath: String) {
playAnimationFromAssets(assetsPath, 0)
}
/**
* play animation from a file directory path
* @param filePath must be a directory
*/
override fun playAnimationFromFile(filePath: String) {
playAnimationFromFile(filePath, 0)
}
/**
* play animation from assets files
* @param assetsPath must be a directory
* @param index the start frame index
*/
override fun playAnimationFromAssets(assetsPath: String, index: Int) {
val paths = Util.getPathList(mContext, assetsPath)
playAnimation(paths.map {
PathData(it, PATH_ASSETS)
} as MutableList<PathData>, index)
}
/**
* play animation from a file directory path
* @param filePath must be a directory
* @param index the start frame index
*/
override fun playAnimationFromFile(filePath: String, index: Int) {
val paths = Util.getPathList(File(filePath))
playAnimation(paths.map {
PathData(it, PATH_FILE)
} as MutableList<PathData>, index)
}
var mPaths: MutableList<PathData>? = null
private set
/**
* start playing animations
* @param paths the path data
*/
override fun playAnimation(paths: MutableList<PathData>, index: Int) {
if (paths.isNullOrEmpty()) {
Log.e(TAG, "path is null or empty")
return
}
if (mSurfaceView == null && mTextureView == null) {
throw NullPointerException("TextureView and SurfaceView is null")
}
mPaths = paths
drawIndex = index
mRepeatStrategy.setPaths(paths)
mBitmapPool.start(mRepeatStrategy, index)
if (isPlaying) {
return
}
isPlaying = true
if (drawThread?.isAlive == true) {
relayDraw = true
} else {
draw()
}
}
/**
* stop the animation async
*/
override fun stopAnimation(): Int {
if (!isPlaying) {
return 0
}
isPlaying = false
mBitmapPool.release()
try {
drawThread?.interrupt()
} catch (e: InterruptedException) {
//e.printStackTrace()
}
mPaths = null
animationListener?.onAnimationEnd()
if (clearViewAfterStop) {
mBitmapDrawer.clear()
}
return drawIndex
}
override fun stopAnimationFromPool() {
drawIndex = 0
mHandler.sendEmptyMessage(MSG_STOP)
}
private fun draw() {
mHandler.sendEmptyMessage(MSG_ANIMATION_START)
drawThread = thread(start = true) {
while (isPlaying) {
val startTime = SystemClock.uptimeMillis()
val bitmap = mBitmapPool.take() ?: continue
configureDrawMatrix(bitmap, mSurfaceView ?: mTextureView!!)
val canvas = mBitmapDrawer.draw(bitmap, mDrawMatrix) ?: continue
val interval = SystemClock.uptimeMillis() - startTime
if (interval < frameInterval) {
try {
Thread.sleep(frameInterval - interval)
} catch (e: InterruptedException) {
//e.printStackTrace()
}
}
drawIndex++
mBitmapDrawer.unlockAndPost(canvas)
if (mBitmapPool.getRepeatStrategy() != null) {
val strategy = mBitmapPool.getRepeatStrategy()
if (strategy!!.getTotalFrames() == FRAMES_INFINITE) {
animationListener?.onProgress(0f, drawIndex, strategy.getTotalFrames())
} else {
animationListener?.onProgress(drawIndex.toFloat() / strategy.getTotalFrames().toFloat(), drawIndex, strategy.getTotalFrames())
}
}
if (supportInBitmap) {
mBitmapPool.recycle(bitmap)
}
if (!isPlaying && clearViewAfterStop) {
mBitmapDrawer.clear()
}
}
if (relayDraw) {
draw()
relayDraw = false
}
}
}
/**
* set the bitmap scale type
* @see ScaleType
*/
override fun setScaleType(scaleType: ScaleType) {
mScaleType = scaleType
}
/**
* set the bitmap transform matrix
* @see setScaleType
*/
override fun setScaleType(matrix: Matrix) {
mScaleType = ScaleType.MATRIX
mDrawMatrix = matrix
}
/**
* set the animation repeat mode
* Works before the animation plays, if called when animation playing, it won't take effect until the next playing.
* @see RepeatMode
*/
override fun setRepeatMode(repeatMode: RepeatMode) {
mRepeatStrategy = when (repeatMode) {
RepeatMode.INFINITE -> RepeatInfinite()
RepeatMode.REVERSE_ONCE -> RepeatReverse()
RepeatMode.REVERSE_INFINITE -> RepeatReverseInfinite()
else -> RepeatOnce()
}
}
/**
* @see setRepeatMode
*/
override fun setRepeatMode(repeatMode: RepeatStrategy) {
mRepeatStrategy = repeatMode
}
private val MATRIX_SCALE_ARRAY =
arrayOf(Matrix.ScaleToFit.FILL, Matrix.ScaleToFit.START, Matrix.ScaleToFit.CENTER, Matrix.ScaleToFit.END)
private var mScaleType = ScaleType.CENTER
private var mDrawMatrix = Matrix()
private var lastSrcWidth = 0
private var lastDstWidth = 0
private var lastSrcHeight = 0
private var lastDstHeight = 0
private var lastScaleType: ScaleType? = null
/**
* 根据ScaleType配置绘制bitmap的Matrix
*
* @param bitmap
*/
private fun configureDrawMatrix(bitmap: Bitmap, view: View) {
val srcWidth = bitmap.width
val dstWidth = view.width
val srcHeight = bitmap.height
val dstHeight = view.height
val nothingChanged = lastScaleType == mScaleType &&
lastSrcWidth == srcWidth && dstWidth == lastDstWidth && lastSrcHeight == srcHeight && lastDstHeight == dstHeight
if (nothingChanged) {
return
}
lastSrcWidth = srcWidth
lastDstWidth = dstWidth
lastSrcHeight = srcHeight
lastDstHeight = dstHeight
lastScaleType = mScaleType
when (mScaleType) {
ScaleType.MATRIX -> return
ScaleType.CENTER -> mDrawMatrix.setTranslate(
Math.round((dstWidth - srcWidth) * 0.5f).toFloat(),
Math.round((dstHeight - srcHeight) * 0.5f).toFloat()
)
ScaleType.CENTER_CROP -> {
val scale: Float
var dx = 0f
var dy = 0f
//按照高缩放
if (dstHeight * srcWidth > dstWidth * srcHeight) {
scale = dstHeight.toFloat() / srcHeight.toFloat()
dx = (dstWidth - srcWidth * scale) * 0.5f
} else {
scale = dstWidth.toFloat() / srcWidth.toFloat()
dy = (dstHeight - srcHeight * scale) * 0.5f
}
mDrawMatrix.setScale(scale, scale)
mDrawMatrix.postTranslate(dx, dy)
}
ScaleType.CENTER_INSIDE -> {
//小于dst时不缩放
val scale: Float = if (srcWidth <= dstWidth && srcHeight <= dstHeight) {
1.0f
} else {
Math.min(
dstWidth.toFloat() / srcWidth.toFloat(),
dstHeight.toFloat() / srcHeight.toFloat()
)
}
val dx = Math.round((dstWidth - srcWidth * scale) * 0.5f).toFloat()
val dy = Math.round((dstHeight - srcHeight * scale) * 0.5f).toFloat()
mDrawMatrix.setScale(scale, scale)
mDrawMatrix.postTranslate(dx, dy)
}
else -> {
val srcRect = RectF(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat())
val dstRect = RectF(0f, 0f, view.width.toFloat(), view.height.toFloat())
mDrawMatrix.setRectToRect(srcRect, dstRect, MATRIX_SCALE_ARRAY[mScaleType.value - 1])
}
}
}
interface FrameAnimationListener {
/**
* notifies the start of the animation.
*/
fun onAnimationStart()
/**
* notifies the end of the animation.
*/
fun onAnimationEnd()
/**
* callback for animation playing progress not in UI thread
* @param progress 0-1, if the animation played infinitely, always 0
* @param frameIndex the current frame index
* @param totalFrames the total frames of the animation, -1 if the animation played infinitely
*/
fun onProgress(progress: Float, frameIndex: Int, totalFrames: Int)
}
private var animationListener: FrameAnimationListener? = null
override fun setAnimationListener(listener: FrameAnimationListener) {
animationListener = listener
}
enum class ScaleType(val value: Int) {
/**
* scale using the bitmap matrix when drawing.
*/
MATRIX(0),
/**
* @see Matrix.ScaleToFit.FILL
*/
FIT_XY(1),
/**
* @see Matrix.ScaleToFit.START
*/
FIT_START(2),
/**
* @see Matrix.ScaleToFit.CENTER
*/
FIT_CENTER(3),
/**
* @see Matrix.ScaleToFit.END
*/
FIT_END(4),
/**
* Center the image in the view, but perform no scaling.
*/
CENTER(5),
/**
* Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image
* will be equal to or larger than the corresponding dimension of the view.
*/
CENTER_CROP(6),
/**
* Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image
* will be equal to or less than the corresponding dimension of the view.
*/
CENTER_INSIDE(7)
}
enum class RepeatMode {
/**
* play once
*/
ONCE,
/**
* play infinity
*/
INFINITE,
/**
* the original order 1 2 3 4 5
* playing order 5 4 3 2 1 ...
*/
REVERSE_ONCE,
/**
* the original order 1 2 3 4 5
* playing order 1 2 3 4 5 4 3 2 1 2 3 4 5 ...
*/
REVERSE_INFINITE
}
companion object {
val PATH_FILE = 0x00
val PATH_ASSETS = 0x01
val FRAMES_INFINITE = -0x01
}
/**
*
* @param type the path type ,file or assets
* @see PATH_FILE
* @see PATH_ASSETS
*/
data class PathData(val path: String, val type: Int)
} | apache-2.0 | 4838862654e6647c62ee4898eb7b7f87 | 29.444882 | 150 | 0.58183 | 4.852526 | false | false | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/http/HttpResponseException.kt | 1 | 2882 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.http
open class HttpResponseException @JvmOverloads constructor(val status: Int, message: String, val details: Map<String, String> = mapOf()) : RuntimeException(message)
class RedirectResponse @JvmOverloads constructor(
status: Int = HttpCode.FOUND.status,
message: String = "Redirected",
details: Map<String, String> = mapOf()
) : HttpResponseException(status, message, details)
class BadRequestResponse @JvmOverloads constructor(
message: String = "Bad request",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.BAD_REQUEST.status, message, details)
class UnauthorizedResponse @JvmOverloads constructor(
message: String = "Unauthorized",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.UNAUTHORIZED.status, message, details)
class ForbiddenResponse @JvmOverloads constructor(
message: String = "Forbidden",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.FORBIDDEN.status, message, details)
class NotFoundResponse @JvmOverloads constructor(
message: String = "Not found",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.NOT_FOUND.status, message, details)
class MethodNotAllowedResponse @JvmOverloads constructor(
message: String = "Method not allowed",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.METHOD_NOT_ALLOWED.status, message, details)
class ConflictResponse @JvmOverloads constructor(
message: String = "Conflict",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.CONFLICT.status, message, details)
class GoneResponse @JvmOverloads constructor(
message: String = "Gone",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.GONE.status, message, details)
class InternalServerErrorResponse @JvmOverloads constructor(
message: String = "Internal server error",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.INTERNAL_SERVER_ERROR.status, message, details)
class BadGatewayResponse @JvmOverloads constructor(
message: String = "Bad gateway",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.BAD_GATEWAY.status, message, details)
class ServiceUnavailableResponse @JvmOverloads constructor(
message: String = "Service unavailable",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.SERVICE_UNAVAILABLE.status, message, details)
class GatewayTimeoutResponse @JvmOverloads constructor(
message: String = "Gateway timeout",
details: Map<String, String> = mapOf()
) : HttpResponseException(HttpCode.GATEWAY_TIMEOUT.status, message, details)
| apache-2.0 | 61ee423a677cc0e58b51821710bf3c60 | 39.577465 | 164 | 0.756335 | 4.391768 | false | false | false | false |
SakaiTakao/HighRisk | app/src/main/kotlin/sakaitakao/android/highrisk/activity/RedirectActivity.kt | 1 | 3769 | package sakaitakao.android.highrisk.activity
import java.security.NoSuchAlgorithmException
import sakaitakao.android.highrisk.R
import sakaitakao.android.highrisk.util.SecroidUtil
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
/**
* Secroid にリダイレクトします。画面はありません。
* @author takao
*/
class RedirectActivity : Activity() {
/*
* (非 Javadoc)
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
finish()
val intent = this.intent
if (intent == null) {
Log.e(javaClass.simpleName, "onCreate: intent is null.")
Toast.makeText(this, R.string.redirect_error_message, Toast.LENGTH_LONG).show()
return
}
try {
val action = intent.action
when (action) {
Intent.ACTION_VIEW ->
redirectByUri(intent)
Intent.ACTION_SEND ->
redirectByText(intent)
else ->
Log.e(javaClass.simpleName, "onCreate: Unexpected action. ($action)")
}
} catch (e: ActivityNotFoundException) {
// ブラウザなし
Toast.makeText(this, R.string.browser_not_found, Toast.LENGTH_LONG).show()
} catch (e: NoSuchAlgorithmException) {
// アルゴリズムなし
Toast.makeText(this, R.string.unsupported_algorithm, Toast.LENGTH_LONG).show()
}
}
// -------------------------------------------------------------------------
// Privates
// -------------------------------------------------------------------------
/**
* ブラウザから起動された時の処理を実行します。
*/
@Throws(NoSuchAlgorithmException::class, ActivityNotFoundException::class)
private fun redirectByUri(intent: Intent) {
val storeUri = intent.data
if (storeUri == null) {
Log.e(javaClass.simpleName, "redirectByUri: intent.getData() returns null.")
Toast.makeText(this, R.string.redirect_error_message, Toast.LENGTH_LONG).show()
return
}
val id = storeUri.getQueryParameter("id")
if (id?.isEmpty() ?: true) {
Log.e(javaClass.simpleName, "redirectByUri: URI has no \"id\" parameter. URI = $storeUri")
Toast.makeText(this, R.string.redirect_error_message, Toast.LENGTH_LONG).show()
return
}
// secroid へ遷移
SecroidUtil.go(this, id)
}
/**
* Play ストアアプリから起動された時の処理を実行します。
*/
@Throws(NoSuchAlgorithmException::class, ActivityNotFoundException::class)
private fun redirectByText(intent: Intent) {
val extras = intent.extras
if (extras == null) {
Log.e(javaClass.simpleName, "redirectByText: intent.getExtras() returns null.")
Toast.makeText(this, R.string.redirect_error_message, Toast.LENGTH_LONG).show()
return
}
val uriText = extras.getString(Intent.EXTRA_TEXT)
val uri = Uri.parse(uriText)
val id = uri.getQueryParameter("id")
if (id?.isEmpty() ?: true) {
Log.e(javaClass.simpleName, "redirectByText: URI has no \"id\" parameter. URI = $uriText")
Toast.makeText(this, R.string.redirect_error_message, Toast.LENGTH_LONG).show()
return
}
// secroid へ遷移
SecroidUtil.go(this, id)
}
}
| bsd-2-clause | 4b3077b3adce4a478007196adfdaf915 | 32.598131 | 102 | 0.586092 | 4.132184 | false | false | false | false |
Gu3pardo/PasswordSafe-AndroidClient | lib_password/src/main/java/guepardoapps/password/WordGenerator.kt | 1 | 2782 | package guepardoapps.password
import android.annotation.SuppressLint
import android.content.Context
import android.os.AsyncTask
import android.util.Log
import androidx.annotation.NonNull
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.lang.IllegalArgumentException
import java.lang.StringBuilder
import java.util.*
@Throws(IllegalArgumentException::class)
fun generateRandomWords(@NonNull wordList: ArrayList<String>, addRandomDice: Boolean = false, pwLengthSettings: Pair<Int, Int>): String {
if (pwLengthSettings.first < 1 || pwLengthSettings.second < 1 || pwLengthSettings.second < pwLengthSettings.first) {
Log.e("GenerateRandom", "Invalid signCount (first: ${pwLengthSettings.first}, second: ${pwLengthSettings.second})")
throw IllegalArgumentException("Invalid signCount (first: ${pwLengthSettings.first}, second: ${pwLengthSettings.second})")
}
val password = StringBuilder()
while (password.length < pwLengthSettings.first + 2) {
val random = Random()
val wordIndex = random.nextInt(wordList.size)
val currentWord = wordList[wordIndex]
password.append(currentWord.capitalize())
if (addRandomDice) {
password.append(generateRandomDice(Pair(1, 1)))
}
}
return password.toString().substring(0, password.length - 2)
}
@Throws(IOException::class)
fun readWordList(context: Context): ArrayList<String> {
val wordList = ArrayList<String>()
val inputStream = context.assets.open("words.txt")
val inputStreamReader = InputStreamReader(inputStream)
val bufferedReader = BufferedReader(inputStreamReader)
var fileLine: String? = bufferedReader.readLine()
while (fileLine != null) {
wordList.add(fileLine)
fileLine = bufferedReader.readLine()
}
bufferedReader.close()
inputStreamReader.close()
inputStream.close()
return wordList
}
interface OnGenerateWordPasswordTask {
fun onFinished(password: String?, success: Boolean)
}
class GenerateWordPasswordTask : AsyncTask<String, Void, String>() {
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
lateinit var onGenerateWordPasswordTask: OnGenerateWordPasswordTask
lateinit var pwLengthSettings: Pair<Int, Int>
var addRandomDice: Boolean = false
override fun doInBackground(vararg params: String?): String? {
return try {
val wordList = readWordList(context)
generateRandomWords(wordList, addRandomDice, pwLengthSettings)
} catch (exception: Exception) {
null
}
}
override fun onPostExecute(result: String?) {
onGenerateWordPasswordTask.onFinished(result, !result.isNullOrEmpty())
}
} | mit | 4501b8c47d5b78ebac1b9140952df07f | 30.988506 | 137 | 0.721064 | 4.545752 | false | false | false | false |
MFlisar/Lumberjack | library-viewer/src/main/java/com/michaelflisar/lumberjack/ExtensionViewer.kt | 1 | 946 | package com.michaelflisar.lumberjack
import android.content.Context
import android.content.Intent
import com.michaelflisar.lumberjack.interfaces.IDataExtractor
import com.michaelflisar.lumberjack.interfaces.IFileLoggingSetup
import com.michaelflisar.lumberjack.view.LumberjackViewerActivity
/*
* convenient extension to show a log file
*/
fun L.showLog(
context: Context,
fileLoggingSetup: IFileLoggingSetup,
receiver: String? = null,
dataExtractor: IDataExtractor = DefaultDataExtractor,
title: String? = null
) {
LumberjackViewerActivity.show(context, fileLoggingSetup, receiver, dataExtractor, title)
}
fun L.createViewerIntent(
context: Context,
fileLoggingSetup: IFileLoggingSetup,
receiver: String? = null,
dataExtractor: IDataExtractor = DefaultDataExtractor,
title: String? = null
): Intent = LumberjackViewerActivity.createIntent(context, fileLoggingSetup, receiver, dataExtractor, title) | apache-2.0 | f65e9d17d147c575b9958af59398954c | 32.821429 | 108 | 0.791755 | 4.042735 | false | false | false | false |
rock3r/detekt | detekt-cli/src/test/kotlin/io/gitlab/arturbosch/detekt/cli/ConfigurationsSpec.kt | 1 | 12941 | package io.gitlab.arturbosch.detekt.cli
import com.beust.jcommander.ParameterException
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.internal.PathFilters
import io.gitlab.arturbosch.detekt.test.resource
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.nio.file.Paths
internal class ConfigurationsSpec : Spek({
describe("a configuration") {
it("should be an empty config") {
val config = CliArgs().loadConfiguration()
assertThat(config.valueOrDefault("one", -1)).isEqualTo(-1)
assertThat(config.valueOrDefault("two", -1)).isEqualTo(-1)
assertThat(config.valueOrDefault("three", -1)).isEqualTo(-1)
}
}
describe("parse different path based configuration settings") {
val pathOne = resource("/configs/one.yml").path
val pathTwo = resource("/configs/two.yml").path
val pathThree = resource("/configs/three.yml").path
it("should load single config") {
val config = CliArgs { config = pathOne }.loadConfiguration()
assertThat(config.valueOrDefault("one", -1)).isEqualTo(1)
}
it("should load two configs") {
val config = CliArgs { config = "$pathOne, $pathTwo" }.loadConfiguration()
assertThat(config.valueOrDefault("one", -1)).isEqualTo(1)
assertThat(config.valueOrDefault("two", -1)).isEqualTo(2)
}
it("should load three configs") {
val config = CliArgs { config = "$pathOne, $pathTwo;$pathThree" }.loadConfiguration()
assertThat(config.valueOrDefault("one", -1)).isEqualTo(1)
assertThat(config.valueOrDefault("two", -1)).isEqualTo(2)
assertThat(config.valueOrDefault("three", -1)).isEqualTo(3)
}
it("should fail on invalid config value") {
assertThatIllegalArgumentException()
.isThrownBy { CliArgs { config = "," }.loadConfiguration() }
assertThatExceptionOfType(ParameterException::class.java)
.isThrownBy { CliArgs { config = "sfsjfsdkfsd" }.loadConfiguration() }
assertThatExceptionOfType(ParameterException::class.java)
.isThrownBy { CliArgs { config = "./i.do.not.exist.yml" }.loadConfiguration() }
}
}
describe("parse different resource based configuration settings") {
it("should load single config") {
val config = CliArgs { configResource = "/configs/one.yml" }.loadConfiguration()
assertThat(config.valueOrDefault("one", -1)).isEqualTo(1)
}
it("should load two configs") {
val config = CliArgs { configResource = "/configs/one.yml, /configs/two.yml" }.loadConfiguration()
assertThat(config.valueOrDefault("one", -1)).isEqualTo(1)
assertThat(config.valueOrDefault("two", -1)).isEqualTo(2)
}
it("should load three configs") {
val config = CliArgs {
configResource = "/configs/one.yml, /configs/two.yml;configs/three.yml"
}.loadConfiguration()
assertThat(config.valueOrDefault("one", -1)).isEqualTo(1)
assertThat(config.valueOrDefault("two", -1)).isEqualTo(2)
assertThat(config.valueOrDefault("three", -1)).isEqualTo(3)
}
it("should fail on invalid config value") {
@Suppress("DEPRECATION")
assertThatExceptionOfType(Config.InvalidConfigurationError::class.java)
.isThrownBy { CliArgs { configResource = "," }.loadConfiguration() }
assertThatExceptionOfType(ParameterException::class.java)
.isThrownBy { CliArgs { configResource = "sfsjfsdkfsd" }.loadConfiguration() }
assertThatExceptionOfType(ParameterException::class.java)
.isThrownBy { CliArgs { configResource = "./i.do.not.exist.yml" }.loadConfiguration() }
}
}
describe("parse different filter settings") {
it("should load single filter") {
val filters = CliArgs { excludes = "**/one/**" }.createFilters()
assertThat(filters?.isIgnored(Paths.get("/one/path"))).isTrue()
assertThat(filters?.isIgnored(Paths.get("/two/path"))).isFalse()
}
describe("parsing with different separators") {
// can parse pattern **/one/**,**/two/**,**/three
fun assertFilters(filters: PathFilters?) {
assertThat(filters?.isIgnored(Paths.get("/one/path"))).isTrue()
assertThat(filters?.isIgnored(Paths.get("/two/path"))).isTrue()
assertThat(filters?.isIgnored(Paths.get("/three"))).isTrue()
assertThat(filters?.isIgnored(Paths.get("/root/three"))).isTrue()
assertThat(filters?.isIgnored(Paths.get("/three/path"))).isFalse()
}
it("should load multiple comma-separated filters with no spaces around commas") {
val filters = CliArgs { excludes = "**/one/**,**/two/**,**/three" }.createFilters()
assertFilters(filters)
}
it("should load multiple semicolon-separated filters with no spaces around semicolons") {
val filters = CliArgs { excludes = "**/one/**;**/two/**;**/three" }.createFilters()
assertFilters(filters)
}
it("should load multiple comma-separated filters with spaces around commas") {
val filters = CliArgs { excludes = "**/one/** ,**/two/**, **/three" }.createFilters()
assertFilters(filters)
}
it("should load multiple semicolon-separated filters with spaces around semicolons") {
val filters = CliArgs { excludes = "**/one/** ;**/two/**; **/three" }.createFilters()
assertFilters(filters)
}
it("should load multiple mixed-separated filters with no spaces around separators") {
val filters = CliArgs { excludes = "**/one/**,**/two/**;**/three" }.createFilters()
assertFilters(filters)
}
it("should load multiple mixed-separated filters with spaces around separators") {
val filters = CliArgs { excludes = "**/one/** ,**/two/**; **/three" }.createFilters()
assertFilters(filters)
}
}
it("should ignore empty and blank filters") {
val filters = CliArgs { excludes = " ,,**/three" }.createFilters()
assertThat(filters?.isIgnored(Paths.get("/three"))).isTrue()
assertThat(filters?.isIgnored(Paths.get("/root/three"))).isTrue()
assertThat(filters?.isIgnored(Paths.get("/one/path"))).isFalse()
assertThat(filters?.isIgnored(Paths.get("/two/path"))).isFalse()
assertThat(filters?.isIgnored(Paths.get("/three/path"))).isFalse()
}
}
describe("fail fast only") {
val config = CliArgs {
configResource = "/configs/empty.yml"
failFast = true
}.loadConfiguration()
it("should override active to true by default") {
val actual = config.subConfig("comments")
.subConfig("UndocumentedPublicClass")
.valueOrDefault("active", false)
assertThat(actual).isEqualTo(true)
}
it("should override maxIssues to 0 by default") {
assertThat(config.subConfig("build").valueOrDefault("maxIssues", -1)).isEqualTo(0)
}
it("should keep config from default") {
val actual = config.subConfig("style")
.subConfig("MaxLineLength")
.valueOrDefault("maxLineLength", -1)
assertThat(actual).isEqualTo(120)
}
}
describe("fail fast override") {
val config = CliArgs {
configResource = "/configs/fail-fast-will-override-here.yml"
failFast = true
}.loadConfiguration()
it("should override config when specified") {
val actual = config.subConfig("style")
.subConfig("MaxLineLength")
.valueOrDefault("maxLineLength", -1)
assertThat(actual).isEqualTo(100)
}
it("should override active when specified") {
val actual = config.subConfig("comments")
.subConfig("CommentOverPrivateMethod")
.valueOrDefault("active", true)
assertThat(actual).isEqualTo(false)
}
it("should override maxIssues when specified") {
assertThat(config.subConfig("build").valueOrDefault("maxIssues", -1)).isEqualTo(1)
}
}
describe("build upon default config") {
val config = CliArgs {
buildUponDefaultConfig = true
failFast = false
configResource = "/configs/fail-fast-wont-override-here.yml"
}.loadConfiguration()
it("should override config when specified") {
val ruleConfig = config.subConfig("style").subConfig("MaxLineLength")
val lineLength = ruleConfig.valueOrDefault("maxLineLength", -1)
val excludeComments = ruleConfig.valueOrDefault("excludeCommentStatements", false)
assertThat(lineLength).isEqualTo(100)
assertThat(excludeComments).isTrue()
}
it("should be active=false by default") {
val actual = config.subConfig("comments")
.subConfig("CommentOverPrivateFunction")
.valueOrDefault("active", true)
assertThat(actual).isFalse()
}
it("should be maxIssues=0 by default") {
val actual = config.subConfig("build").valueOrDefault("maxIssues", -1)
assertThat(actual).isEqualTo(0)
}
}
describe("auto correct config") {
context("when specified it respects all autoCorrect values of rules and rule sets") {
val config = CliArgs {
autoCorrect = true
configResource = "/configs/config-with-auto-correct.yml"
}.loadConfiguration()
val style = config.subConfig("style")
val comments = config.subConfig("comments")
it("is disabled for rule sets") {
assertThat(style.valueOrNull<Boolean>("autoCorrect")).isTrue()
assertThat(comments.valueOrNull<Boolean>("autoCorrect")).isFalse()
}
it("is disabled for rules") {
assertThat(style.subConfig("MagicNumber").valueOrNull<Boolean>("autoCorrect")).isTrue()
assertThat(style.subConfig("MagicString").valueOrNull<Boolean>("autoCorrect")).isFalse()
assertThat(comments.subConfig("ClassDoc").valueOrNull<Boolean>("autoCorrect")).isTrue()
assertThat(comments.subConfig("FunctionDoc").valueOrNull<Boolean>("autoCorrect")).isFalse()
}
}
mapOf(
CliArgs {
configResource = "/configs/config-with-auto-correct.yml"
}.loadConfiguration() to "when not specified all autoCorrect values are overridden to false",
CliArgs {
autoCorrect = false
configResource = "/configs/config-with-auto-correct.yml"
}.loadConfiguration() to "when specified as false, all autoCorrect values are overridden to false",
CliArgs {
autoCorrect = false
failFast = true
buildUponDefaultConfig = true
configResource = "/configs/config-with-auto-correct.yml"
}.loadConfiguration() to "regardless of other cli options, autoCorrect values are overridden to false"
).forEach { (config, testContext) ->
context(testContext) {
val style = config.subConfig("style")
val comments = config.subConfig("comments")
it("is disabled for rule sets") {
assertThat(style.valueOrNull<Boolean>("autoCorrect")).isFalse()
assertThat(comments.valueOrNull<Boolean>("autoCorrect")).isFalse()
}
it("is disabled for rules") {
assertThat(style.subConfig("MagicNumber").valueOrNull<Boolean>("autoCorrect")).isFalse()
assertThat(style.subConfig("MagicString").valueOrNull<Boolean>("autoCorrect")).isFalse()
assertThat(comments.subConfig("ClassDoc").valueOrNull<Boolean>("autoCorrect")).isFalse()
assertThat(comments.subConfig("FunctionDoc").valueOrNull<Boolean>("autoCorrect")).isFalse()
}
}
}
}
})
| apache-2.0 | f2e2c995c441b4545695959783a9cd76 | 43.47079 | 114 | 0.598176 | 5.12312 | false | true | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/util/ScheduleUtils.kt | 1 | 4715 | /*
* 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.util
import android.app.Application
import android.content.Context
import co.timetableapp.TimetableApplication
import co.timetableapp.data.handler.ClassTimeHandler
import co.timetableapp.data.handler.DataNotFoundException
import co.timetableapp.data.query.Filters
import co.timetableapp.data.query.Query
import co.timetableapp.data.schema.ClassTimesSchema
import co.timetableapp.model.Class
import co.timetableapp.model.ClassDetail
import co.timetableapp.model.ClassTime
import co.timetableapp.model.Timetable
import org.threeten.bp.DayOfWeek
import org.threeten.bp.LocalDate
/**
* A utility class containing helper methods related to the user's schedule.
*/
object ScheduleUtils {
/**
* @return the [ClassTime]s occurring on a particular [date] for the currently selected
* timetable. Note that if the specified [date] is not within the start and end dates
* of the current timetable, the returned list will be empty (the timetable would not
* have started or would have ended).
*/
@JvmStatic
fun getClassTimesForDate(context: Context,
application: Application,
date: LocalDate): List<ClassTime> {
val timetable = (application as TimetableApplication).currentTimetable!!
if (!timetable.isValidToday(date)) {
// Return empty list if timetable hasn't started or has ended
return emptyList()
}
val weekNumber = DateUtils.findWeekNumber(application, date)
return getClassTimesForDate(context, timetable, date, date.dayOfWeek, weekNumber)
}
/**
* Returns the class times occurring on the specified [date].
*
* Note that if the specified [date] is not within the start and end dates of the
* [currentTimetable], then an empty list will be returned as the timetable would either not
* have started or would have ended during that date.
*
* @param context the activity context
* @param currentTimetable the current timetable as in [TimetableApplication.currentTimetable]
* @param date the date to find [ClassTime]s for
* @param dayOfWeek the day of the week of the [date] (e.g. Monday, Tuesday, etc.)
* @param weekNumber the week number of the [date] according to the scheduling pattern
* set by [Timetable.weekRotations]. For example, '2' if it the date
* occurs on a 'Week 2' or 'Week B'.
*
* @return the list of [ClassTime]s which occur on the specified [date]
*/
@JvmStatic
fun getClassTimesForDate(context: Context,
currentTimetable: Timetable,
date: LocalDate,
dayOfWeek: DayOfWeek,
weekNumber: Int): List<ClassTime> {
if (!currentTimetable.isValidToday(date)) {
return emptyList()
}
val timetableId = currentTimetable.id
val query = Query.Builder()
.addFilter(Filters.equal(ClassTimesSchema.COL_TIMETABLE_ID, timetableId.toString()))
.addFilter(Filters.equal(ClassTimesSchema.COL_DAY, dayOfWeek.value.toString()))
.addFilter(Filters.equal(ClassTimesSchema.COL_WEEK_NUMBER, weekNumber.toString()))
.build()
val classTimes = ArrayList<ClassTime>()
for (classTime in ClassTimeHandler(context).getAllItems(query)) {
try {
val classDetail = ClassDetail.create(context, classTime.classDetailId)
val cls = Class.create(context, classDetail.classId)
if (cls.isCurrent(date)) {
classTimes.add(classTime)
}
} catch (e: DataNotFoundException) {
// Don't display to the user if the item can't be found but print the stack trace
e.printStackTrace()
continue
}
}
return classTimes
}
}
| apache-2.0 | 66ea255341fd932c8c624b6eac2efd67 | 40 | 100 | 0.647084 | 4.748238 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/util/Math.kt | 2 | 936 | package de.westnordost.streetcomplete.util
import kotlin.math.PI
/** returns a number between [startAt] - [startAt]+360 */
fun Double.normalizeDegrees(startAt: Double = 0.0): Double {
var result = this % 360 // is now -360..360
result = (result + 360) % 360 // is now 0..360
if (result > startAt + 360) result -= 360
return result
}
/** returns a number between [startAt] - [startAt]+2PI */
fun Double.normalizeRadians(startAt: Double = 0.0): Double {
val pi2 = PI*2
var result = this % pi2 // is now -2PI..2PI
result = (result + pi2) % pi2 // is now 0..2PI
if (result > startAt + pi2) result -= pi2
return result
}
/** returns a number between [startAt] - [startAt]+360 */
fun Float.normalizeDegrees(startAt: Float = 0f): Float {
var result = this % 360 // is now -360..360
result = (result + 360) % 360 // is now 0..360
if (result > startAt + 360) result -= 360
return result
}
| gpl-3.0 | 6ff1b84ef6e2a37502a3f4d9f303ed4e | 32.428571 | 60 | 0.633547 | 3.428571 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/map/components/TracksMapComponent.kt | 1 | 2584 | package de.westnordost.streetcomplete.map.components
import android.location.Location
import com.mapzen.tangram.LngLat
import com.mapzen.tangram.geometry.Polyline
import de.westnordost.streetcomplete.map.tangram.KtMapController
import de.westnordost.streetcomplete.map.tangram.toLngLat
import kotlin.math.max
/** Takes care of showing the path(s) walked on the map */
class TracksMapComponent(ctrl: KtMapController) {
/* There are two layers simply as a performance optimization: If there are thousands of
trackpoints, we don't want to update (=copy) the thousands of points each time a new
trackpoint is added. Instead, we only update a list of 100 trackpoints each time a new
trackpoint is added and every 100th time, we update the other layer.
So, the list of points updated ~per second doesn't grow too long.
*/
private val layer1 = ctrl.addDataLayer(LAYER1)
private val layer2 = ctrl.addDataLayer(LAYER2)
private var index = 0
private var tracks: MutableList<MutableList<LngLat>>
init {
tracks = ArrayList()
tracks.add(ArrayList())
}
/** Add a point to the current track */
fun addToCurrentTrack(pos: Location) {
val track = tracks.last()
track.add(pos.toLngLat())
// every 100th trackpoint, move the index to the back
if (track.size - index > 100) {
putAllTracksInOldLayer()
} else {
layer1.setFeatures(listOf(track.subList(index, track.size).toPolyline(false)))
}
}
/** Start a new track. I.e. the points in that track will be drawn as an own polyline */
fun startNewTrack() {
tracks.add(ArrayList())
putAllTracksInOldLayer()
}
/** Set all the tracks (when re-initializing) */
fun setTracks(tracks: List<List<Location>>) {
this.tracks = tracks.map { track -> track.map { it.toLngLat() }.toMutableList() }.toMutableList()
putAllTracksInOldLayer()
}
private fun putAllTracksInOldLayer() {
index = max(0, tracks.last().lastIndex)
layer1.clear()
layer2.setFeatures(tracks.map { it.toPolyline(true) })
}
fun clear() {
tracks = ArrayList()
startNewTrack()
}
companion object {
// see streetcomplete.yaml for the definitions of the layer
private const val LAYER1 = "streetcomplete_track"
private const val LAYER2 = "streetcomplete_track2"
}
}
private fun List<LngLat>.toPolyline(old: Boolean) =
Polyline(this, mapOf("type" to "line", "old" to old.toString()))
| gpl-3.0 | c922b64b5f54975de2b8f0545b41b383 | 33 | 105 | 0.669118 | 4.161031 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.