repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nearbydelta/KoreanAnalyzer | khaiii/src/main/kotlin/kr/bydelta/koala/khaiii/ext.kt | 1 | 4337 | @file:JvmName("Util")
@file:JvmMultifileClass
package kr.bydelta.koala.khaiii
import kr.bydelta.koala.POS
import java.util.logging.Level
/**
* ์
๋ ฅ๋ฐ์ ์ธ์ข
ํ์ฌ ํ๊ธฐ๋ฅผ ์นด์ด ๋ถ์๊ธฐ์ ํ์ฌ ํ๊ธฐ๋ก ๋ณํํฉ๋๋ค.
*
* * ๋ณํํ๋ [์ฌ๊ธฐ](https://docs.google.com/spreadsheets/d/1OGM4JDdLk6URuegFKXg1huuKWynhg_EQnZYgTmG4h0s Conversion Table (Korean))์์ ๋ณผ ์ ์์ต๋๋ค.
*
* ## ์ฌ์ฉ ์
* ### Kotlin
* ```kotlin
* POS.NNG.fromSejongPOS()
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support)
* ```scala
* POS.NNG.fromSejongPOS()
* ```
*
* ### Java
* ```java
* Util.fromSejongPOS(POS.NNG)
* ```
*
* @since 1.x
* @return ๋์ํ๋ ์ฝ๋ชจ๋ ํ์ฌ์ ๊ฐ
*/
fun POS.fromSejongPOS(): String =
when (this) {
POS.NF -> "ZN"
POS.NV -> "ZV"
POS.NA -> "ZZ"
POS.XPV -> "ZZ"
POS.XSM -> "ZZ"
POS.XSO -> "ZZ"
else -> this.toString()
}
/**
* ์นด์ด ๋ถ์๊ธฐ์ ํ์ฌ ํ๊ธฐ๋ฅผ ์ธ์ข
ํ์ฌ ํ๊ธฐ [POS] ๊ฐ์ผ๋ก ๋ณํํฉ๋๋ค.
*
* * ๋ณํํ๋ [์ฌ๊ธฐ](https://docs.google.com/spreadsheets/d/1OGM4JDdLk6URuegFKXg1huuKWynhg_EQnZYgTmG4h0s Conversion Table (Korean))์์ ๋ณผ ์ ์์ต๋๋ค.
*
* ## ์ฌ์ฉ ์
* ### Kotlin
* ```kotlin
* "NNG".toSejongPOS()
* ```
*
* ### Scala + [koalanlp-scala](https://koalanlp.github.io/scala-support)
* ```scala
* "NNG".toSejongPOS()
* ```
*
* ### Java
* ```java
* Util.toSejongPOS("NNG")
* ```
*
* @since 1.x
* @return ๋์ํ๋ ์ธ์ข
ํ์ฌ์ ๊ฐ
*/
fun String?.toSejongPOS(): POS =
when (this?.toUpperCase()) {
null -> POS.NA
"ZN" -> POS.NF
"ZV" -> POS.NV
"ZZ" -> POS.NA
"SWK" -> POS.SW
else -> POS.valueOf(this.toUpperCase())
}
/**
* ์ฃผ์ด์ง string์ UTF-8 ๋ฐ์ดํธ ํํ์ ๋ง์ถฐ ๋ฌธ์ index๋ฅผ ํ๊ธฐํจ.
* ์) 'ํ๊ธ english'๋ (0,0,0, 1,1,1, 2, 3, 4, 5, 6, 7, 8, 9)๊ฐ ๋จ
* @return ๊ฐ ๋ฐ์ดํธ๋น ์ค์ string์ ๋ฌธ์ ์์น๋ฅผ ํํํ list
*/
fun String.byteAlignment(): List<Int> {
val utf8IndexList = mutableListOf<Int>()
for ((index, ch) in this.withIndex()) {
val utf8Len = when {
ch.toInt() <= 0x7F -> 1
ch.toInt() <= 0x7FF -> 2
ch.isHighSurrogate() -> 4
else -> 3
}
for (i in 1..utf8Len) {
utf8IndexList.add(index)
}
}
return utf8IndexList
}
/**
* Khaiii์์ ์ค์ ๋ Logger ์ ํ๋ค.
*/
enum class KhaiiiLoggerType {
/**
* ์ ์ฒด Logger
*/
all,
/**
* Khaiii console. (ํ์ฌ ๋ฒ์ v0.1์์๋ Java์ ๋ฌด๊ดํจ)
*/
console,
/**
* ์ค๋ถ์ ์ฌ์
*/
ErrPatch,
/**
* ๋ถ์ ๋ฆฌ์์ค
*/
Resource,
/**
* ๊ธฐ๋ถ์ ์ฌ์
*/
Preanal,
/**
* ์ํ ๋ณต์
*/
Restore,
/**
* ๋ฌธ์ฅ ๊ตฌ์ฑ
*/
Sentence,
/**
* ์ด์ ๊ตฌ์ฑ
*/
Word,
/**
* ํํ์ ๊ตฌ์ฑ
*/
Morph,
/**
* ํํ์ ๋ถ์๊ธฐ
*/
Tagger,
/**
* Word Embedding
*/
Embed,
/**
* Trie ๊ตฌ์กฐ
*/
Trie,
/**
* Khaiii ๊ตฌํ์ฒด
*/
KhaiiiImpl
}
/**
* Java์ LogLevel์ Khaiii๊ฐ ์ฌ์ฉํ๋ spdlog์ level๋ก ๋ณ๊ฒฝํ๋ค.
* @return spdlig์ level๊ฐ (String)
*/
fun Level.getSpdlogLevel(): String = when (this) {
Level.SEVERE, Level.OFF -> "critical" // Off ๋ถ๊ฐ๋ฅ
Level.WARNING -> "warn"
Level.INFO -> "info"
Level.CONFIG, Level.FINE -> "debug"
Level.FINER, Level.FINEST, Level.ALL -> "trace"
else -> "info"
}
/**
* [Khaiii.analyzeBeforeErrorPatch]์ ๊ฒฐ๊ณผ๋ฅผ ํด์ํ๊ธฐ ์ํด, Khaiii์์ ์ฌ์ฉํ๋ ํ๊ทธ๋ค์ ์์๋ฅผ ๊ทธ๋๋ก ๊ฐ์ ธ์์ต๋๋ค.
*
* ์ฐธ๊ณ : [https://github.com/kakao/khaiii/blob/v0.1/src/main/cpp/khaiii/Morph.cpp#L32]
*/
val posTagsInKhaiii = listOf("EC", "EF", "EP", "ETM", "ETN", "IC", "JC", "JKB", "JKC", "JKG",
"JKO", "JKQ", "JKS", "JKV", "JX", "MAG", "MAJ", "MM", "NNB", "NNG",
"NNP", "NP", "NR", "SE", "SF", "SH", "SL", "SN", "SO", "SP",
"SS", "SW", "SWK", "VA", "VCN", "VCP", "VV", "VX", "XPN", "XR",
"XSA", "XSN", "XSV", "ZN", "ZV", "ZZ")
| gpl-3.0 | 32bc5310394330291947417e63d94fd8 | 19.825137 | 137 | 0.504592 | 2.590755 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/entity/remote/events/NotificationEvent.kt | 1 | 2417 | package forpdateam.ru.forpda.entity.remote.events
/**
* Created by radiationx on 29.07.17.
*/
data class NotificationEvent @JvmOverloads constructor(
var type: Type,
var source: Source,
var messageId: Int = 0,
var sourceId: Int = 0,
var userId: Int = 0,
var timeStamp: Long = 0,
var lastTimeStamp: Long = 0,
var msgCount: Int = 0,
var isImportant: Boolean = false,
var sourceTitle: String = "",
var userNick: String = "",
var sourceEventText: String? = null
) {
/*
* short
* */
val isNew: Boolean
get() = NotificationEvent.isNew(type)
val isRead: Boolean
get() = NotificationEvent.isRead(type)
val isMention: Boolean
get() = NotificationEvent.isMention(type)
enum class Type(val value: Int) {
NEW(2),
READ(4),
MENTION(8),
HAT_EDITED(16)
}
enum class Source(val value: Int) {
THEME(32),
SITE(64),
QMS(128)
}
fun fromTheme(): Boolean {
return NotificationEvent.fromTheme(source)
}
fun fromSite(): Boolean {
return NotificationEvent.fromSite(source)
}
fun fromQms(): Boolean {
return NotificationEvent.fromQms(source)
}
@JvmOverloads
fun notifyId(type: Type? = this.type): Int {
return sourceId / 4 + type!!.value + type.value
}
companion object {
const val SRC_EVENT_NEW = 1
const val SRC_EVENT_READ = 2
const val SRC_EVENT_MENTION = 3
const val SRC_EVENT_HAT_EDITED = 4
const val SRC_TYPE_SITE = "s"
const val SRC_TYPE_THEME = "t"
const val SRC_TYPE_QMS = "q"
fun isNew(type: Type?): Boolean {
return type != null && type == Type.NEW
}
fun isRead(type: Type?): Boolean {
return type != null && type == Type.READ
}
fun isMention(type: Type?): Boolean {
return type != null && type == Type.MENTION
}
fun fromTheme(source: Source?): Boolean {
return source != null && source == Source.THEME
}
fun fromSite(source: Source?): Boolean {
return source != null && source == Source.SITE
}
fun fromQms(source: Source?): Boolean {
return source != null && source == Source.QMS
}
}
}
| gpl-3.0 | e23b79a3b1985ae5077e944405754a26 | 21.588785 | 59 | 0.547373 | 4.138699 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/comments/unified/UnifiedCommentListViewModel.kt | 1 | 17553 | package org.wordpress.android.ui.comments.unified
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.wordpress.android.R.string
import org.wordpress.android.analytics.AnalyticsTracker.Stat.COMMENT_BATCH_APPROVED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.COMMENT_BATCH_DELETED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.COMMENT_BATCH_SPAMMED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.COMMENT_BATCH_TRASHED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.COMMENT_BATCH_UNAPPROVED
import org.wordpress.android.fluxc.model.CommentStatus
import org.wordpress.android.fluxc.model.CommentStatus.APPROVED
import org.wordpress.android.fluxc.model.CommentStatus.DELETED
import org.wordpress.android.fluxc.model.CommentStatus.SPAM
import org.wordpress.android.fluxc.model.CommentStatus.TRASH
import org.wordpress.android.fluxc.model.CommentStatus.UNAPPROVED
import org.wordpress.android.fluxc.persistence.comments.CommentsDao.CommentEntity
import org.wordpress.android.fluxc.store.CommentStore.CommentError
import org.wordpress.android.fluxc.store.CommentsStore.CommentsData.PagingData
import org.wordpress.android.models.usecases.BatchModerateCommentsUseCase.Parameters.ModerateCommentsParameters
import org.wordpress.android.models.usecases.CommentsUseCaseType
import org.wordpress.android.models.usecases.CommentsUseCaseType.BATCH_MODERATE_USE_CASE
import org.wordpress.android.models.usecases.CommentsUseCaseType.MODERATE_USE_CASE
import org.wordpress.android.models.usecases.CommentsUseCaseType.PAGINATE_USE_CASE
import org.wordpress.android.models.usecases.LocalCommentCacheUpdateHandler
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.Parameters.ModerateCommentParameters
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.Parameters.ModerateWithFallbackParameters
import org.wordpress.android.models.usecases.ModerateCommentWithUndoUseCase.SingleCommentModerationResult
import org.wordpress.android.models.usecases.PaginateCommentsUseCase.Parameters.GetPageParameters
import org.wordpress.android.models.usecases.PaginateCommentsUseCase.Parameters.ReloadFromCacheParameters
import org.wordpress.android.models.usecases.UnifiedCommentsListHandler
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.comments.unified.CommentFilter.UNREPLIED
import org.wordpress.android.ui.comments.unified.CommentListUiModelHelper.BatchModerationStatus
import org.wordpress.android.ui.comments.unified.CommentListUiModelHelper.CommentsUiModel
import org.wordpress.android.ui.mysite.SelectedSiteRepository
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.usecase.UseCaseResult
import org.wordpress.android.usecase.UseCaseResult.Failure
import org.wordpress.android.usecase.UseCaseResult.Success
import org.wordpress.android.util.NetworkUtilsWrapper
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import org.wordpress.android.viewmodel.ScopedViewModel
import javax.inject.Inject
import javax.inject.Named
typealias CommentsPagingResult = UseCaseResult<CommentsUseCaseType, CommentError, PagingData>
class UnifiedCommentListViewModel @Inject constructor(
private val commentListUiModelHelper: CommentListUiModelHelper,
private val selectedSiteRepository: SelectedSiteRepository,
private val networkUtilsWrapper: NetworkUtilsWrapper,
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper,
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher,
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
private val unifiedCommentsListHandler: UnifiedCommentsListHandler,
localCommentCacheUpdateHandler: LocalCommentCacheUpdateHandler
) : ScopedViewModel(mainDispatcher) {
private var isStarted = false
private lateinit var commentFilter: CommentFilter
private val _commentsUpdateListener = localCommentCacheUpdateHandler.subscribe()
private val _onSnackbarMessage = MutableSharedFlow<SnackbarMessageHolder>()
private val _selectedComments = MutableStateFlow(emptyList<SelectedComment>())
private val _batchModerationStatus = MutableStateFlow<BatchModerationStatus>(BatchModerationStatus.Idle)
val onSnackbarMessage: SharedFlow<SnackbarMessageHolder> = _onSnackbarMessage
private var commentInModeration = ArrayList<Long>()
// TODO maybe we can change to some generic Action pattern
private val _onCommentDetailsRequested = MutableSharedFlow<SelectedComment>()
val onCommentDetailsRequested: SharedFlow<SelectedComment> = _onCommentDetailsRequested
private val _commentsProvider = unifiedCommentsListHandler.subscribe()
val uiState: StateFlow<CommentsUiModel> by lazy {
combine(
_commentsProvider.filter { it.type == PAGINATE_USE_CASE }.filterIsInstance<CommentsPagingResult>(),
_selectedComments,
_batchModerationStatus
) { commentData, selectedCommentIds, batchModerationStatus ->
commentListUiModelHelper.buildUiModel(
commentFilter,
commentData,
selectedCommentIds,
batchModerationStatus,
uiState.replayCache.firstOrNull(),
this::toggleItem,
this::clickItem,
this::requestNextPage,
this::moderateSelectedComments,
this::onBatchModerationConfirmationCanceled
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.Companion.WhileSubscribed(UI_STATE_FLOW_TIMEOUT_MS),
initialValue = CommentsUiModel.buildInitialState()
)
}
fun start(commentListFilter: CommentFilter) {
if (isStarted) return
isStarted = true
commentFilter = commentListFilter
listenToLocalCacheUpdateRequests()
listenToSnackBarRequests()
requestsFirstPage()
}
private fun requestsFirstPage() {
launch(bgDispatcher) {
unifiedCommentsListHandler.requestPage(
GetPageParameters(
site = selectedSiteRepository.getSelectedSite()!!,
number = if (commentFilter == UNREPLIED) UNREPLIED_COMMENT_PAGE_SIZE else COMMENT_PAGE_SIZE,
offset = 0,
commentFilter = commentFilter
)
)
}
}
private fun requestNextPage(offset: Int) {
launch(bgDispatcher) {
unifiedCommentsListHandler.requestPage(
GetPageParameters(
site = selectedSiteRepository.getSelectedSite()!!,
number = if (commentFilter == UNREPLIED) {
UNREPLIED_COMMENT_PAGE_SIZE
} else {
COMMENT_PAGE_SIZE
},
offset = offset,
commentFilter = commentFilter
)
)
}
}
private fun listenToLocalCacheUpdateRequests() {
launch(bgDispatcher) {
_commentsUpdateListener.collectLatest {
launch(bgDispatcher) {
unifiedCommentsListHandler.refreshFromCache(
ReloadFromCacheParameters(
pagingParameters = GetPageParameters(
site = selectedSiteRepository.getSelectedSite()!!,
number = if (commentFilter == UNREPLIED) {
UNREPLIED_COMMENT_PAGE_SIZE
} else {
COMMENT_PAGE_SIZE
},
offset = 0,
commentFilter = commentFilter
),
hasMore = uiState.value.commentData.hasMore
)
)
}
}
}
}
private fun listenToSnackBarRequests() {
launch(bgDispatcher) {
_commentsProvider.filter { it is Failure }.collectLatest {
val errorMessage = if (it.type == BATCH_MODERATE_USE_CASE) {
UiStringRes(string.comment_batch_moderation_error)
} else {
if ((it as Failure).error.message.isNullOrEmpty()) {
null
} else {
UiStringText(it.error.message)
}
}
if (errorMessage != null) {
_onSnackbarMessage.emit(SnackbarMessageHolder(errorMessage))
}
}
}
listenToModerateWithUndoSnackbarRequets()
}
fun listenToModerateWithUndoSnackbarRequets() {
launch(bgDispatcher) {
_commentsProvider.filter { it is Success && it.type == MODERATE_USE_CASE }.collectLatest {
if (it is Success && it.data is SingleCommentModerationResult) {
val message = when (it.data.newStatus) {
TRASH -> UiStringRes(string.comment_trashed)
SPAM -> UiStringRes(string.comment_spammed)
else -> UiStringRes(string.comment_deleted_permanently)
}
commentInModeration.add(it.data.remoteCommentId)
_onSnackbarMessage.emit(
SnackbarMessageHolder(
message = message,
buttonTitle = UiStringRes(string.undo),
buttonAction = {
launch(bgDispatcher) {
commentInModeration.remove(it.data.remoteCommentId)
unifiedCommentsListHandler.undoCommentModeration(
ModerateWithFallbackParameters(
selectedSiteRepository.getSelectedSite()!!,
it.data.remoteCommentId,
it.data.newStatus,
it.data.oldStatus
)
)
}
},
onDismissAction = { _ ->
launch(bgDispatcher) {
if (commentInModeration.contains(it.data.remoteCommentId)) {
commentInModeration.remove(it.data.remoteCommentId)
unifiedCommentsListHandler.moderateAfterUndo(
ModerateWithFallbackParameters(
selectedSiteRepository.getSelectedSite()!!,
it.data.remoteCommentId,
it.data.newStatus,
it.data.oldStatus
)
)
}
}
}
)
)
}
}
}
}
fun reload() {
if (!networkUtilsWrapper.isNetworkAvailable()) {
launch(bgDispatcher) {
_onSnackbarMessage.emit(SnackbarMessageHolder(UiStringRes(string.no_network_message)))
}
} else {
requestsFirstPage()
}
}
private fun toggleItem(remoteCommentId: Long, commentStatus: CommentStatus) {
viewModelScope.launch {
val selectedComment = SelectedComment(remoteCommentId, commentStatus)
val selectedComments = _selectedComments.value.toMutableList()
if (selectedComments.contains(selectedComment)) {
selectedComments.remove(selectedComment)
} else {
selectedComments.add(selectedComment)
}
_selectedComments.emit(selectedComments)
}
}
private fun clickItem(comment: CommentEntity) {
if (_selectedComments.value.isNotEmpty()) {
toggleItem(comment.remoteCommentId, CommentStatus.fromString(comment.status))
} else {
launch {
_onCommentDetailsRequested.emit(
SelectedComment(
comment.remoteCommentId,
CommentStatus.fromString(comment.status)
)
)
}
}
}
fun clearActionModeSelection() {
viewModelScope.launch {
if (!_selectedComments.value.isNullOrEmpty()) {
_selectedComments.emit(listOf())
}
}
}
fun performSingleCommentModeration(commentId: Long, newStatus: CommentStatus) {
launch(bgDispatcher) {
if (newStatus == SPAM || newStatus == TRASH || newStatus == DELETED) {
unifiedCommentsListHandler.preModerateWithUndo(
ModerateCommentParameters(
selectedSiteRepository.getSelectedSite()!!,
commentId,
newStatus
)
)
} else {
launch(bgDispatcher) {
unifiedCommentsListHandler.moderateComments(
ModerateCommentsParameters(
selectedSiteRepository.getSelectedSite()!!,
listOf(commentId),
newStatus
)
)
}
}
}
}
fun onBatchModerationConfirmationCanceled() {
launch(bgDispatcher) {
_batchModerationStatus.emit(BatchModerationStatus.Idle)
}
}
fun performBatchModeration(newStatus: CommentStatus) {
launch(bgDispatcher) {
if (!networkUtilsWrapper.isNetworkAvailable()) {
launch(bgDispatcher) {
_onSnackbarMessage.emit(SnackbarMessageHolder(UiStringRes(string.no_network_message)))
}
return@launch
}
if (newStatus == DELETED || newStatus == TRASH) {
_batchModerationStatus.emit(BatchModerationStatus.AskingToModerate(newStatus))
} else {
moderateSelectedComments(newStatus)
}
}
}
private fun moderateSelectedComments(newStatus: CommentStatus) {
launch(bgDispatcher) {
_batchModerationStatus.emit(BatchModerationStatus.Idle)
val commentsToModerate = _selectedComments.value.map { it.remoteCommentId }
_selectedComments.emit(emptyList())
unifiedCommentsListHandler.moderateComments(
ModerateCommentsParameters(
selectedSiteRepository.getSelectedSite()!!,
commentsToModerate,
newStatus
)
)
when (newStatus) {
APPROVED -> analyticsTrackerWrapper.track(COMMENT_BATCH_APPROVED)
UNAPPROVED -> analyticsTrackerWrapper.track(COMMENT_BATCH_UNAPPROVED)
SPAM -> analyticsTrackerWrapper.track(COMMENT_BATCH_SPAMMED)
TRASH -> analyticsTrackerWrapper.track(COMMENT_BATCH_TRASHED)
DELETED -> analyticsTrackerWrapper.track(COMMENT_BATCH_DELETED)
else -> { // noop
}
}
}
}
data class SelectedComment(val remoteCommentId: Long, val status: CommentStatus)
companion object {
private const val UI_STATE_FLOW_TIMEOUT_MS = 5000L
private const val COMMENT_PAGE_SIZE = 30
private const val UNREPLIED_COMMENT_PAGE_SIZE = 100
}
}
| gpl-2.0 | 65919b857242cdcd5c78faab585bfa0f | 45.683511 | 120 | 0.585769 | 6.135267 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddNamesToCallArgumentsIntention.kt | 1 | 2349 | // 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.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtLambdaArgument
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.LambdaArgument
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class AddNamesToCallArgumentsIntention : SelfTargetingRangeIntention<KtCallElement>(
KtCallElement::class.java,
KotlinBundle.lazyMessage("add.names.to.call.arguments")
) {
override fun applicabilityRange(element: KtCallElement): TextRange? {
val arguments = element.valueArguments
if (arguments.all { it.isNamed() || it is LambdaArgument }) return null
val resolvedCall = element.resolveToCall() ?: return null
if (!resolvedCall.candidateDescriptor.hasStableParameterNames()) return null
if (arguments.all {
AddNameToArgumentIntention.argumentMatchedAndCouldBeNamedInCall(it, resolvedCall, element.languageVersionSettings)
}
) {
val calleeExpression = element.calleeExpression ?: return null
if (arguments.size < 2) return calleeExpression.textRange
val endOffset = (arguments.firstOrNull() as? KtValueArgument)?.endOffset ?: return null
return TextRange(calleeExpression.startOffset, endOffset)
}
return null
}
override fun applyTo(element: KtCallElement, editor: Editor?) {
val arguments = element.valueArguments
val resolvedCall = element.resolveToCall() ?: return
for (argument in arguments) {
if (argument !is KtValueArgument || argument is KtLambdaArgument) continue
AddNameToArgumentIntention.apply(argument, resolvedCall, editor)
}
}
} | apache-2.0 | 266487adb8fff4723daa056960f18b27 | 46 | 158 | 0.750532 | 5.029979 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/expressionExt.kt | 1 | 3467 | // 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.util
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.base.psi.textRangeIn as _textRangeIn
fun KtCallElement.replaceOrCreateTypeArgumentList(newTypeArgumentList: KtTypeArgumentList) {
if (typeArgumentList != null) typeArgumentList?.replace(newTypeArgumentList)
else addAfter(
newTypeArgumentList,
calleeExpression,
)
}
fun KtModifierListOwner.hasInlineModifier() = hasModifier(KtTokens.INLINE_KEYWORD)
fun KtModifierListOwner.hasPrivateModifier() = hasModifier(KtTokens.PRIVATE_KEYWORD)
fun KtPrimaryConstructor.mustHaveValOrVar(): Boolean = containingClass()?.let {
it.isAnnotation() || it.hasInlineModifier()
} ?: false
// TODO: add cases
fun KtExpression.hasNoSideEffects(): Boolean = when (this) {
is KtStringTemplateExpression -> !hasInterpolation()
is KtConstantExpression -> true
else -> ConstantExpressionEvaluator.getConstant(this, analyze(BodyResolveMode.PARTIAL)) != null
}
@Deprecated("Please use org.jetbrains.kotlin.idea.base.psi.textRangeIn")
fun PsiElement.textRangeIn(other: PsiElement): TextRange = _textRangeIn(other)
fun KtDotQualifiedExpression.calleeTextRangeInThis(): TextRange? = callExpression?.calleeExpression?.textRangeIn(this)
fun KtNamedDeclaration.nameIdentifierTextRangeInThis(): TextRange? = nameIdentifier?.textRangeIn(this)
fun PsiElement.hasComments(): Boolean = anyDescendantOfType<PsiComment>()
fun KtDotQualifiedExpression.hasNotReceiver(): Boolean {
val element = getQualifiedElementSelector()?.mainReference?.resolve() ?: return false
return element is KtClassOrObject ||
element is KtConstructor<*> ||
element is KtCallableDeclaration && element.receiverTypeReference == null && (element.containingClassOrObject is KtObjectDeclaration?) ||
element is PsiMember && element.hasModifier(JvmModifier.STATIC) ||
element is PsiMethod && element.isConstructor
}
val KtExpression.isUnitLiteral: Boolean
get() = StandardNames.FqNames.unit.shortName() == (this as? KtNameReferenceExpression)?.getReferencedNameAsName()
val PsiElement.isAnonymousFunction: Boolean get() = this is KtNamedFunction && isAnonymousFunction
val KtNamedFunction.isAnonymousFunction: Boolean get() = nameIdentifier == null
val DeclarationDescriptor.isPrimaryConstructorOfDataClass: Boolean
get() = this is ConstructorDescriptor && this.isPrimary && this.constructedClass.isData
| apache-2.0 | c72514aa8a1d4fc8e27c39b5665eb6f6 | 45.851351 | 158 | 0.801269 | 5.046579 | false | false | false | false |
hsson/card-balance-app | app/src/main/java/se/creotec/chscardbalance2/model/Dish.kt | 1 | 977 | // Copyright (c) 2017 Alexander Hรฅkansson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package se.creotec.chscardbalance2.model
import com.google.gson.annotations.SerializedName
class Dish {
@SerializedName("title")
var title: String = ""
@SerializedName("desc")
var description: String = ""
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
val dish = other as Dish
return title == dish.title && description == dish.description
}
override fun hashCode(): Int {
var result = title.hashCode()
result = 31 * result + description.hashCode()
return result
}
override fun toString(): String {
return "Dish{" +
"title='" + title + '\'' +
", description='" + description + '\'' +
'}'
}
}
| mit | 6779abde73493f15126a9ce89211f0f8 | 27.705882 | 70 | 0.589139 | 4.41629 | false | false | false | false |
VTUZ-12IE1bzud/TruckMonitor-Android | app/src/main/kotlin/ru/annin/truckmonitor/presentation/ui/decoration/StickyHeaderDecoration.kt | 1 | 5919 | package ru.annin.truckmonitor.presentation.ui.decoration
import android.graphics.Canvas
import android.graphics.Rect
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import ru.annin.truckmonitor.presentation.ui.adapter.StickyHeaderAdapter
/**
* @author Pavel Annin.
*/
class StickyHeaderDecoration(
val adapter: StickyHeaderAdapter<RecyclerView.ViewHolder>,
val renderInline: Boolean = false) : RecyclerView.ItemDecoration() {
companion object {
const val NO_HEADER_ID = 1L
}
private val headerCache: MutableMap<Long, RecyclerView.ViewHolder> = HashMap()
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view)
var headerHeight = 0
if (position != RecyclerView.NO_POSITION
&& hasHeader(position)
&& showHeaderAboveItem(position)) {
val header = getHeader(parent, position).itemView
headerHeight = getHeaderHeightForLayout(header)
}
outRect.set(0, headerHeight, 0, 0)
}
override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val count = parent.childCount
var previousHeaderId: Long = -1
for (layoutPos in 0..count - 1) {
val child = parent.getChildAt(layoutPos)
val adapterPos = parent.getChildAdapterPosition(child)
if (adapterPos != RecyclerView.NO_POSITION && hasHeader(adapterPos)) {
val headerId = adapter.getHeaderId(adapterPos)
if (headerId != previousHeaderId) {
previousHeaderId = headerId
val header = getHeader(parent, adapterPos).itemView
canvas.save()
val left = child.left
val top = getHeaderTop(parent, child, header, adapterPos, layoutPos)
canvas.translate(left.toFloat(), top.toFloat())
header.translationX = left.toFloat()
header.translationY = top.toFloat()
header.draw(canvas)
canvas.restore()
}
}
}
}
fun clearHeaderCache() {
headerCache.clear()
}
fun findHeaderViewHolder(x: Float, y: Float): View? {
for (holder in headerCache.values) {
val child: View = holder.itemView
val translationX: Float = ViewCompat.getTranslationX(child)
val translationY: Float = ViewCompat.getTranslationY(child)
if (x >= child.left + translationX
&& x <= child.right + translationX
&& y >= child.top + translationY
&& y <= child.bottom + translationY) {
return child
}
}
return null
}
private fun showHeaderAboveItem(itemAdapterPosition: Int): Boolean {
if (itemAdapterPosition == 0) {
return true
}
return adapter.getHeaderId(itemAdapterPosition - 1) != adapter.getHeaderId(itemAdapterPosition)
}
private fun hasHeader(position: Int): Boolean {
return adapter.getHeaderId(position) != NO_HEADER_ID
}
private fun getHeader(parent: RecyclerView, position: Int): RecyclerView.ViewHolder {
val key = adapter.getHeaderId(position)
if (headerCache.containsKey(key)) {
return headerCache[key]!!
} else {
val holder: RecyclerView.ViewHolder = adapter.onCreateHeaderViewHolder(parent)
val header: View = holder.itemView
adapter.onBindHeaderViewHolder(holder, position)
val widthSpec: Int = View.MeasureSpec.makeMeasureSpec(parent.measuredWidth, View.MeasureSpec.EXACTLY)
val heightSpec: Int = View.MeasureSpec.makeMeasureSpec(parent.measuredHeight, View.MeasureSpec.UNSPECIFIED)
val childWidth: Int = ViewGroup.getChildMeasureSpec(widthSpec, parent.paddingLeft + parent.paddingRight, header.layoutParams.width)
val childHeight: Int = ViewGroup.getChildMeasureSpec(heightSpec, parent.paddingTop + parent.paddingBottom, header.layoutParams.height)
header.measure(childWidth, childHeight)
header.layout(0,0, header.measuredWidth, header.measuredHeight)
headerCache.put(key, holder)
return holder
}
}
private fun getHeaderTop(parent: RecyclerView, child: View, header: View, adapterPos: Int, layoutPos: Int): Int {
val headerHeight = getHeaderHeightForLayout(header)
var top: Int = (child.y - headerHeight).toInt()
if (layoutPos == 0) {
val count = parent.childCount
val currentId = adapter.getHeaderId(adapterPos)
// find next view with header and compute the offscreen push if needed
for (i in 1..count - 1) {
val adapterPosHere = parent.getChildAdapterPosition(parent.getChildAt(i))
if (adapterPosHere != RecyclerView.NO_POSITION) {
val nextId = adapter.getHeaderId(adapterPosHere)
if (nextId != currentId) {
val next = parent.getChildAt(i)
val offset = next.y.toInt() - (headerHeight + getHeader(parent, adapterPosHere).itemView.height)
if (offset < 0) {
return offset
} else {
break
}
}
}
}
top = Math.max(0, top)
}
return top
}
private fun getHeaderHeightForLayout(header: View): Int {
return if (renderInline) 0 else header.height
}
} | apache-2.0 | 2b515d8fa37c128e76b36ccae1f3e213 | 36.948718 | 146 | 0.605001 | 4.986521 | false | false | false | false |
icela/FriceEngine | src/org/frice/obj/effects/FunctionEffect.kt | 1 | 1004 | package org.frice.obj.effects
import org.frice.obj.sub.ImageObject
import org.frice.platform.FriceImage
import org.frice.resource.graphics.ColorResource
import org.frice.resource.graphics.FunctionResource
import org.frice.resource.image.ImageResource
/**
* Tested, Work stably.
* Created by ice1000 on 2016/8/24.
*
* @author ice1000
* @since v0.4.1
*/
class FunctionEffect(
res: FunctionResource,
x: Double,
y: Double) : ImageObject(res.resource, x, y) {
constructor(function: (Double) -> Double, x: Double, y: Double, width: Int, height: Int) :
this(FunctionResource(ColorResource.BLUE, function::invoke, width, height), x, y)
override val width: Double get() = res.image.width.toDouble()
override val height: Double get() = res.image.height.toDouble()
override val resource get() = ImageResource(image)
override val image: FriceImage get() = res.image
override fun scale(x: Double, y: Double) {
res.image = image.scale(image.width * x / 1000.0, image.height * y / 1000.0)
}
} | agpl-3.0 | 69a93aa66faa370e0df8842226f35707 | 28.558824 | 91 | 0.731076 | 3.249191 | false | false | false | false |
iMeiji/Daily | app/src/main/java/com/meiji/daily/util/HttpLoggingInterceptor.kt | 1 | 9374 | package com.meiji.daily.util
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.internal.http.HttpHeaders
import okhttp3.internal.platform.Platform
import okhttp3.internal.platform.Platform.INFO
import okio.Buffer
import java.io.EOFException
import java.io.IOException
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit
/**
* Created by Meiji on 2018/2/6.
*
* from:
* https://github.com/square/okhttp/blob/master/okhttp-logging-interceptor/src/main/java/okhttp3/logging/HttpLoggingInterceptor.java
*
* add:
* JsonFormat Print
*/
class HttpLoggingInterceptor
@JvmOverloads
constructor(private val logger: HttpLoggingInterceptor.Logger = HttpLoggingInterceptor.Logger.DEFAULT)
: Interceptor {
@Volatile
var mLevel: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.NONE
enum class Level {
/** No logs. */
NONE,
/**
* Logs request and response lines.
*
*
* Example:
* <pre>`--> POST /greeting http/1.1 (3-byte body)
*
* <-- 200 OK (22ms, 6-byte body)
`</pre> *
*/
BASIC,
/**
* Logs request and response lines and their respective headers.
*
*
* Example:
* <pre>`--> POST /greeting http/1.1
* Host: example.com
* Content-Type: plain/text
* Content-Length: 3
* --> END POST
*
* <-- 200 OK (22ms)
* Content-Type: plain/text
* Content-Length: 6
* <-- END HTTP
`</pre> *
*/
HEADERS,
/**
* Logs request and response lines and their respective headers and bodies (if present).
*
*
* Example:
* <pre>`--> POST /greeting http/1.1
* Host: example.com
* Content-Type: plain/text
* Content-Length: 3
*
* Hi?
* --> END POST
*
* <-- 200 OK (22ms)
* Content-Type: plain/text
* Content-Length: 6
*
* Hello!
* <-- END HTTP
`</pre> *
*/
BODY
}
interface Logger {
fun log(message: String)
companion object {
/** A [HttpLoggingInterceptor.Logger] defaults output appropriate for the current platform. */
val DEFAULT: HttpLoggingInterceptor.Logger = object : HttpLoggingInterceptor.Logger {
override fun log(message: String) {
Platform.get().log(INFO, message, null)
}
}
}
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val level = this.mLevel
val request = chain.request()
if (level == HttpLoggingInterceptor.Level.NONE) {
return chain.proceed(request)
}
val logBody = level == HttpLoggingInterceptor.Level.BODY
val logHeaders = logBody || level == HttpLoggingInterceptor.Level.HEADERS
val requestBody = request.body()
val hasRequestBody = requestBody != null
val connection = chain.connection()
var requestStartMessage = ("--> "
+ request.method()
+ ' '.toString() + request.url()
+ if (connection != null) " " + connection.protocol() else "")
if (!logHeaders && hasRequestBody) {
requestStartMessage += " (" + requestBody!!.contentLength() + "-byte body)"
}
logger.log(requestStartMessage)
if (logHeaders) {
if (hasRequestBody) {
// Request body headers are only present when installed as a network interceptor. Force
// them to be included (when available) so there values are known.
if (requestBody!!.contentType() != null) {
logger.log("Content-Type: " + requestBody.contentType()!!)
}
if (requestBody.contentLength().toInt() != -1) {
logger.log("Content-Length: " + requestBody.contentLength())
}
}
val headers = request.headers()
var i = 0
val count = headers.size()
while (i < count) {
val name = headers.name(i)
// Skip headers from the request body as they are explicitly logged above.
if (!"Content-Type".equals(name, ignoreCase = true) && !"Content-Length".equals(name, ignoreCase = true)) {
logger.log(name + ": " + headers.value(i))
}
i++
}
if (!logBody || !hasRequestBody) {
logger.log("--> END " + request.method())
} else if (bodyEncoded(request.headers())) {
logger.log("--> END " + request.method() + " (encoded body omitted)")
} else {
val buffer = Buffer()
requestBody!!.writeTo(buffer)
var charset: Charset? = UTF8
val contentType = requestBody.contentType()
if (contentType != null) {
charset = contentType.charset(UTF8)
}
logger.log("")
if (isPlaintext(buffer)) {
logger.log(buffer.readString(charset!!))
logger.log("--> END " + request.method()
+ " (" + requestBody.contentLength() + "-byte body)")
} else {
logger.log("--> END " + request.method() + " (binary "
+ requestBody.contentLength() + "-byte body omitted)")
}
}
}
val startNs = System.nanoTime()
val response: Response
try {
response = chain.proceed(request)
} catch (e: Exception) {
logger.log("<-- HTTP FAILED: " + e)
throw e
}
val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)
val responseBody = response.body()
val contentLength = responseBody!!.contentLength()
val bodySize = if (contentLength.toInt() != -1) contentLength.toString() + "-byte" else "unknown-length"
logger.log("<-- "
+ response.code()
+ (if (response.message().isEmpty()) "" else ' ' + response.message())
+ ' '.toString() + response.request().url()
+ " (" + tookMs + "ms" + (if (!logHeaders) ", $bodySize body" else "") + ')'.toString())
if (logHeaders) {
val headers = response.headers()
var i = 0
val count = headers.size()
while (i < count) {
logger.log(headers.name(i) + ": " + headers.value(i))
i++
}
if (!logBody || !HttpHeaders.hasBody(response)) {
logger.log("<-- END HTTP")
} else if (bodyEncoded(response.headers())) {
logger.log("<-- END HTTP (encoded body omitted)")
} else {
val source = responseBody.source()
source.request(java.lang.Long.MAX_VALUE) // Buffer the entire body.
val buffer = source.buffer()
var charset: Charset? = UTF8
val contentType = responseBody.contentType()
if (contentType != null) {
charset = contentType.charset(UTF8)
}
if (!isPlaintext(buffer)) {
logger.log("")
logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)")
return response
}
if (contentLength != 0L) {
logger.log("\n" + JsonUtil.convert(buffer.clone().readString(charset!!)))
}
logger.log("<-- END HTTP (" + buffer.size() + "-byte body)")
}
}
return response
}
private fun bodyEncoded(headers: Headers): Boolean {
val contentEncoding = headers.get("Content-Encoding")
return contentEncoding != null && !contentEncoding.equals("identity", ignoreCase = true)
}
companion object {
private val UTF8 = Charset.forName("UTF-8")
/**
* Returns true if the body in question probably contains human readable text. Uses a small sample
* of code points to detect unicode control characters commonly used in binary file signatures.
*/
internal fun isPlaintext(buffer: Buffer): Boolean {
try {
val prefix = Buffer()
val byteCount = if (buffer.size() < 64) buffer.size() else 64
buffer.copyTo(prefix, 0, byteCount)
for (i in 0..15) {
if (prefix.exhausted()) {
break
}
val codePoint = prefix.readUtf8CodePoint()
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false
}
}
return true
} catch (e: EOFException) {
return false // Truncated UTF-8 sequence.
}
}
}
}
| apache-2.0 | 27265398a14be47342e11851cc259966 | 33.336996 | 132 | 0.511841 | 4.846949 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/preview/html/CodeSpanRunnerGeneratingProvider.kt | 2 | 1844 | // 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.ui.preview.html
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.ast.ASTNode
import org.intellij.markdown.ast.LeafASTNode
import org.intellij.markdown.html.GeneratingProvider
import org.intellij.markdown.html.HtmlGenerator
import org.intellij.markdown.html.TrimmingInlineHolderProvider
import org.intellij.plugins.markdown.extensions.jcef.commandRunner.CommandRunnerExtension
import org.intellij.plugins.markdown.ui.preview.html.DefaultCodeFenceGeneratingProvider.Companion.escape
internal class CodeSpanRunnerGeneratingProvider(private val generatingProvider: GeneratingProvider,
val project: Project,
val file: VirtualFile) : TrimmingInlineHolderProvider() {
override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) {
val codeViewExtension = CommandRunnerExtension.getRunnerByFile(file)
if (codeViewExtension == null ) {
generatingProvider.processNode(visitor, text, node)
return
}
var codeLine = ""
for (child in childrenToRender(node)) {
if (child is LeafASTNode) { when (child.type) {
MarkdownTokenTypes.BACKTICK -> continue
else -> {
codeLine += text.substring(child.startOffset, child.endOffset)
}
}
}
}
visitor.consumeTagOpen(node, "code")
visitor.consumeHtml(codeViewExtension.processCodeLine(codeLine, false) + escape(codeLine))
visitor.consumeTagClose("code")
}
} | apache-2.0 | 2e2fa638bf9863ce3cec7e53dd73be50 | 45.125 | 158 | 0.732104 | 4.668354 | false | false | false | false |
JOML-CI/JOML | src/main/kotlin/org/joml/Operators.kt | 1 | 12129 | package org.joml
/* Matrix2f */
operator fun Matrix2f.minusAssign(m: Matrix2fc) {sub(m)}
operator fun Matrix2fc.minus(m: Matrix2fc): Matrix2f = sub(m,Matrix2f())
operator fun Matrix2f.plusAssign(m: Matrix2fc) {add(m)}
operator fun Matrix2fc.plus(m: Matrix2fc): Matrix2f = add(m,Matrix2f())
operator fun Matrix2f.timesAssign(m: Matrix2fc) {mul(m)}
operator fun Matrix2fc.times(m: Matrix2fc): Matrix2f = mul(m,Matrix2f())
operator fun Matrix2f.timesAssign(v: Vector2f) {transform(v)}
operator fun Matrix2fc.times(v: Vector2f): Vector2f = transform(v, Vector2f())
infix fun Matrix2fc.transform(v: Vector2f) {transform(v)}
/* Matrix2d */
operator fun Matrix2d.minusAssign(m: Matrix2dc) {sub(m)}
operator fun Matrix2dc.minus(m: Matrix2dc): Matrix2d = sub(m,Matrix2d())
operator fun Matrix2d.plusAssign(m: Matrix2dc) {add(m)}
operator fun Matrix2dc.plus(m: Matrix2dc): Matrix2d = add(m,Matrix2d())
operator fun Matrix2d.timesAssign(m: Matrix2dc) {mul(m)}
operator fun Matrix2dc.times(m: Matrix2dc): Matrix2d = mul(m,Matrix2d())
operator fun Matrix2d.timesAssign(m: Matrix2fc) {mul(m)}
operator fun Matrix2dc.times(m: Matrix2fc): Matrix2d = mul(m,Matrix2d())
operator fun Matrix2d.timesAssign(v: Vector2d) {transform(v)}
operator fun Matrix2dc.times(v: Vector2d): Vector2d = transform(v,Vector2d())
infix fun Matrix2dc.transform(v: Vector2d) {transform(v)}
/* Matrix3f */
operator fun Matrix3f.minusAssign(m: Matrix3f) {sub(m)}
operator fun Matrix3fc.minus(m: Matrix3f): Matrix3f = sub(m,Matrix3f())
operator fun Matrix3f.plusAssign(m: Matrix3fc) {add(m)}
operator fun Matrix3fc.plus(m: Matrix3fc): Matrix3f = add(m,Matrix3f())
operator fun Matrix3f.timesAssign(m: Matrix3fc) {mul(m)}
operator fun Matrix3fc.times(m: Matrix3fc): Matrix3f = mul(m,Matrix3f())
operator fun Matrix3f.timesAssign(v: Vector3f) {transform(v)}
operator fun Matrix3fc.times(v: Vector3f): Vector3f = transform(v,Vector3f())
operator fun Matrix3f.timesAssign(q: Quaternionfc) {rotate(q)}
operator fun Matrix3fc.times(q: Quaternionfc): Matrix3f = rotate(q,Matrix3f())
infix fun Matrix3f.rotate(q: Quaternionfc) {rotate(q)}
infix fun Matrix3fc.transform(v: Vector3f) {transform(v)}
/* Matrix3d */
operator fun Matrix3d.minusAssign(m: Matrix3d) {sub(m)}
operator fun Matrix3dc.minus(m: Matrix3d): Matrix3d = sub(m,Matrix3d())
operator fun Matrix3d.plusAssign(m: Matrix3dc) {add(m)}
operator fun Matrix3dc.plus(m: Matrix3dc): Matrix3d = add(m,Matrix3d())
operator fun Matrix3d.timesAssign(m: Matrix3dc) {mul(m)}
operator fun Matrix3dc.times(m: Matrix3dc): Matrix3d = mul(m,Matrix3d())
operator fun Matrix3d.timesAssign(m: Matrix3fc) {mul(m)}
operator fun Matrix3dc.times(m: Matrix3fc): Matrix3d = mul(m,Matrix3d())
operator fun Matrix3d.timesAssign(v: Vector3d) {transform(v)}
operator fun Matrix3dc.times(v: Vector3d): Vector3d = transform(v,Vector3d())
operator fun Matrix3d.timesAssign(v: Vector3f) {transform(v)}
operator fun Matrix3dc.times(v: Vector3f): Vector3f = transform(v,Vector3f())
operator fun Matrix3d.timesAssign(q: Quaternionfc) {rotate(q)}
operator fun Matrix3dc.times(q: Quaternionfc): Matrix3d = rotate(q,Matrix3d())
operator fun Matrix3d.timesAssign(q: Quaterniondc) {rotate(q)}
operator fun Matrix3dc.times(q: Quaterniondc): Matrix3d = rotate(q,Matrix3d())
infix fun Matrix3d.rotate(q: Quaternionfc) {rotate(q)}
infix fun Matrix3d.rotate(q: Quaterniondc) {rotate(q)}
infix fun Matrix3dc.transform(v: Vector3f) {transform(v)}
infix fun Matrix3dc.transform(v: Vector3d) {transform(v)}
/* Matrix4x3f */
operator fun Matrix4x3f.minusAssign(m: Matrix4x3f) {sub(m)}
operator fun Matrix4x3fc.minus(m: Matrix4x3f): Matrix4x3f = sub(m,Matrix4x3f())
operator fun Matrix4x3f.plusAssign(m: Matrix4x3fc) {add(m)}
operator fun Matrix4x3fc.plus(m: Matrix4x3fc): Matrix4x3f = add(m,Matrix4x3f())
operator fun Matrix4x3f.timesAssign(m: Matrix4x3fc) {mul(m)}
operator fun Matrix4x3fc.times(m: Matrix4x3fc): Matrix4x3f = mul(m,Matrix4x3f())
operator fun Matrix4x3f.timesAssign(v: Vector4f) {transform(v)}
operator fun Matrix4x3fc.times(v: Vector4f): Vector4f = transform(v,Vector4f())
operator fun Matrix4x3f.timesAssign(q: Quaternionfc) {rotate(q)}
operator fun Matrix4x3fc.times(q: Quaternionfc): Matrix4x3f = rotate(q,Matrix4x3f())
infix fun Matrix4x3f.rotate(q: Quaternionfc) {rotate(q)}
infix fun Matrix4x3fc.transform(v: Vector4f) {transform(v)}
infix fun Matrix4x3fc.transformPosition(v: Vector3f) {transformPosition(v)}
infix fun Matrix4x3fc.transformDirection(v: Vector3f) {transformDirection(v)}
/* Matrix4x3d */
operator fun Matrix4x3d.minusAssign(m: Matrix4x3dc) {sub(m)}
operator fun Matrix4x3dc.minus(m: Matrix4x3dc): Matrix4x3d = sub(m,Matrix4x3d())
operator fun Matrix4x3d.plusAssign(m: Matrix4x3dc) {add(m)}
operator fun Matrix4x3dc.plus(m: Matrix4x3dc): Matrix4x3d = add(m,Matrix4x3d())
operator fun Matrix4x3d.timesAssign(m: Matrix4x3fc) {mul(m)}
operator fun Matrix4x3dc.times(m: Matrix4x3fc): Matrix4x3d = mul(m,Matrix4x3d())
operator fun Matrix4x3d.timesAssign(m: Matrix4x3dc) {mul(m)}
operator fun Matrix4x3dc.times(m: Matrix4x3dc): Matrix4x3d = mul(m,Matrix4x3d())
operator fun Matrix4x3d.timesAssign(v: Vector4d) {transform(v)}
operator fun Matrix4x3dc.times(v: Vector4d): Vector4d = transform(v,Vector4d())
operator fun Matrix4x3d.timesAssign(q: Quaternionfc) {rotate(q)}
operator fun Matrix4x3dc.times(q: Quaternionfc): Matrix4x3d = rotate(q,Matrix4x3d())
operator fun Matrix4x3d.timesAssign(q: Quaterniondc) {rotate(q)}
operator fun Matrix4x3dc.times(q: Quaterniondc): Matrix4x3d = rotate(q,Matrix4x3d())
infix fun Matrix4x3d.rotate(q: Quaternionfc) {rotate(q)}
infix fun Matrix4x3d.rotate(q: Quaterniondc) {rotate(q)}
infix fun Matrix4x3dc.transform(v: Vector4d) {transform(v)}
infix fun Matrix4x3dc.transformPosition(v: Vector3d) {transformPosition(v)}
infix fun Matrix4x3dc.transformDirection(v: Vector3d) {transformDirection(v)}
/* Matrix4f */
operator fun Matrix4f.minusAssign(m: Matrix4f) {sub(m)}
operator fun Matrix4fc.minus(m: Matrix4f): Matrix4f = sub(m,Matrix4f())
operator fun Matrix4f.plusAssign(m: Matrix4fc) {add(m)}
operator fun Matrix4fc.plus(m: Matrix4fc): Matrix4f = add(m,Matrix4f())
operator fun Matrix4f.timesAssign(m: Matrix4fc) {mul(m)}
operator fun Matrix4fc.times(m: Matrix4fc): Matrix4f = mul(m,Matrix4f())
operator fun Matrix4f.timesAssign(m: Matrix4x3fc) {mul(m, this)}
operator fun Matrix4f.timesAssign(v: Vector4f) {transform(v)}
operator fun Matrix4fc.times(v: Vector4f): Vector4f = transform(v,Vector4f())
operator fun Matrix4f.timesAssign(q: Quaternionfc) {rotate(q)}
operator fun Matrix4fc.times(q: Quaternionfc): Matrix4f = rotate(q,Matrix4f())
infix fun Matrix4f.mulAffine(m: Matrix4fc) {this.mulAffine(m)}
infix fun Matrix4f.mulAffineR(m: Matrix4fc) {this.mulAffineR(m)}
infix fun Matrix4f.rotate(q: Quaternionfc) {rotate(q)}
infix fun Matrix4f.transform(v: Vector4f) {transform(v)}
infix fun Matrix4f.transformPosition(v: Vector3f) {transformPosition(v)}
infix fun Matrix4f.transformDirection(v: Vector3f) {transformDirection(v)}
/* Matrix4d */
operator fun Matrix4d.minusAssign(m: Matrix4dc) {sub(m)}
operator fun Matrix4dc.minus(m: Matrix4dc): Matrix4d = sub(m,Matrix4d())
operator fun Matrix4d.plusAssign(m: Matrix4dc) {add(m)}
operator fun Matrix4dc.plus(m: Matrix4dc): Matrix4d = add(m,Matrix4d())
operator fun Matrix4d.timesAssign(m: Matrix4dc) {mul(m)}
operator fun Matrix4dc.times(m: Matrix4dc): Matrix4d = mul(m,Matrix4d())
operator fun Matrix4d.timesAssign(m: Matrix4x3fc) {mul(m, this)}
operator fun Matrix4d.timesAssign(m: Matrix4x3dc) {mul(m, this)}
operator fun Matrix4d.timesAssign(v: Vector4d) {transform(v)}
operator fun Matrix4dc.times(v: Vector4d): Vector4d = transform(v,Vector4d())
operator fun Matrix4d.timesAssign(q: Quaternionfc) {rotate(q)}
operator fun Matrix4dc.times(q: Quaternionfc): Matrix4d = rotate(q,Matrix4d())
operator fun Matrix4d.timesAssign(q: Quaterniondc) {rotate(q)}
operator fun Matrix4dc.times(q: Quaterniondc): Matrix4d = rotate(q,Matrix4d())
infix fun Matrix4d.mulAffine(m: Matrix4dc) {this.mulAffine(m)}
infix fun Matrix4d.mulAffineR(m: Matrix4dc) {this.mulAffineR(m)}
infix fun Matrix4d.rotate(q: Quaternionfc) {rotate(q)}
infix fun Matrix4d.transform(v: Vector4d) {transform(v)}
infix fun Matrix4dc.transformPosition(v: Vector3d) {transformPosition(v)}
infix fun Matrix4dc.transformDirection(v: Vector3f) {transformDirection(v)}
infix fun Matrix4dc.transformDirection(v: Vector3d) {transformDirection(v)}
/* Vector2f */
operator fun Vector2f.minusAssign(v: Vector2fc) {sub(v)}
operator fun Vector2fc.minus(v: Vector2fc): Vector2f = sub(v,Vector2f())
operator fun Vector2f.plusAssign(v: Vector2fc) {add(v)}
operator fun Vector2fc.plus(v: Vector2fc): Vector2f = add(v,Vector2f())
operator fun Vector2f.unaryMinus() {negate()}
/* Vector2d */
operator fun Vector2d.minusAssign(v: Vector2fc) {sub(v)}
operator fun Vector2dc.minus(v: Vector2fc): Vector2d = sub(v,Vector2d())
operator fun Vector2d.minusAssign(v: Vector2dc) {sub(v)}
operator fun Vector2dc.minus(v: Vector2dc): Vector2d = sub(v,Vector2d())
operator fun Vector2d.plusAssign(v: Vector2fc) {add(v)}
operator fun Vector2dc.plus(v: Vector2fc): Vector2d = add(v,Vector2d())
operator fun Vector2d.plusAssign(v: Vector2dc) {add(v)}
operator fun Vector2dc.plus(v: Vector2dc): Vector2d = add(v,Vector2d())
operator fun Vector2d.unaryMinus() {negate()}
/* Vector3f */
operator fun Vector3f.minusAssign(v: Vector3fc) {sub(v)}
operator fun Vector3fc.minus(v: Vector3fc): Vector3f = sub(v,Vector3f())
operator fun Vector3f.plusAssign(v: Vector3fc) {add(v)}
operator fun Vector3fc.plus(v: Vector3fc): Vector3f = add(v,Vector3f())
operator fun Vector3f.unaryMinus() {negate()}
/* Vector3d */
operator fun Vector3d.minusAssign(v: Vector3fc) {sub(v)}
operator fun Vector3dc.minus(v: Vector3fc): Vector3d = sub(v,Vector3d())
operator fun Vector3d.minusAssign(v: Vector3dc) {sub(v)}
operator fun Vector3dc.minus(v: Vector3dc): Vector3d = sub(v,Vector3d())
operator fun Vector3d.plusAssign(v: Vector3fc) {add(v)}
operator fun Vector3dc.plus(v: Vector3fc): Vector3d = add(v,Vector3d())
operator fun Vector3d.plusAssign(v: Vector3dc) {add(v)}
operator fun Vector3dc.plus(v: Vector3dc): Vector3d = add(v,Vector3d())
operator fun Vector3d.unaryMinus() {negate()}
/* Vector4f */
operator fun Vector4f.minusAssign(v: Vector4fc) {sub(v)}
operator fun Vector4fc.minus(v: Vector4fc): Vector4f = sub(v,Vector4f())
operator fun Vector4f.plusAssign(v: Vector4fc) {add(v)}
operator fun Vector4fc.plus(v: Vector4fc): Vector4f = add(v,Vector4f())
operator fun Vector4f.unaryMinus() {negate()}
/* Vector4d */
operator fun Vector4d.minusAssign(v: Vector4fc) {sub(v)}
operator fun Vector4dc.minus(v: Vector4fc): Vector4d = sub(v,Vector4d())
operator fun Vector4d.minusAssign(v: Vector4dc) {sub(v)}
operator fun Vector4dc.minus(v: Vector4dc): Vector4d = sub(v,Vector4d())
operator fun Vector4d.plusAssign(v: Vector4fc) {add(v)}
operator fun Vector4dc.plus(v: Vector4fc): Vector4d = add(v,Vector4d())
operator fun Vector4d.plusAssign(v: Vector4dc) {add(v)}
operator fun Vector4dc.plus(v: Vector4dc): Vector4d = add(v,Vector4d())
operator fun Vector4d.unaryMinus() {negate()}
/* Quaternionf */
operator fun Quaternionf.minusAssign(q: Quaternionfc) {mul(q)}
operator fun Quaternionfc.minus(q: Quaternionfc): Quaternionf = mul(q,Quaternionf())
operator fun Quaternionf.unaryMinus() {conjugate()}
operator fun Quaternionf.timesAssign(v: Vector3f) {transform(v)}
operator fun Quaternionfc.times(v: Vector3f): Vector3f = transform(v,Vector3f())
operator fun Quaternionf.timesAssign(v: Vector4f) {transform(v)}
operator fun Quaternionfc.times(v: Vector4f): Vector4f = transform(v,Vector4f())
/* Quaterniond */
operator fun Quaterniond.minusAssign(q: Quaterniondc) {mul(q)}
operator fun Quaterniondc.minus(q: Quaterniondc): Quaterniond = mul(q,Quaterniond())
operator fun Quaterniond.unaryMinus() {conjugate()}
operator fun Quaterniond.timesAssign(v: Vector3d) {transform(v)}
operator fun Quaterniondc.times(v: Vector3d): Vector3d = transform(v,Vector3d())
operator fun Quaterniond.timesAssign(v: Vector4d) {transform(v)}
operator fun Quaterniondc.times(v: Vector4d): Vector4d = transform(v,Vector4d())
| mit | 78a271833929fd8cf7e1326265f4154e | 52.197368 | 84 | 0.767664 | 2.83985 | false | false | false | false |
RollnCode/BackTube | app/src/main/java/com/rollncode/backtube/player/TubePlayer.kt | 1 | 6279 | package com.rollncode.backtube.player
import android.annotation.SuppressLint
import android.app.Application
import android.app.Service
import android.content.Context
import android.net.Uri
import com.rollncode.backtube.api.TubeApi
import com.rollncode.backtube.api.TubeVideo
import com.rollncode.backtube.logic.NotificationController
import com.rollncode.backtube.logic.PlayerController
import com.rollncode.backtube.logic.TUBE_PLAYLIST
import com.rollncode.backtube.logic.TUBE_VIDEO
import com.rollncode.backtube.logic.TubeState
import com.rollncode.backtube.logic.TubeUri
import com.rollncode.backtube.logic.ViewController
import com.rollncode.backtube.logic.toLog
import com.rollncode.backtube.logic.whenDebug
import com.rollncode.utility.ICoroutines
import com.rollncode.utility.receiver.ObjectsReceiver
import com.rollncode.utility.receiver.ReceiverBus
import kotlinx.coroutines.experimental.Job
import java.lang.ref.Reference
import java.lang.ref.SoftReference
import java.lang.ref.WeakReference
object TubePlayer : ObjectsReceiver, ICoroutines {
private lateinit var context: Application
private var service: Reference<Service> = WeakReference<Service>(null)
override val jobs = mutableSetOf<Job>()
@SuppressLint("StaticFieldLeak")
private var notificationController: NotificationController? = null
private var playerController: PlayerController? = null
private var viewController: ViewController? = null
init {
ReceiverBus.subscribe(this,
TubeState.PLAY, TubeState.PAUSE, TubeState.SERVICE_START,
TubeState.SERVICE_STOP, TubeState.RELEASE,
TubeState.WINDOW_SHOW, TubeState.WINDOW_HIDE,
TubeState.LIST_SHOW, TubeState.LIST_HIGHLIGHT_ITEM,
TubeState.PREVIOUS, TubeState.NEXT)
}
fun attachContext(context: Context) {
this.context = context.applicationContext as Application
if (notificationController == null) {
notificationController = NotificationController(this.context)
playerController = PlayerController(notificationController ?: throw NullPointerException())
viewController = ViewController(this.context, playerController ?: throw NullPointerException())
}
if (context is Service) {
this.service = SoftReference(context)
notificationController?.context = context
}
notificationController?.showNotification()
}
fun play(context: Context, uri: Uri) {
attachContext(context)
val tubeUri = TubeUri(uri)
TubeState.currentUri = tubeUri.original
when (tubeUri.type) {
TUBE_VIDEO -> execute {
TubeApi.requestVideo(tubeUri.videoId,
{
toLog("requestVideo: $it")
playerController?.play(it, tubeUri.timeReference)
ReceiverBus.notify(TubeState.LIST_SHOW, emptyList<TubeVideo>())
},
{
ReceiverBus.notify(TubeState.SERVICE_STOP)
})
}
TUBE_PLAYLIST -> execute {
TubeApi.requestPlaylist(tubeUri.playlistId,
{
toLog("requestPlaylist: $it")
var index: Int? = null
var startSeconds = 0
var i = 0
for (video in it.videos) {
if (video.id == tubeUri.videoId) {
index = i
startSeconds = tubeUri.timeReference
break
}
i++
}
playerController?.play(it, index, startSeconds)
ReceiverBus.notify(TubeState.LIST_SHOW, it.videos)
},
{
ReceiverBus.notify(TubeState.SERVICE_STOP)
})
}
else -> ReceiverBus.notify(TubeState.SERVICE_STOP)
}
ReceiverBus.notify(TubeState.WINDOW_SHOW)
}
fun onServiceDestroy() {
service.get()?.run {
stopForeground(false)
service.clear()
}
notificationController?.context = context
notificationController?.showNotification()
}
override fun onObjectsReceive(event: Int, vararg objects: Any) {
when (event) {
TubeState.PLAY -> when (objects.size) {
0 -> playerController?.play()
1 -> playerController?.play(objects.first() as Int)
2 -> playerController?.play(objects.first() as Int, objects[1] as Int)
}
TubeState.PAUSE -> playerController?.pause()
TubeState.PREVIOUS -> playerController?.previous()
TubeState.NEXT -> playerController?.next()
TubeState.WINDOW_SHOW -> viewController?.show()
TubeState.WINDOW_HIDE -> viewController?.hide()
TubeState.LIST_SHOW -> {
@Suppress("UNCHECKED_CAST")
viewController?.showList(objects.first() as List<TubeVideo>)
}
TubeState.LIST_HIGHLIGHT_ITEM -> {
viewController?.highlightCurrent(objects.first() as Int)
}
TubeState.SERVICE_START -> TubeService.start(context)
TubeState.SERVICE_STOP -> onServiceDestroy()
TubeState.RELEASE -> release()
else -> whenDebug { throw IllegalStateException("Unknown event: $event") }
}
}
private fun release() {
ReceiverBus.notify(TubeState.CLOSE_APP)
service.clear()
cancelJobs()
notificationController?.release()
playerController?.release()
viewController?.release()
notificationController = null
playerController = null
viewController = null
}
} | apache-2.0 | 0cf9620ec06a666fc6385ce469aba3b1 | 37.765432 | 111 | 0.578914 | 5.125714 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/common/Histogram.kt | 1 | 2861 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"): you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.common
import com.google.common.collect.TreeMultiset
import java.util.*
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Utility class to build basic statistics about quantities.
*/
data class Histogram(
val median: Optional<Long>,
val p75: Optional<Long>,
val p99: Optional<Long>,
val min: Optional<Long>,
val max: Optional<Long>,
val mean: Optional<Double>,
val sum: Optional<Long>
) {
companion object {
@JvmStatic
fun empty() = Builder().build()
}
class Builder(
val samples: TreeMultiset<Long> = TreeMultiset.create(Long::compareTo)
) {
fun add(sample: Long) {
samples.add(sample)
}
fun build(): Histogram {
val entries = samples.toList()
val mean = meanAndSum(entries)
return Histogram(
median = nth(entries, 0.50),
p75 = nth(entries, 0.75),
p99 = nth(entries, 0.99),
min = nth(entries, 0.00),
max = nth(entries, 1.00),
mean = mean.first,
sum = mean.second
)
}
private fun meanAndSum(entries: List<Long>)
: Pair<Optional<Double>, Optional<Long>> {
val count = entries.size
if (count <= 0) return Optional.empty<Double>() to Optional.empty()
val sum = entries.reduce { a, b -> a + b }
val mean = sum.toDouble() / count.toDouble()
return Optional.of(mean) to Optional.of(sum)
}
/**
* Simplified accessor for n.
*/
private fun nth(samples: List<Long>, n: Double): Optional<Long> {
if (samples.isEmpty()) return Optional.empty()
val index = min(samples.size - 1,
max(0, (samples.size.toDouble() * n).roundToInt() - 1)
)
return Optional.ofNullable(samples[index])
}
}
}
| apache-2.0 | 181a263b957f7536204c92a46eb96600 | 29.43617 | 79 | 0.603985 | 4.182749 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/leetcode/subarray_sum_equals_k/Tests.kt | 1 | 1365 | package katas.kotlin.leetcode.subarray_sum_equals_k
import java.util.*
//
// https://leetcode.com/problems/subarray-sum-equals-k
//
// Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
// Constraints:
// - The length of the array is in range [1, 20000].
// - The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
//
// Example 1:
// Input:nums = [1,1,1], k = 2
// Output: 2
//
// 5 2 3 -4 -1 1
// 5 7 10 6 5 6 <- prefix sum
// f t
fun subarraySum(ints: IntArray, targetSum: Int): Int {
return subArrays(ints, targetSum).count()
}
private fun subArrays(ints: IntArray, targetSum: Int): Sequence<Pair<Int, Int>> = sequence {
(0..ints.lastIndex).forEach { from ->
var sum = 0
(from..ints.lastIndex).forEach { to ->
sum += ints[to]
if (sum == targetSum) yield(Pair(from, to))
}
}
}
fun subarraySum_cleverHashMap(nums: IntArray, targetSum: Int): Int {
var count = 0
val countBySum = HashMap<Int, Int>()
countBySum[0] = 1
var sum = 0
nums.forEach {
sum += it
count += countBySum.getOrDefault(sum - targetSum, defaultValue = 0)
countBySum[sum] = countBySum.getOrDefault(sum, defaultValue = 0) + 1
}
return count
} | unlicense | 774d0a1c8b54e1fcd2d6a8d626573654 | 27.458333 | 128 | 0.619048 | 3.353808 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/dynamodb/src/main/kotlin/com/kotlin/dynamodb/DeleteItem.kt | 1 | 2131 | // snippet-sourcedescription:[DeleteItem.kt demonstrates how to delete an item from an Amazon DynamoDB table.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon DynamoDB]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.dynamodb
// snippet-start:[dynamodb.kotlin.delete_item.import]
import aws.sdk.kotlin.services.dynamodb.DynamoDbClient
import aws.sdk.kotlin.services.dynamodb.model.AttributeValue
import aws.sdk.kotlin.services.dynamodb.model.DeleteItemRequest
import kotlin.system.exitProcess
// snippet-end:[dynamodb.kotlin.delete_item.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<tableName> <key> <keyval>
Where:
tableName - The Amazon DynamoDB table to delete the item from (for example, Music3).
key - The key used in the Amazon DynamoDB table (for example, Artist).
keyval - The key value that represents the item to delete (for example, Famous Band).
"""
if (args.size != 3) {
println(usage)
exitProcess(0)
}
val tableName = args[0]
val key = args[1]
val keyVal = args[2]
deleteDymamoDBItem(tableName, key, keyVal)
}
// snippet-start:[dynamodb.kotlin.delete_item.main]
suspend fun deleteDymamoDBItem(tableNameVal: String, keyName: String, keyVal: String) {
val keyToGet = mutableMapOf<String, AttributeValue>()
keyToGet[keyName] = AttributeValue.S(keyVal)
val request = DeleteItemRequest {
tableName = tableNameVal
key = keyToGet
}
DynamoDbClient { region = "us-east-1" }.use { ddb ->
ddb.deleteItem(request)
println("Item with key matching $keyVal was deleted")
}
}
// snippet-end:[dynamodb.kotlin.delete_item.main]
| apache-2.0 | f79a7f435935a2b3ee553dd2765ffc92 | 30.287879 | 110 | 0.688878 | 3.895795 | false | false | false | false |
MarkusAmshove/Kluent | common/src/test/kotlin/org/amshove/kluent/tests/basic/ShouldEqualShould.kt | 1 | 1773 | package org.amshove.kluent.tests.basic
import org.amshove.kluent.internal.assertFails
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeEqualToIgnoringCase
import org.amshove.kluent.tests.Person
import kotlin.test.Test
class ShouldEqualShould {
@Test
fun passWhenComparingEqualStrings() {
"hello world" shouldBeEqualTo "hello world"
}
@Test
fun passWhenComparingEqualStringsIgnoringCase() {
"hello world" shouldBeEqualToIgnoringCase "Hello World"
}
@Test
fun returnTheTestedInstance() {
val hello = "hello world"
val returnedInstance = hello shouldBeEqualTo "hello world"
hello shouldBeEqualTo returnedInstance
}
@Test
fun returnTheTestedInstanceIgnoringCase() {
val hello = "hello world"
val returnedInstance = hello shouldBeEqualToIgnoringCase "Hello World"
hello shouldBeEqualToIgnoringCase returnedInstance
}
@Test
fun failWhenComparingUnequalStrings() {
assertFails { "hello world!" shouldBeEqualTo "hello" }
}
@Test
fun failWhenComparingUnequalStringsIgnoringCase() {
assertFails { "hello world!" shouldBeEqualToIgnoringCase "Hello" }
}
@Test
fun failWhenComparingDifferentTypes() {
assertFails { "hello world" shouldBeEqualTo 5 }
}
@Test
fun passWhenCheckingTwoDataObjectsWithSameValues() {
val firstObject = Person("Jon", "Doe")
val secondObject = Person("Jon", "Doe")
firstObject shouldBeEqualTo secondObject
}
@Test
fun failWhenCheckingTwoDataObjectsWithDifferentValues() {
val jane = Person("Jane", "Doe")
val jon = Person("Jon", "Doe")
assertFails { jane shouldBeEqualTo jon }
}
} | mit | 3535cb1796190e85cd101bd54f44fe81 | 27.15873 | 78 | 0.693175 | 4.938719 | false | true | false | false |
paplorinc/intellij-community | python/src/com/jetbrains/python/psi/impl/stubs/PyDataclassStubs.kt | 1 | 2742 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.psi.impl.stubs
import com.intellij.psi.stubs.StubInputStream
import com.intellij.psi.stubs.StubOutputStream
import com.jetbrains.python.codeInsight.stdlib.parseDataclassParametersForStub
import com.jetbrains.python.psi.PyClass
import com.jetbrains.python.psi.stubs.PyDataclassStub
import java.io.IOException
class PyDataclassStubType : PyCustomClassStubType<PyDataclassStub>() {
override fun createStub(psi: PyClass): PyDataclassStub? {
return PyDataclassStubImpl.create(psi)
}
@Throws(IOException::class)
override fun deserializeStub(stream: StubInputStream): PyDataclassStub? {
return PyDataclassStubImpl.deserialize(stream)
}
}
class PyDataclassStubImpl private constructor(private val type: String,
private val init: Boolean,
private val repr: Boolean,
private val eq: Boolean,
private val order: Boolean,
private val unsafeHash: Boolean,
private val frozen: Boolean) : PyDataclassStub {
companion object {
fun create(cls: PyClass): PyDataclassStub? {
return parseDataclassParametersForStub(cls)?.let {
PyDataclassStubImpl(it.type.toString(), it.init, it.repr, it.eq, it.order, it.unsafeHash, it.frozen)
}
}
@Throws(IOException::class)
fun deserialize(stream: StubInputStream): PyDataclassStub? {
val type = stream.readNameString() ?: return null
val init = stream.readBoolean()
val repr = stream.readBoolean()
val eq = stream.readBoolean()
val order = stream.readBoolean()
val unsafeHash = stream.readBoolean()
val frozen = stream.readBoolean()
return PyDataclassStubImpl(type, init, repr, eq, order, unsafeHash, frozen)
}
}
override fun getTypeClass(): Class<out PyCustomClassStubType<out PyCustomClassStub>> = PyDataclassStubType::class.java
override fun serialize(stream: StubOutputStream) {
stream.writeName(type)
stream.writeBoolean(init)
stream.writeBoolean(repr)
stream.writeBoolean(eq)
stream.writeBoolean(order)
stream.writeBoolean(unsafeHash)
stream.writeBoolean(frozen)
}
override fun getType() = type
override fun initValue() = init
override fun reprValue() = repr
override fun eqValue() = eq
override fun orderValue() = order
override fun unsafeHashValue() = unsafeHash
override fun frozenValue() = frozen
} | apache-2.0 | 0f12d9cf4afd532c0cbd26ce577717df | 36.575342 | 140 | 0.673231 | 4.835979 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | app/src/main/java/de/ph1b/audiobook/features/bookCategory/BookCategoryViewModel.kt | 1 | 2200 | package de.ph1b.audiobook.features.bookCategory
import de.ph1b.audiobook.data.repo.BookRepository
import de.ph1b.audiobook.features.bookOverview.GridMode
import de.ph1b.audiobook.features.bookOverview.list.BookComparator
import de.ph1b.audiobook.features.bookOverview.list.BookOverviewModel
import de.ph1b.audiobook.features.bookOverview.list.header.BookOverviewCategory
import de.ph1b.audiobook.features.gridCount.GridCount
import de.ph1b.audiobook.injection.PrefKeys
import de.ph1b.audiobook.misc.Observables
import de.ph1b.audiobook.persistence.pref.Pref
import io.reactivex.Observable
import java.util.UUID
import javax.inject.Inject
import javax.inject.Named
class BookCategoryViewModel
@Inject constructor(
private val repo: BookRepository,
@Named(PrefKeys.CURRENT_BOOK)
private val currentBookIdPref: Pref<UUID>,
@Named(PrefKeys.GRID_MODE)
private val gridModePref: Pref<GridMode>,
private val gridCount: GridCount,
private val comparatorPrefForCategory: @JvmSuppressWildcards Map<BookOverviewCategory, Pref<BookComparator>>
) {
lateinit var category: BookOverviewCategory
private fun comparatorPref(): Pref<BookComparator> = comparatorPrefForCategory[category]!!
fun get(): Observable<BookCategoryState> {
val comparatorStream = comparatorPref().stream
return Observables.combineLatest(
gridModePref.stream,
repo.booksStream(),
comparatorStream
) { gridMode, books, comparator ->
val gridColumnCount = gridCount.gridColumnCount(gridMode)
val currentBookId = currentBookIdPref.value
val models = books.asSequence()
.filter(category.filter)
.sortedWith(comparator)
.map { book ->
BookOverviewModel(
book = book,
isCurrentBook = book.id == currentBookId,
useGridView = gridColumnCount > 1
)
}
.toList()
BookCategoryState(gridColumnCount, models)
}
}
fun sort(comparator: BookComparator) {
comparatorPref().value = comparator
}
fun bookSorting(): BookComparator {
return comparatorPref().value
}
}
data class BookCategoryState(
val gridColumnCount: Int,
val models: List<BookOverviewModel>
)
| lgpl-3.0 | 5027c28548a4d7fe0f1039c730d7fe24 | 31.352941 | 110 | 0.750455 | 4.238921 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/dialog/LoginPrompt.kt | 2 | 3383 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.ui.dialog
import io.kvision.core.StringPair
import io.kvision.form.select.SimpleSelect
import io.kvision.form.text.Password
import io.kvision.form.text.Text
import org.apache.causeway.client.kroviz.core.event.ReplayController
import org.apache.causeway.client.kroviz.to.Link
import org.apache.causeway.client.kroviz.to.ValueType
import org.apache.causeway.client.kroviz.ui.core.*
class LoginPrompt(val nextController: Controller? = null) : Controller() {
//Default values
private var url = Constants.demoUrl
private var username = Constants.demoUser
private var password = Constants.demoPass
override fun open() {
val formItems = mutableListOf<FormItem>()
val urlList = mutableListOf<StringPair>()
urlList.add(StringPair(Constants.demoUrl, Constants.demoUrl))
urlList.add(StringPair(Constants.demoUrlRemote, Constants.demoUrlRemote))
urlList.add(StringPair(Constants.domoxUrl, Constants.domoxUrl))
formItems.add(FormItem("Url", ValueType.SIMPLE_SELECT, urlList))
formItems.add(FormItem("User", ValueType.TEXT, username))
formItems.add(FormItem("Password", ValueType.PASSWORD, password))
dialog = RoDialog(caption = "Connect", items = formItems, controller = this, heightPerc = 27)
val at = ViewManager.position!!
dialog.open(at)
}
override fun execute(action: String?) {
extractUserInput()
if (nextController is ReplayController) {
nextController.initUnderTest(url, username, password)
nextController.open()
} else {
SessionManager.login(url, username, password)
val link = Link(href = url + Constants.restInfix)
invoke(link)
ViewManager.closeDialog(dialog)
}
}
private fun extractUserInput() {
//function has a side effect, ie. changes variable values
var key: String?
val formPanel = dialog.formPanel
val kids = formPanel!!.getChildren()
//iterate over FormItems (0,1,2) but not Buttons(3,4)
for (i in kids) {
when (i) {
is SimpleSelect -> {
url = i.getValue()!!
}
is Text -> {
key = i.label!!
if (key == "User")
username = i.getValue()!!
}
is Password -> {
password = i.getValue()!!
}
}
}
}
}
| apache-2.0 | e81a2993c8b30d3289cbe76b7c552af0 | 37.885057 | 101 | 0.644398 | 4.382124 | false | false | false | false |
google/intellij-community | tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/runner/IDERunContext.kt | 1 | 13789 | package com.intellij.ide.starter.runner
import com.intellij.ide.starter.bus.EventState
import com.intellij.ide.starter.bus.StarterBus
import com.intellij.ide.starter.di.di
import com.intellij.ide.starter.ide.CodeInjector
import com.intellij.ide.starter.ide.IDETestContext
import com.intellij.ide.starter.ide.command.MarshallableCommand
import com.intellij.ide.starter.isClassFileVerificationEnabled
import com.intellij.ide.starter.models.IDEStartResult
import com.intellij.ide.starter.models.VMOptions
import com.intellij.ide.starter.models.andThen
import com.intellij.ide.starter.process.collectJavaThreadDump
import com.intellij.ide.starter.process.destroyGradleDaemonProcessIfExists
import com.intellij.ide.starter.process.exec.ExecOutputRedirect
import com.intellij.ide.starter.process.exec.ExecTimeoutException
import com.intellij.ide.starter.process.exec.ProcessExecutor
import com.intellij.ide.starter.process.getJavaProcessId
import com.intellij.ide.starter.profiler.ProfilerInjector
import com.intellij.ide.starter.profiler.ProfilerType
import com.intellij.ide.starter.report.ErrorReporter
import com.intellij.ide.starter.system.SystemInfo
import com.intellij.ide.starter.utils.*
import kotlinx.coroutines.delay
import org.kodein.di.direct
import org.kodein.di.instance
import java.io.Closeable
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.io.path.absolutePathString
import kotlin.io.path.createDirectories
import kotlin.io.path.div
import kotlin.io.path.listDirectoryEntries
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.measureTime
interface IDERunCloseContext {
val wasRunSuccessful: Boolean
}
data class IDERunContext(
val testContext: IDETestContext,
val patchVMOptions: VMOptions.() -> VMOptions = { this },
val commandLine: IDECommandLine? = null,
val commands: Iterable<MarshallableCommand> = listOf(),
val codeBuilder: (CodeInjector.() -> Unit)? = null,
val runTimeout: Duration = 10.minutes,
val dumpThreadInterval: Duration = 10.minutes,
val useStartupScript: Boolean = true,
val closeHandlers: List<IDERunCloseContext.() -> Unit> = listOf(),
val verboseOutput: Boolean = false,
val launchName: String = "",
val expectedKill: Boolean = false,
val collectNativeThreads: Boolean = false
) {
val contextName: String
get() = if (launchName.isNotEmpty()) {
"${testContext.testName}/$launchName"
}
else {
testContext.testName
}
val jvmCrashLogDirectory by lazy { testContext.paths.logsDir.resolve("jvm-crash").createDirectories() }
val heapDumpOnOomDirectory by lazy { testContext.paths.logsDir.resolve("heap-dump").createDirectories() }
fun verbose() = copy(verboseOutput = true)
@Suppress("unused")
fun withVMOptions(patchVMOptions: VMOptions.() -> VMOptions) = addVMOptionsPatch(patchVMOptions)
fun addVMOptionsPatch(patchVMOptions: VMOptions.() -> VMOptions) = copy(
patchVMOptions = this.patchVMOptions.andThen(patchVMOptions)
)
fun addCompletionHandler(handler: IDERunCloseContext.() -> Unit) = this.copy(closeHandlers = closeHandlers + handler)
fun uploadProfilerResultsToCIServer(profilerSnapshotsDir: Path, artifactName: String) =
this.addCompletionHandler {
testContext.publishArtifact(source = profilerSnapshotsDir, artifactName = artifactName)
}
private fun installProfiler(): IDERunContext {
return when (val profilerType = testContext.profilerType) {
ProfilerType.ASYNC, ProfilerType.YOURKIT -> {
val profiler = di.direct.instance<ProfilerInjector>(tag = profilerType)
logOutput("Injecting profiler ${profiler.type.kind}")
profiler.injectProfiler(this)
}
ProfilerType.NONE -> {
logOutput("No profiler is specified. Skipping profiler setup")
return this
}
}
}
private fun calculateVmOptions(): VMOptions = testContext.ide.originalVMOptions
.disableStartupDialogs()
.usingStartupFramework()
.setFatalErrorNotificationEnabled()
.setFlagIntegrationTests()
.takeScreenshotIfFailure(testContext.paths.logsDir)
.withJvmCrashLogDirectory(jvmCrashLogDirectory)
.withHeapDumpOnOutOfMemoryDirectory(heapDumpOnOomDirectory)
.let { if (isClassFileVerificationEnabled) it.withClassFileVerification() else it }
.let { testContext.testCase.vmOptionsFix(it) }
.let { testContext.patchVMOptions(it) }
.patchVMOptions()
.let {
if (!useStartupScript) {
require(commands.count() > 0) { "script builder is not allowed when useStartupScript is disabled" }
it
}
else
it.installTestScript(testName = contextName, paths = testContext.paths, commands = commands)
}
// TODO: refactor this https://youtrack.jetbrains.com/issue/AT-18/Simplify-refactor-code-for-starting-IDE-in-IdeRunContext
private fun prepareToRunIDE(): IDEStartResult {
StarterBus.post(IdeLaunchEvent(EventState.BEFORE, this))
deleteSavedAppStateOnMac()
val paths = testContext.paths
val logsDir = paths.logsDir.createDirectories()
paths.snapshotsDir.createDirectories()
val disabledPlugins = paths.configDir.resolve("disabled_plugins.txt")
if (disabledPlugins.toFile().exists()) {
logOutput("The list of disabled plugins: " + disabledPlugins.toFile().readText())
}
val stdout = if (verboseOutput) ExecOutputRedirect.ToStdOut("[ide-${contextName}-out]") else ExecOutputRedirect.ToString()
val stderr = ExecOutputRedirect.ToStdOut("[ide-${contextName}-err]")
var isRunSuccessful = true
val host by lazy { di.direct.instance<CodeInjector>() }
try {
val codeBuilder = codeBuilder
if (codeBuilder != null) {
host.codeBuilder()
}
val finalOptions: VMOptions = calculateVmOptions()
if (codeBuilder != null) {
host.setup(testContext)
}
testContext.setProviderMemoryOnlyOnLinux()
val jdkHome: Path by lazy {
try {
testContext.ide.resolveAndDownloadTheSameJDK()
}
catch (e: Exception) {
logError("Failed to download the same JDK as in ${testContext.ide.build}")
logError(e.stackTraceToString())
val defaultJavaHome = resolveInstalledJdk11()
logOutput("JDK is not found in ${testContext.ide.build}. Fallback to default java: $defaultJavaHome")
defaultJavaHome
}
}
val startConfig = testContext.ide.startConfig(finalOptions, logsDir)
if (startConfig is Closeable) {
addCompletionHandler { startConfig.close() }
}
val commandLineArgs = when (val cmd = commandLine ?: IDECommandLine.OpenTestCaseProject) {
is IDECommandLine.Args -> cmd.args
is IDECommandLine.OpenTestCaseProject -> listOf(testContext.resolvedProjectHome.toAbsolutePath().toString())
}
val finalEnvVariables = startConfig.environmentVariables + finalOptions.env
val extendedEnvVariablesWithJavaHome = finalEnvVariables.toMutableMap()
extendedEnvVariablesWithJavaHome.putIfAbsent("JAVA_HOME", jdkHome.absolutePathString())
val finalArgs = startConfig.commandLine + commandLineArgs
logOutput(buildString {
appendLine("Starting IDE for ${contextName} with timeout $runTimeout")
appendLine(" Command line: [" + finalArgs.joinToString() + "]")
appendLine(" VM Options: [" + finalOptions.toString().lineSequence().map { it.trim() }.joinToString(" ") + "]")
appendLine(" On Java : [" + System.getProperty("java.home") + "]")
})
File(finalArgs.first()).setExecutable(true)
val executionTime = measureTime {
ProcessExecutor(
presentableName = "run-ide-$contextName",
workDir = startConfig.workDir,
environmentVariables = extendedEnvVariablesWithJavaHome,
timeout = runTimeout,
args = finalArgs,
errorDiagnosticFiles = startConfig.errorDiagnosticFiles,
stdoutRedirect = stdout,
stderrRedirect = stderr,
onProcessCreated = { process, pid ->
val javaProcessId by lazy { getJavaProcessId(jdkHome, startConfig.workDir, pid, process) }
val monitoringThreadDumpDir = logsDir.resolve("monitoring-thread-dumps").createDirectories()
var cnt = 0
while (process.isAlive) {
delay(dumpThreadInterval)
if (!process.isAlive) break
val dumpFile = monitoringThreadDumpDir.resolve("threadDump-${++cnt}-${System.currentTimeMillis()}" + ".txt")
logOutput("Dumping threads to $dumpFile")
catchAll { collectJavaThreadDump(jdkHome, startConfig.workDir, javaProcessId, dumpFile, false) }
}
},
onBeforeKilled = { process, pid ->
if (!expectedKill) {
val javaProcessId by lazy { getJavaProcessId(jdkHome, startConfig.workDir, pid, process) }
if (collectNativeThreads) {
val fileToStoreNativeThreads = logsDir.resolve("native-thread-dumps.txt")
startProfileNativeThreads(javaProcessId.toString())
delay(15.seconds)
stopProfileNativeThreads(javaProcessId.toString(), fileToStoreNativeThreads.toAbsolutePath().toString())
}
val dumpFile = logsDir.resolve("threadDump-before-kill-${System.currentTimeMillis()}" + ".txt")
catchAll { collectJavaThreadDump(jdkHome, startConfig.workDir, javaProcessId, dumpFile) }
}
takeScreenshot(logsDir)
}
).start()
}
logOutput("IDE run $contextName completed in $executionTime")
require(FileSystem.countFiles(paths.configDir) > 3) {
"IDE must have created files under config directory at ${paths.configDir}. Were .vmoptions included correctly?"
}
require(FileSystem.countFiles(paths.systemDir) > 1) {
"IDE must have created files under system directory at ${paths.systemDir}. Were .vmoptions included correctly?"
}
val vmOptionsDiff = startConfig.vmOptionsDiff()
if (vmOptionsDiff != null && !vmOptionsDiff.isEmpty) {
logOutput("VMOptions were changed:")
logOutput("new lines:")
vmOptionsDiff.newLines.forEach { logOutput(" $it") }
logOutput("removed lines:")
vmOptionsDiff.missingLines.forEach { logOutput(" $it") }
logOutput()
}
return IDEStartResult(runContext = this, executionTime = executionTime, vmOptionsDiff = vmOptionsDiff, logsDir = logsDir)
}
catch (t: Throwable) {
isRunSuccessful = false
if (t is ExecTimeoutException && !expectedKill) {
error("Timeout of IDE run $contextName for $runTimeout")
}
else {
logOutput("IDE run for $contextName has been expected to be killed after $runTimeout")
}
val failureCauseFile = testContext.paths.logsDir.resolve("failure_cause.txt")
val errorMessage = if (Files.exists(failureCauseFile)) {
Files.readString(failureCauseFile)
}
else {
t.message ?: t.javaClass.name
}
if (!expectedKill) {
throw Exception(errorMessage, t)
}
else {
return IDEStartResult(runContext = this, executionTime = runTimeout, logsDir = logsDir)
}
}
finally {
collectJBRDiagnosticFilesIfExist(testContext)
try {
if (SystemInfo.isWindows) {
destroyGradleDaemonProcessIfExists()
}
listOf(heapDumpOnOomDirectory, jvmCrashLogDirectory).filter { dir ->
dir.listDirectoryEntries().isEmpty()
}.forEach { it.toFile().deleteRecursively() }
ErrorReporter.reportErrorsAsFailedTests(logsDir / "script-errors", this)
publishArtifacts(isRunSuccessful)
if (codeBuilder != null) {
host.tearDown(testContext)
}
val closeContext = object : IDERunCloseContext {
override val wasRunSuccessful: Boolean = isRunSuccessful
}
closeHandlers.forEach {
try {
it.invoke(closeContext)
}
catch (t: Throwable) {
logOutput("Failed to complete close step. ${t.message}.\n" + t)
t.printStackTrace(System.err)
}
}
}
finally {
StarterBus.post(IdeLaunchEvent(EventState.AFTER, this))
}
}
}
private fun publishArtifacts(isRunSuccessful: Boolean) {
// publish artifacts to directory with a test in any case
testContext.publishArtifact(
source = testContext.paths.logsDir,
artifactPath = contextName,
artifactName = formatArtifactName("logs", testContext.testName)
)
if (!isRunSuccessful)
testContext.publishArtifact(
source = testContext.paths.logsDir,
artifactPath = "_crashes/$contextName",
artifactName = formatArtifactName("crash", testContext.testName)
)
}
fun runIDE(): IDEStartResult {
return installProfiler().prepareToRunIDE()
}
private fun deleteSavedAppStateOnMac() {
if (SystemInfo.isMac) {
val filesToBeDeleted = listOf(
"com.jetbrains.${testContext.testCase.ideInfo.installerProductName}-EAP.savedState",
"com.jetbrains.${testContext.testCase.ideInfo.installerProductName}.savedState"
)
val home = System.getProperty("user.home")
val savedAppStateDir = Paths.get(home).resolve("Library").resolve("Saved Application State")
savedAppStateDir.toFile()
.walkTopDown().maxDepth(1)
.filter { file -> filesToBeDeleted.any { fileToBeDeleted -> file.name == fileToBeDeleted } }
.forEach { it.deleteRecursively() }
}
}
}
| apache-2.0 | fe2b5f9dfa6bff3d94068f54c1544795 | 37.951977 | 127 | 0.692726 | 4.576502 | false | true | false | false |
google/intellij-community | plugins/kotlin/native/src/org/jetbrains/kotlin/ide/konan/NativeDefinitions.kt | 3 | 9493 | // 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.ide.konan
import com.intellij.extapi.psi.PsiFileBase
import com.intellij.lang.*
import com.intellij.lexer.FlexAdapter
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.HighlighterColors
import com.intellij.openapi.fileTypes.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.tree.*
import javax.swing.Icon
import java.io.Reader
import org.jetbrains.kotlin.ide.konan.psi.*
import org.jetbrains.kotlin.idea.KotlinIcons
const val KOTLIN_NATIVE_DEFINITIONS_FILE_EXTENSION = "def"
const val KOTLIN_NATIVE_DEFINITIONS_ID = "KND"
val KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION get() = KotlinNativeBundle.message("kotlin.native.definitions.description")
object NativeDefinitionsFileType : LanguageFileType(NativeDefinitionsLanguage.INSTANCE) {
override fun getName(): String = "Kotlin/Native Def"
override fun getDescription(): String = KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION
override fun getDefaultExtension(): String = KOTLIN_NATIVE_DEFINITIONS_FILE_EXTENSION
override fun getIcon(): Icon = KotlinIcons.NATIVE
}
class NativeDefinitionsLanguage private constructor() : Language(KOTLIN_NATIVE_DEFINITIONS_ID) {
companion object {
val INSTANCE = NativeDefinitionsLanguage()
}
override fun getDisplayName(): String = KotlinNativeBundle.message("kotlin.native.definitions.short")
}
class NativeDefinitionsFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, NativeDefinitionsLanguage.INSTANCE) {
override fun getFileType(): FileType = NativeDefinitionsFileType
override fun toString(): String = KOTLIN_NATIVE_DEFINITIONS_DESCRIPTION
override fun getIcon(flags: Int): Icon? = super.getIcon(flags)
}
class NativeDefinitionsLexerAdapter : FlexAdapter(NativeDefinitionsLexer(null as Reader?))
private object NativeDefinitionsTokenSets {
val COMMENTS: TokenSet = TokenSet.create(NativeDefinitionsTypes.COMMENT)
}
class NativeDefinitionsParserDefinition : ParserDefinition {
private val FILE = IFileElementType(NativeDefinitionsLanguage.INSTANCE)
override fun getWhitespaceTokens(): TokenSet = TokenSet.WHITE_SPACE
override fun getCommentTokens(): TokenSet = NativeDefinitionsTokenSets.COMMENTS
override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY
override fun getFileNodeType(): IFileElementType = FILE
override fun createLexer(project: Project): Lexer = NativeDefinitionsLexerAdapter()
override fun createParser(project: Project): PsiParser = NativeDefinitionsParser()
override fun createFile(viewProvider: FileViewProvider): PsiFile = NativeDefinitionsFile(viewProvider)
override fun createElement(node: ASTNode): PsiElement = NativeDefinitionsTypes.Factory.createElement(node)
override fun spaceExistenceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements =
ParserDefinition.SpaceRequirements.MAY
}
class CLanguageInjector : LanguageInjector {
val cLanguage = Language.findLanguageByID("ObjectiveC")
override fun getLanguagesToInject(host: PsiLanguageInjectionHost, registrar: InjectedLanguagePlaces) {
if (!host.isValid) return
if (host is NativeDefinitionsCodeImpl && cLanguage != null) {
val range = host.getTextRange().shiftLeft(host.startOffsetInParent)
registrar.addPlace(cLanguage, range, null, null)
}
}
}
object NativeDefinitionsSyntaxHighlighter : SyntaxHighlighterBase() {
override fun getTokenHighlights(tokenType: IElementType?): Array<TextAttributesKey> =
when (tokenType) {
TokenType.BAD_CHARACTER -> BAD_CHAR_KEYS
NativeDefinitionsTypes.COMMENT -> COMMENT_KEYS
NativeDefinitionsTypes.DELIM -> COMMENT_KEYS
NativeDefinitionsTypes.SEPARATOR -> OPERATOR_KEYS
NativeDefinitionsTypes.UNKNOWN_KEY -> BAD_CHAR_KEYS
NativeDefinitionsTypes.UNKNOWN_PLATFORM -> BAD_CHAR_KEYS
NativeDefinitionsTypes.VALUE -> VALUE_KEYS
// known properties
NativeDefinitionsTypes.COMPILER_OPTS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.DEPENDS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.DISABLE_DESIGNATED_INITIALIZER_CHECKS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.ENTRY_POINT -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.EXCLUDE_DEPENDENT_MODULES -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.EXCLUDE_SYSTEM_LIBS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.EXCLUDED_FUNCTIONS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.EXCLUDED_MACROS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.EXPORT_FORWARD_DECLARATIONS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.HEADERS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.HEADER_FILTER -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.LANGUAGE -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.LIBRARY_PATHS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.LINKER -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.LINKER_OPTS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.MODULES -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.NON_STRICT_ENUMS -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.NO_STRING_CONVERSION -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.PACKAGE -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.STATIC_LIBRARIES -> KNOWN_PROPERTIES_KEYS
NativeDefinitionsTypes.STRICT_ENUMS -> KNOWN_PROPERTIES_KEYS
// known extensions
NativeDefinitionsTypes.ANDROID -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ANDROID_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ANDROID_X86 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ANDROID_ARM32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ANDROID_ARM64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ARM32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.ARM64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.IOS -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.IOS_ARM32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.IOS_ARM64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.IOS_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.LINUX -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.LINUX_ARM32_HFP -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.LINUX_MIPS32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.LINUX_MIPSEL32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.LINUX_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.MACOS_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.MINGW -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.MINGW_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.MIPS32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.MIPSEL32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.OSX -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.TVOS -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.TVOS_ARM64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.TVOS_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WASM -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WASM32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WATCHOS -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WATCHOS_ARM32 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WATCHOS_ARM64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WATCHOS_X64 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.WATCHOS_X86 -> KNOWN_EXTENSIONS_KEYS
NativeDefinitionsTypes.X64 -> KNOWN_EXTENSIONS_KEYS
else -> EMPTY_KEYS
}
override fun getHighlightingLexer(): Lexer = NativeDefinitionsLexerAdapter()
private fun createKeys(externalName: String, key: TextAttributesKey): Array<TextAttributesKey> {
return arrayOf(TextAttributesKey.createTextAttributesKey(externalName, key))
}
private val BAD_CHAR_KEYS = createKeys("Unknown key", HighlighterColors.BAD_CHARACTER)
private val COMMENT_KEYS = createKeys("Comment", DefaultLanguageHighlighterColors.LINE_COMMENT)
private val EMPTY_KEYS = emptyArray<TextAttributesKey>()
private val KNOWN_EXTENSIONS_KEYS = createKeys("Known extension", DefaultLanguageHighlighterColors.LABEL)
private val KNOWN_PROPERTIES_KEYS = createKeys("Known property", DefaultLanguageHighlighterColors.KEYWORD)
private val OPERATOR_KEYS = createKeys("Operator", DefaultLanguageHighlighterColors.OPERATION_SIGN)
private val VALUE_KEYS = createKeys("Value", DefaultLanguageHighlighterColors.STRING)
}
class NativeDefinitionsSyntaxHighlighterFactory : SyntaxHighlighterFactory() {
override fun getSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?): SyntaxHighlighter =
NativeDefinitionsSyntaxHighlighter
} | apache-2.0 | 56b650749ca254c133381a750e122443 | 51.453039 | 125 | 0.748868 | 5.613838 | false | false | false | false |
apollographql/apollo-android | apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo3/gradle/internal/SchemaDownloader.kt | 1 | 3457 | package com.apollographql.apollo3.gradle.internal
import com.apollographql.apollo3.compiler.fromJson
object SchemaDownloader {
fun downloadIntrospection(
endpoint: String,
headers: Map<String, String>
): String {
val body = mapOf(
"query" to introspectionQuery,
"operationName" to "IntrospectionQuery"
)
val response = SchemaHelper.executeQuery(body, endpoint, headers)
return response.body.use { responseBody ->
responseBody!!.string()
}
}
fun downloadRegistry(
key: String,
graph: String,
variant: String,
endpoint: String = "https://graphql.api.apollographql.com/api/graphql"
): String {
val query = """
query DownloadSchema(${'$'}graphID: ID!, ${'$'}variant: String!) {
service(id: ${'$'}graphID) {
variant(name: ${'$'}variant) {
activeSchemaPublish {
schema {
document
}
}
}
}
}
""".trimIndent()
val variables = mapOf("graphID" to graph, "variant" to variant)
val response = SchemaHelper.executeQuery(query, variables, endpoint, mapOf("x-api-key" to key))
val responseString = response.body.use { it?.string() }
val document = responseString
?.fromJson<Map<String, *>>()
?.get("data").cast<Map<String, *>>()
?.get("service").cast<Map<String, *>>()
?.get("variant").cast<Map<String, *>>()
?.get("activeSchemaPublish").cast<Map<String, *>>()
?.get("schema").cast<Map<String, *>>()
?.get("document").cast<String>()
check(document != null) {
"Cannot retrieve document from $responseString\nCheck graph id and variant"
}
return document
}
inline fun <reified T> Any?.cast() = this as? T
private val introspectionQuery = """
query IntrospectionQuery {
__schema {
queryType { name }
mutationType { name }
subscriptionType { name }
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type { ...TypeRef }
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}""".trimIndent()
} | mit | f1f75c287fbe45372bf6a14315b254b6 | 21.166667 | 99 | 0.493202 | 5.083824 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/config/GithubPullRequestsProjectUISettings.kt | 2 | 4070 | // 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.github.pullrequest.config
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.api.GHRepositoryPath
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.accounts.GHAccountSerializer
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.util.GHGitRepositoryMapping
import org.jetbrains.plugins.github.util.GHProjectRepositoriesManager
@Service
@State(name = "GithubPullRequestsUISettings", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)], reportStatistic = false)
class GithubPullRequestsProjectUISettings(private val project: Project)
: PersistentStateComponentWithModificationTracker<GithubPullRequestsProjectUISettings.SettingsState> {
private var state: SettingsState = SettingsState()
class SettingsState : BaseState() {
var selectedUrlAndAccountId by property<UrlAndAccount?>(null) { it == null }
var recentSearchFilters by list<String>()
var recentNewPullRequestHead by property<RepoCoordinatesHolder?>(null) { it == null }
}
@Deprecated("Deprecated when moving to single-tab pull requests")
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
fun getHiddenUrls(): Set<String> = emptySet()
var selectedRepoAndAccount: Pair<GHGitRepositoryMapping, GithubAccount>?
get() {
val (url, accountId) = state.selectedUrlAndAccountId ?: return null
val repo = project.service<GHProjectRepositoriesManager>().knownRepositories.find {
it.gitRemote.url == url
} ?: return null
val account = GHAccountSerializer.deserialize(accountId) ?: return null
return repo to account
}
set(value) {
state.selectedUrlAndAccountId = value?.let { (repo, account) ->
UrlAndAccount(repo.gitRemote.url, GHAccountSerializer.serialize(account))
}
}
fun getRecentSearchFilters(): List<String> = state.recentSearchFilters.toList()
fun addRecentSearchFilter(searchFilter: String) {
val addExisting = state.recentSearchFilters.remove(searchFilter)
state.recentSearchFilters.add(0, searchFilter)
if (state.recentSearchFilters.size > RECENT_SEARCH_FILTERS_LIMIT) {
state.recentSearchFilters.removeLastOrNull()
}
if (!addExisting) {
state.intIncrementModificationCount()
}
}
var recentNewPullRequestHead: GHRepositoryCoordinates?
get() = state.recentNewPullRequestHead?.let { GHRepositoryCoordinates(it.server, GHRepositoryPath(it.owner, it.repository)) }
set(value) {
state.recentNewPullRequestHead = value?.let { RepoCoordinatesHolder(it) }
}
override fun getStateModificationCount() = state.modificationCount
override fun getState() = state
override fun loadState(state: SettingsState) {
this.state = state
}
companion object {
@JvmStatic
fun getInstance(project: Project) = project.service<GithubPullRequestsProjectUISettings>()
private const val RECENT_SEARCH_FILTERS_LIMIT = 10
class UrlAndAccount private constructor() {
var url: String = ""
var accountId: String = ""
constructor(url: String, accountId: String) : this() {
this.url = url
this.accountId = accountId
}
operator fun component1() = url
operator fun component2() = accountId
}
class RepoCoordinatesHolder private constructor() {
var server: GithubServerPath = GithubServerPath.DEFAULT_SERVER
var owner: String = ""
var repository: String = ""
constructor(coordinates: GHRepositoryCoordinates): this() {
server = coordinates.serverPath
owner = coordinates.repositoryPath.owner
repository = coordinates.repositoryPath.repository
}
}
}
} | apache-2.0 | ae69830a5bf203c503de8d8516d38452 | 37.046729 | 140 | 0.746437 | 4.833729 | false | false | false | false |
mr-max/learning-spaces | app/src/main/java/de/maxvogler/learningspaces/fragments/LocationMapFragment.kt | 1 | 4424 | package de.maxvogler.learningspaces.fragments
import android.os.Bundle
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.squareup.otto.Subscribe
import de.maxvogler.learningspaces.events.LocationFocusChangeEvent
import de.maxvogler.learningspaces.events.PanelVisibilityChangedEvent
import de.maxvogler.learningspaces.events.UpdateLocationsEvent
import de.maxvogler.learningspaces.models.Location
import de.maxvogler.learningspaces.services.BusProvider
import de.maxvogler.learningspaces.services.MarkerFactory
import kotlin.properties.Delegates
/**
* A Fragment, displaying all [Location]s in a [GoogleMap].
*/
public class LocationMapFragment : SupportMapFragment() {
companion object {
val START_LAT = 49.011019
val START_LNG = 8.414874
}
private val bus = BusProvider.instance
private var markers: Map<Location, Marker> = emptyMap()
private var markerFactory: MarkerFactory by Delegates.notNull()
private var selectedMarker: Marker? = null
private var selectedLocation: Location? = null
private var mapView: GoogleMap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
markerFactory = MarkerFactory(activity)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
getMapAsync {
this.mapView = it
val pos = LatLng(START_LAT, START_LNG)
it.uiSettings.isZoomControlsEnabled = false
it.uiSettings.isMyLocationButtonEnabled = false
it.uiSettings.isCompassEnabled = false
it.isMyLocationEnabled = true
it.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 14f))
it.setOnMarkerClickListener { marker ->
val location = markers.entrySet().firstOrNull { it.getValue() == marker }?.key
if (location != null) {
showSelectedMarker(markerFactory.createSelectedMarker(location))
bus.post(LocationFocusChangeEvent(location))
}
true
}
it.setOnMapClickListener {
bus.post(LocationFocusChangeEvent(null))
}
}
}
override fun onResume() {
super.onResume()
bus.register(this)
}
override fun onPause() {
bus.unregister(this)
super.onPause()
}
@Subscribe
public fun onReceiveLocations(event: UpdateLocationsEvent) {
val locations = event.locations
removeSelectedMarker()
mapView?.clear()
markers = locations.values().toMap({ it }, { it })
.mapValues { markerFactory.createMarker(it.getValue()) }
.mapValues { mapView?.addMarker(it.getValue()) }
.filter { it.getValue() != null }
.mapValues { it.getValue()!! }
val oldSelected = selectedLocation
if (oldSelected != null) {
val newSelected = locations.get(oldSelected.id)
if (newSelected != null) {
selectedLocation = newSelected
showSelectedMarker(markerFactory.createSelectedMarker(newSelected))
}
}
}
@Subscribe
public fun onLocationFocusChange(event: LocationFocusChangeEvent) {
removeSelectedMarker()
selectedLocation = event.location
if (event.location != null) {
val marker = markerFactory.createSelectedMarker(event.location)
showSelectedMarker(marker)
if (event.animateMap) {
mapView?.animateCamera(CameraUpdateFactory.newLatLng(marker.position))
}
}
}
@Subscribe
public fun onPanelVisibilityChanged(event: PanelVisibilityChangedEvent) {
mapView?.uiSettings?.setAllGesturesEnabled(!event.visible)
}
private fun removeSelectedMarker() {
selectedMarker?.remove()
selectedMarker = null
}
private fun showSelectedMarker(options: MarkerOptions) {
removeSelectedMarker()
selectedMarker = mapView?.addMarker(options)
}
}
| gpl-2.0 | 3dc1ee6234442aedf0e7ce7f8a719dbf | 31.057971 | 94 | 0.662749 | 5.04447 | false | false | false | false |
theunknownxy/mcdocs | src/main/kotlin/de/theunknownxy/mcdocs/gui/utils/GuiBuilder.kt | 1 | 4718 | package de.theunknownxy.mcdocs.gui.utils
import de.theunknownxy.mcdocs.docs.DocumentationBackend
import de.theunknownxy.mcdocs.gui.base.Root
import de.theunknownxy.mcdocs.gui.base.Widget
import de.theunknownxy.mcdocs.gui.container.HorizontalBox
import de.theunknownxy.mcdocs.gui.container.MultiContainer
import de.theunknownxy.mcdocs.gui.container.SingleContainer
import de.theunknownxy.mcdocs.gui.container.VerticalBox
import de.theunknownxy.mcdocs.gui.document.DocumentViewer
import de.theunknownxy.mcdocs.gui.layout.Constraint
import de.theunknownxy.mcdocs.gui.layout.ExpandingPolicy
import de.theunknownxy.mcdocs.gui.layout.FixedPolicy
import de.theunknownxy.mcdocs.gui.layout.Policy
import de.theunknownxy.mcdocs.gui.widget.*
import net.minecraft.client.gui.GuiScreen
import net.minecraft.util.ResourceLocation
/****************
* Base classes *
****************/
class BPolicy {
var policy: Policy = ExpandingPolicy(1f)
fun expanding(importance: Float) {
policy = ExpandingPolicy(importance)
}
fun fixed(value: Float) {
policy = FixedPolicy(value)
}
}
abstract class BWidget(var widget: Widget) {
fun vpolicy(init: BPolicy.() -> Unit) {
val policy = BPolicy()
policy.init()
widget.constraint.vertical = policy.policy
}
fun hpolicy(init: BPolicy.() -> Unit) {
val policy = BPolicy()
policy.init()
widget.constraint.horizontal = policy.policy
}
fun fixed(width: Float, height: Float) {
widget.constraint = Constraint(FixedPolicy(width), FixedPolicy(height))
}
fun id(name: String) {
widget.root!!.named_widgets[name] = this.widget
}
}
abstract class BContainer(widget: Widget) : BWidget(widget) {
abstract fun add(widget: Widget)
fun initWidget<T : BWidget>(widget: T, init: T.() -> Unit) {
widget.init()
add(widget.widget)
}
}
abstract class BMultiContainer(widget: Widget) : BContainer(widget) {
override fun add(widget: Widget) {
(this.widget as MultiContainer).children.add(widget)
}
}
abstract class BSingleContainer(widget: Widget) : BContainer(widget) {
override fun add(widget: Widget) {
val container = this.widget as SingleContainer
container.child = widget
}
}
/********************************
* Classes for concrete Widgets *
********************************/
class BVBox(root: Root?) : BMultiContainer(VerticalBox(root))
class BHBox(root: Root?) : BMultiContainer(HorizontalBox(root))
class BSpacer(root: Root?) : BWidget(Spacer(root))
class BImage(root: Root?) : BWidget(Image(root)) {
fun path(res_path: String) {
val img = widget as Image
img.tex = ResourceLocation(res_path)
}
}
class BTextField(root: Root?) : BWidget(TextField(root)) {
fun content(str: String) {
val field = widget as TextField
field.content = str
}
}
class BButton(root: Root?) : BWidget(Button(root)) {
fun text(str: String) {
val button = widget as Button
button.text = str
}
fun onClick(callback: (Button) -> Unit) {
val button = widget as Button
button.callback = callback
}
}
class BTreeBar(root: Root?) : BWidget(ScrollWidget(root, TreeBar())) {
fun backend(backend: DocumentationBackend) {
val bar = (widget as ScrollWidget).child as TreeBar
bar.backend = backend
}
}
class BDocumentViewer(root: Root?) : BWidget(ScrollWidget(root, DocumentViewer())) {
fun backend(backend: DocumentationBackend) {
val viewer = (widget as ScrollWidget).child as DocumentViewer
viewer.backend = backend
}
}
class BRoot(gui: GuiScreen) : BSingleContainer(Root(gui)) {
public fun setRoot() {
this.widget.root = this.widget as Root
}
}
fun BContainer.image(init: BImage.() -> Unit) = initWidget(BImage(this.widget.root), init)
fun BContainer.textfield(init: BTextField.() -> Unit) = initWidget(BTextField(this.widget.root), init)
fun BContainer.spacer(init: BSpacer.() -> Unit) = initWidget(BSpacer(this.widget.root), init)
fun BContainer.vbox(init: BVBox.() -> Unit) = initWidget(BVBox(this.widget.root), init)
fun BContainer.hbox(init: BHBox.() -> Unit) = initWidget(BHBox(this.widget.root), init)
fun BContainer.button(init: BButton.() -> Unit) = initWidget(BButton(this.widget.root), init)
fun BContainer.treebar(init: BTreeBar.() -> Unit) = initWidget(BTreeBar(this.widget.root), init)
fun BContainer.document(init: BDocumentViewer.() -> Unit) = initWidget(BDocumentViewer(this.widget.root), init)
fun root(gui: GuiScreen, init: BRoot.() -> Unit): Root {
val root = BRoot(gui)
root.setRoot()
root.init()
return root.widget as Root
} | mit | 5935a608833446f6e07fe9dbc674e677 | 31.321918 | 111 | 0.679949 | 3.688819 | false | false | false | false |
udevbe/westford | compositor/src/main/kotlin/org/westford/nativ/libbcm_host/VC_RECT_T.kt | 3 | 1182 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.nativ.libbcm_host
import org.freedesktop.jaccall.CType
import org.freedesktop.jaccall.Field
import org.freedesktop.jaccall.Struct
@Struct(Field(name = "x",
type = CType.INT),
Field(name = "y",
type = CType.INT),
Field(name = "width",
type = CType.INT),
Field(name = "height",
type = CType.INT)) class VC_RECT_T : Struct_VC_RECT_T()
| agpl-3.0 | 9f1d388900b7e714250333a3735b1b97 | 37.129032 | 75 | 0.687817 | 3.993243 | false | false | false | false |
zdary/intellij-community | platform/util/testSrc/com/intellij/util/io/DecompressorTest.kt | 2 | 18301 | // 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.util.io
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.IoTestUtil.assumeNioSymLinkCreationIsSupported
import com.intellij.testFramework.rules.TempDirectory
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.apache.commons.compress.archivers.zip.UnixStat
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Condition
import org.junit.Rule
import org.junit.Test
import java.io.FileOutputStream
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.FileTime
import java.time.Instant
import java.util.*
import java.util.function.Predicate
import java.util.zip.ZipEntry
import java.util.zip.ZipException
import java.util.zip.ZipOutputStream
@Suppress("UsePropertyAccessSyntax")
class DecompressorTest {
@Rule @JvmField var tempDir = TempDirectory()
@Test fun noInternalTraversalInZip() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use { writeEntry(it, "a/../bad.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
testNoTraversal(Decompressor.Zip(zip), dir, dir.resolve("bad.txt"))
}
@Test fun noInternalTraversalInExtZip() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use { writeEntry(it, "a/../bad.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
testNoTraversal(Decompressor.Zip(zip).withZipExtensions(), dir, dir.resolve("bad.txt"))
}
@Test fun noExternalTraversalInZip() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use { writeEntry(it, "../evil.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
testNoTraversal(Decompressor.Zip(zip), dir, dir.parent.resolve("evil.txt"))
}
@Test fun noExternalTraversalInExtZip() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use { writeEntry(it, "../evil.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
testNoTraversal(Decompressor.Zip(zip).withZipExtensions(), dir, dir.parent.resolve("evil.txt"))
}
@Test fun noAbsolutePathsInZip() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use { writeEntry(it, "/root.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).extract(dir)
assertThat(dir.resolve("root.txt")).exists()
}
@Test fun noAbsolutePathsInExtZip() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use { writeEntry(it, "/root.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).withZipExtensions().extract(dir)
assertThat(dir.resolve("root.txt")).exists()
}
@Test fun tarDetectionPlain() {
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use { writeEntry(it, "dir/file.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).extract(dir)
assertThat(dir.resolve("dir/file.txt")).exists()
}
@Test fun tarDetectionGZip() {
val tar = tempDir.newFile("test.tgz")
TarArchiveOutputStream(GzipCompressorOutputStream(FileOutputStream(tar))).use { writeEntry(it, "dir/file.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).extract(dir)
assertThat(dir.resolve("dir/file.txt")).exists()
}
@Test fun noInternalTraversalInTar() {
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use { writeEntry(it, "a/../bad.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
testNoTraversal(Decompressor.Tar(tar), dir, dir.resolve("bad.txt"))
}
@Test fun noExternalTraversalInTar() {
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use { writeEntry(it, "../evil.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
testNoTraversal(Decompressor.Tar(tar), dir, dir.parent.resolve("evil.txt"))
}
@Test fun noAbsolutePathsInTar() {
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use { writeEntry(it, "/root.txt") }
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).extract(dir)
assertThat(dir.resolve("root.txt")).exists()
}
@Test(expected = ZipException::class)
fun failsOnCorruptedZip() {
val zip = tempDir.newFile("test.zip")
zip.writeText("whatever")
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).extract(dir)
}
@Test(expected = ZipException::class)
fun failsOnCorruptedExtZip() {
val zip = tempDir.newFile("test.zip")
zip.writeText("whatever")
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).withZipExtensions().extract(dir)
}
@Test fun tarFileModes() {
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use {
writeEntry(it, "dir/r", mode = 0b100_000_000)
writeEntry(it, "dir/rw", mode = 0b110_000_000)
writeEntry(it, "dir/rx", mode = 0b101_000_000)
writeEntry(it, "dir/rwx", mode = 0b111_000_000)
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).extract(dir)
if (SystemInfo.isWindows) {
arrayOf("r", "rw", "rx", "rwx").forEach {
assertThat(dir.resolve("dir/${it}")).exists().`is`(Writable)
}
}
else {
assertThat(dir.resolve("dir/r")).exists().isNot(Writable).isNot(Executable)
assertThat(dir.resolve("dir/rw")).exists().`is`(Writable).isNot(Executable)
assertThat(dir.resolve("dir/rx")).exists().isNot(Writable).`is`(Executable)
assertThat(dir.resolve("dir/rwx")).exists().`is`(Writable).`is`(Executable)
}
}
@Test fun zipUnixFileModes() {
val zip = tempDir.newFile("test.zip")
ZipArchiveOutputStream(FileOutputStream(zip)).use {
writeEntry(it, "dir/r", mode = 0b100_000_000)
writeEntry(it, "dir/rw", mode = 0b110_000_000)
writeEntry(it, "dir/rx", mode = 0b101_000_000)
writeEntry(it, "dir/rwx", mode = 0b111_000_000)
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).withZipExtensions().extract(dir)
if (SystemInfo.isWindows) {
arrayOf("r", "rw", "rx", "rwx").forEach {
assertThat(dir.resolve("dir/${it}")).exists().`is`(Writable).isNot(Hidden)
}
}
else {
assertThat(dir.resolve("dir/r")).exists().isReadable().isNot(Writable).isNot(Executable)
assertThat(dir.resolve("dir/rw")).exists().isReadable().`is`(Writable).isNot(Executable)
assertThat(dir.resolve("dir/rx")).exists().isReadable().isNot(Writable).`is`(Executable)
assertThat(dir.resolve("dir/rwx")).exists().isReadable().`is`(Writable).`is`(Executable)
}
}
@Test fun zipDosFileModes() {
val zip = tempDir.newFile("test.zip")
ZipArchiveOutputStream(FileOutputStream(zip)).use {
writeEntry(it, "dir/ro", readOnly = true)
writeEntry(it, "dir/rw")
writeEntry(it, "dir/h", hidden = true)
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).withZipExtensions().extract(dir)
assertThat(dir.resolve("dir/ro")).exists().isNot(Writable)
assertThat(dir.resolve("dir/rw")).exists().`is`(Writable)
if (SystemInfo.isWindows) {
assertThat(dir.resolve("dir/h")).exists().`is`(Hidden)
}
}
@Test fun filtering() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use {
writeEntry(it, "d1/f1.txt")
writeEntry(it, "d2/f2.txt")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).filter(Predicate { !it.startsWith("d2/") }).extract(dir)
assertThat(dir.resolve("d1/f1.txt")).isRegularFile()
assertThat(dir.resolve("d2")).doesNotExist()
}
@Test fun tarSymlinks() {
assumeNioSymLinkCreationIsSupported()
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use {
writeEntry(it, "f")
writeEntry(it, "links/ok", link = "../f")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).extract(dir)
assertThat(dir.resolve("links/ok")).isSymbolicLink().hasSameBinaryContentAs(dir.resolve("f"))
}
@Test fun zipSymlinks() {
assumeNioSymLinkCreationIsSupported()
val zip = tempDir.newFile("test.zip")
ZipArchiveOutputStream(FileOutputStream(zip)).use {
writeEntry(it, "f")
writeEntry(it, "links/ok", link = "../f")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).withZipExtensions().extract(dir)
assertThat(dir.resolve("links/ok")).isSymbolicLink().hasSameBinaryContentAs(dir.resolve("f"))
}
@Test fun prefixPathsFilesInZip() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use {
writeEntry(it, "a/b/c.txt")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).removePrefixPath("a/b").extract(dir)
assertThat(dir.resolve("c.txt")).isRegularFile()
assertThat(dir.resolve("a")).doesNotExist()
assertThat(dir.resolve("a/b")).doesNotExist()
assertThat(dir.resolve("b")).doesNotExist()
}
@Test fun prefixPathsFilesInCommonsZip() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use {
writeEntry(it, "a/b/c.txt")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).removePrefixPath("a/b").extract(dir)
assertThat(dir.resolve("c.txt")).isRegularFile()
assertThat(dir.resolve("a")).doesNotExist()
assertThat(dir.resolve("a/b")).doesNotExist()
assertThat(dir.resolve("b")).doesNotExist()
}
@Test fun prefixPathFilesInZipWithFilter() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use {
writeEntry(it, "a/b/c.txt")
writeEntry(it, "skip.txt")
}
val dir = tempDir.newDirectory("unpacked").toPath()
val filterLog = mutableListOf<String>()
Decompressor.Zip(zip).removePrefixPath("a/b").filter(Predicate{ filterLog.add(it) }).extract(dir)
assertThat(dir.resolve("c.txt")).isRegularFile()
assertThat(dir.resolve("a")).doesNotExist()
assertThat(dir.resolve("a/b")).doesNotExist()
assertThat(dir.resolve("b")).doesNotExist()
assertThat(filterLog).containsExactlyInAnyOrder("a/b/c.txt", "skip.txt")
}
@Test fun prefixPathsFilesInTarWithSymlinks() {
assumeNioSymLinkCreationIsSupported()
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use {
writeEntry(it, "a/f")
writeEntry(it, "a/links/ok", link = "../f")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).removePrefixPath("a").extract(dir)
assertThat(dir.resolve("f")).isRegularFile()
assertThat(dir.resolve("links/ok")).isSymbolicLink().hasSameBinaryContentAs(dir.resolve("f"))
}
@Test fun prefixPathFillMatch() {
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use {
writeEntry(it, "./a/f")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).removePrefixPath("/a/f").extract(dir)
assertThat(dir.resolve("f")).doesNotExist()
}
@Test fun prefixPathWithSlashTar() {
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use {
writeEntry(it, "./a/f")
writeEntry(it, "/a/g")
writeEntry(it, "././././././//a/h")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).removePrefixPath("/a/").extract(dir)
assertThat(dir.resolve("f")).isRegularFile()
assertThat(dir.resolve("g")).isRegularFile()
assertThat(dir.resolve("h")).isRegularFile()
}
@Test fun prefixPathWithDotTar() {
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use {
writeEntry(it, "./a/b/f")
writeEntry(it, "/a/b/g")
writeEntry(it, "././././././//a/b/h")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).removePrefixPath("./a/b").extract(dir)
assertThat(dir.resolve("f")).isRegularFile()
assertThat(dir.resolve("g")).isRegularFile()
assertThat(dir.resolve("h")).isRegularFile()
}
@Test fun prefixPathWithCommonsZip() {
val zip = tempDir.newFile("test.zip")
ZipArchiveOutputStream(FileOutputStream(zip)).use {
writeEntry(it, "./a/b/f")
writeEntry(it, "/a/b/g")
writeEntry(it, "././././././//a/b/h")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).removePrefixPath("./a/b").extract(dir)
assertThat(dir.resolve("f")).isRegularFile()
assertThat(dir.resolve("g")).isRegularFile()
assertThat(dir.resolve("h")).isRegularFile()
}
@Test fun prefixPathTarSymlink() {
assumeNioSymLinkCreationIsSupported()
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use {
writeEntry(it, "./a/b/f")
writeEntry(it, "a/b/links/ok", link = "../f")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).removePrefixPath("a/b").extract(dir)
assertThat(dir.resolve("f")).isRegularFile()
assertThat(dir.resolve("links/ok")).isSymbolicLink().hasSameBinaryContentAs(dir.resolve("f"))
}
@Test fun prefixPathZipSymlink() {
assumeNioSymLinkCreationIsSupported()
val zip = tempDir.newFile("test.zip")
ZipArchiveOutputStream(FileOutputStream(zip)).use {
writeEntry(it, "./a/b/f")
writeEntry(it, "a/b/links/ok", link = "../f")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Zip(zip).withZipExtensions().removePrefixPath("a/b").extract(dir)
assertThat(dir.resolve("f")).isRegularFile()
assertThat(dir.resolve("links/ok")).isSymbolicLink().hasSameBinaryContentAs(dir.resolve("f"))
}
@Test fun prefixPathSkipsTooShortPaths() {
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use {
writeEntry(it, "missed")
writeEntry(it, "a/b/c/file.txt")
}
val dir = tempDir.newDirectory("unpacked").toPath()
Decompressor.Tar(tar).removePrefixPath("a/b").extract(dir)
assertThat(dir.resolve("c/file.txt")).isRegularFile()
assertThat(dir.resolve("missed")).doesNotExist()
}
@Test fun fileOverwrite() {
val zip = tempDir.newFile("test.zip")
ZipOutputStream(FileOutputStream(zip)).use { writeEntry(it, "a/file.txt") }
val dir = tempDir.newDirectory("unpacked")
val file = tempDir.newFile("unpacked/a/file.txt", byteArrayOf(0))
Decompressor.Zip(zip).extract(dir)
assertThat(file).hasBinaryContent(TestContent)
}
@Test fun symlinkOverwrite() {
assumeNioSymLinkCreationIsSupported()
val tar = tempDir.newFile("test.tar")
TarArchiveOutputStream(FileOutputStream(tar)).use {
writeEntry(it, "a/file")
writeEntry(it, "a/link", link = "file")
}
val dir = tempDir.newDirectory("unpacked")
val link = tempDir.rootPath.resolve("unpacked/a/link")
val target = tempDir.newFile("unpacked/a/target", byteArrayOf(0)).toPath()
Files.createSymbolicLink(link, target)
Decompressor.Tar(tar).extract(dir)
assertThat(link).isSymbolicLink().hasBinaryContent(TestContent)
}
//<editor-fold desc="Helpers.">
private fun writeEntry(zip: ZipOutputStream, name: String) {
val entry = ZipEntry(name)
entry.time = System.currentTimeMillis()
zip.putNextEntry(entry)
zip.write(TestContent)
zip.closeEntry()
}
private fun writeEntry(tar: TarArchiveOutputStream, name: String, mode: Int = 0, link: String? = null) {
if (link != null) {
val entry = TarArchiveEntry(name, TarArchiveEntry.LF_SYMLINK)
entry.modTime = Date()
entry.linkName = link
entry.size = 0
tar.putArchiveEntry(entry)
}
else {
val entry = TarArchiveEntry(name)
entry.modTime = Date()
entry.size = TestContent.size.toLong()
if (mode != 0) entry.mode = mode
tar.putArchiveEntry(entry)
tar.write(TestContent)
}
tar.closeArchiveEntry()
}
private fun writeEntry(zip: ZipArchiveOutputStream, name: String, mode: Int = 0, readOnly: Boolean = false, hidden: Boolean = false, link: String? = null) {
val entry = ZipArchiveEntry(name)
entry.lastModifiedTime = FileTime.from(Instant.now())
if (link != null) {
entry.unixMode = UnixStat.LINK_FLAG
zip.putArchiveEntry(entry)
zip.write(link.toByteArray())
}
else {
when {
mode != 0 -> entry.unixMode = mode
readOnly || hidden -> {
var dosAttributes = entry.externalAttributes
if (readOnly) dosAttributes = dosAttributes or 0b01
if (hidden) dosAttributes = dosAttributes or 0b10
entry.externalAttributes = dosAttributes
}
}
zip.putArchiveEntry(entry)
zip.write(TestContent)
}
zip.closeArchiveEntry()
}
private fun testNoTraversal(decompressor: Decompressor, dir: Path, unexpected: Path) {
val error = try {
decompressor.extract(dir)
null
}
catch (e: IOException) { e }
assertThat(unexpected).doesNotExist()
assertThat(error?.message).contains(unexpected.fileName.toString())
}
companion object {
private val TestContent = "...".toByteArray()
private val Writable = Condition<Path>(Predicate { Files.isWritable(it) }, "writable")
private val Executable = Condition<Path>(Predicate { Files.isExecutable(it) }, "executable")
private val Hidden = Condition<Path>(Predicate { Files.isHidden(it) }, "hidden")
}
//</editor-fold>
}
| apache-2.0 | dba9f756f8576b70dd9e0370f208256e | 36.734021 | 158 | 0.68264 | 3.86097 | false | true | false | false |
SmokSmog/smoksmog-android | app/src/main/kotlin/com/antyzero/smoksmog/ui/screen/start/StartActivity.kt | 1 | 10784 | package com.antyzero.smoksmog.ui.screen.start
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import com.antyzero.smoksmog.R
import com.antyzero.smoksmog.SmokSmog
import com.antyzero.smoksmog.SmokSmogApplication
import com.antyzero.smoksmog.dsl.observable
import com.antyzero.smoksmog.dsl.tag
import com.antyzero.smoksmog.dsl.toast
import com.antyzero.smoksmog.error.ErrorReporter
import com.antyzero.smoksmog.eventbus.RxBus
import com.antyzero.smoksmog.firebase.FirebaseEvents
import com.antyzero.smoksmog.ui.BaseDragonActivity
import com.antyzero.smoksmog.ui.dialog.AboutDialog
import com.antyzero.smoksmog.ui.dialog.InfoDialog
import com.antyzero.smoksmog.ui.screen.ActivityModule
import com.antyzero.smoksmog.ui.screen.order.OrderActivity
import com.antyzero.smoksmog.ui.screen.settings.SettingsActivity
import com.antyzero.smoksmog.ui.typeface.TypefaceProvider
import com.trello.rxlifecycle.android.ActivityEvent
import kotlinx.android.synthetic.main.activity_start.*
import pl.malopolska.smoksmog.Api
import rx.android.schedulers.AndroidSchedulers
import rx.lang.kotlin.cast
import rx.schedulers.Schedulers
import smoksmog.logger.Logger
import java.io.File
import java.io.FileOutputStream
import javax.inject.Inject
/**
* Base activity for future
*/
class StartActivity : BaseDragonActivity(), ViewPager.OnPageChangeListener {
@Inject lateinit var api: Api
@Inject lateinit var logger: Logger
@Inject lateinit var errorReporter: ErrorReporter
@Inject lateinit var rxBus: RxBus
@Inject lateinit var typefaceProvider: TypefaceProvider
@Inject lateinit var firebaseEvents: FirebaseEvents
@Inject lateinit var smokSmog: SmokSmog
private lateinit var pageSave: PageSave
private lateinit var stationSlideAdapter: StationSlideAdapter
private var lastPageSelected = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
pageSave = PageSave(this)
SmokSmogApplication[this].appComponent
.plus(ActivityModule(this))
.inject(this)
setContentView(R.layout.activity_start)
setSupportActionBar(toolbar)
buttonAddStation.setOnClickListener { OrderActivity.start(this, true) }
stationSlideAdapter = StationSlideAdapter(fragmentManager, smokSmog.storage.fetchAll())
viewPager.adapter = stationSlideAdapter
viewPager.offscreenPageLimit = PAGE_LIMIT
viewPager.addOnPageChangeListener(this)
viewPager.addOnPageChangeListener(viewPagerIndicator)
viewPager.currentItem = pageSave.restorePage()
viewPagerIndicator.setStationIds(smokSmog.storage.fetchAll())
correctTitleMargin()
// Listen for info dialog calls
rxBus.toObserverable()
.compose(bindUntilEvent<Any>(ActivityEvent.DESTROY))
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ event ->
if (event is InfoDialog.Event<*>) {
InfoDialog.show(fragmentManager, event)
}
},
{ throwable -> logger.w("RxEventBus", "Unable to process event", throwable) })
// Listen for title updates
rxBus.toObserverable()
.compose(bindUntilEvent<Any>(ActivityEvent.DESTROY))
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ event ->
if (event is TitleUpdateEvent) {
updateTitleWithStation()
}
},
{ throwable -> logger.w("RxEventBus", "Unable to process event", throwable) })
if (savedInstanceState != null) {
lastPageSelected = savedInstanceState.getInt(KEY_LAST_PAGE, 0)
viewPager.setCurrentItem(lastPageSelected, true)
}
}
override fun onResume() {
super.onResume()
viewPagerIndicator.setStationIds(smokSmog.storage.fetchAll())
stationSlideAdapter.notifyDataSetChanged()
updateTitleWithStation()
if (smokSmog.storage.fetchAll().isEmpty()) {
visibleNoStations()
} else {
visibleStations()
}
}
/**
* Because it's not aligned with main layout margin
*/
private fun correctTitleMargin() {
toolbar.setContentInsetsAbsolute(16, 0)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_settings -> SettingsActivity.start(this)
R.id.action_order -> OrderActivity.start(this)
R.id.action_facebook -> goToFacebookSite()
R.id.action_beta -> goToBetaLogin()
R.id.action_about -> rxBus.send(InfoDialog.Event(AboutDialog::class.java))
R.id.action_share -> shareScreen()
}
return super.onOptionsItemSelected(item)
}
private fun shareScreen() {
window.decorView.findViewById(android.R.id.content).observable()
.map { getScreenShot(it) }
.subscribeOn(AndroidSchedulers.mainThread())
.map { store(it) }
.filter { it != null }
.cast<File>()
.map { shareImage(it) }
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
toast(if (it) {
"Shared success"
} else {
"Shared failed"
})
}, {
toast("Fatal issue " + it.toString())
logger.e(tag(), "Fatal error", it)
})
}
private fun getScreenShot(view: View): Bitmap {
val screenView = view.rootView
screenView.isDrawingCacheEnabled = true
val bitmap = Bitmap.createBitmap(screenView.drawingCache)
screenView.isDrawingCacheEnabled = false
return bitmap
}
private fun store(bm: Bitmap, fileName: String = File.createTempFile(System.currentTimeMillis().toString(), ".png").name): File? {
val dirPath = externalCacheDir.absolutePath + "/Screenshots"
val dir = File(dirPath).apply {
if (!exists()) {
mkdirs()
}
}
val file = File(dir, fileName).apply {
createNewFile()
}
val fOut = FileOutputStream(file)
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut)
fOut.flush()
fOut.close()
return file
}
private fun shareImage(file: File): Boolean {
val uri = Uri.fromFile(file)
val intent = Intent()
intent.action = Intent.ACTION_SEND
intent.type = "image/png"
System.out.println(">>> $file")
System.out.println(">>> ${file.length()}")
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject")
intent.putExtra(android.content.Intent.EXTRA_TEXT, "Text")
intent.putExtra(Intent.EXTRA_STREAM, uri)
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"))
} catch (e: ActivityNotFoundException) {
return false
}
return true
}
private fun goToBetaLogin() {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/apps/testing/pl.malopolska.smoksmog")))
}
private fun goToFacebookSite() {
val facebookUrl = "https://fb.com/SmokSmog"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(facebookUrl))
try {
if (packageManager.getPackageInfo("com.facebook.katana", 0) != null) {
intent.data = Uri.parse("fb://page/714218922054053")
}
} catch (e: PackageManager.NameNotFoundException) {
// do nothing
}
try {
startActivity(intent)
} catch (e: Exception) {
logger.w(tag(), "Going to Facebook page went wrong ($intent)", e)
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://fb.com/SmokSmog")))
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt(KEY_LAST_PAGE, lastPageSelected)
super.onSaveInstanceState(outState)
}
override fun onPageScrollStateChanged(state: Int) {
// do nothing
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
// do nothing
}
override fun onPageSelected(position: Int) {
updateTitleWithStation(position)
lastPageSelected = position
pageSave.savePage(position)
firebaseEvents.logStationCardInView(stationSlideAdapter.getItem(position).stationId)
}
private fun updateTitleWithStation() {
if (stationSlideAdapter.count > 0) {
updateTitleWithStation(viewPager.currentItem)
}
}
fun updateTitleWithStation(position: Int) {
stationSlideAdapter.getFragmentReference(position)?.get()?.let {
val stationFragment = it
it.title.let {
toolbar.title = it
toolbar.subtitle = stationFragment.subtitle
changeSubtitleTypeface()
}
}
}
private fun visibleStations() {
viewSwitcher.displayedChild = 0
}
private fun visibleNoStations() {
if (supportActionBar != null) {
supportActionBar!!.setTitle(R.string.app_name)
supportActionBar!!.subtitle = null
}
viewSwitcher.displayedChild = 1
}
/**
* This is messy, Calligraphy should handle this but for some reason it's the only TextView
* not updated with default font.
*
* TODO fix with Calligraphy in future
*/
private fun changeSubtitleTypeface() {
(1..toolbar.childCount - 1)
.map { toolbar!!.getChildAt(it) }
.filterIsInstance<TextView>()
.forEach { it.typeface = typefaceProvider.default }
}
/**
* Ask to check title and update is possible
*/
class TitleUpdateEvent
companion object {
private val KEY_LAST_PAGE = "lastSelectedPagePosition"
private val PAGE_LIMIT = 5
}
}
| gpl-3.0 | 0ba7de672d8204735ba8ed8cea47cf23 | 32.805643 | 134 | 0.634458 | 4.761148 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/extensionProperties/kt9897.kt | 5 | 745 | object Test {
var z = "0"
var l = 0L
fun changeObject(): String {
"1".someProperty += 1
return z
}
fun changeLong(): Long {
2L.someProperty -= 1
return l
}
var String.someProperty: Int
get() {
return this.length
}
set(left) {
z += this + left
}
var Long.someProperty: Long
get() {
return l
}
set(left) {
l += this + left
}
}
fun box(): String {
val changeObject = Test.changeObject()
if (changeObject != "012") return "fail 1: $changeObject"
val changeLong = Test.changeLong()
if (changeLong != 1L) return "fail 1: $changeLong"
return "OK"
} | apache-2.0 | a6fbffb704d395945f1564090f9275a5 | 17.195122 | 61 | 0.487248 | 3.860104 | false | true | false | false |
mpcjanssen/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/FilterScriptFragment.kt | 1 | 8041 | package nl.mpcjanssen.simpletask
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.fragment.app.Fragment
import androidx.core.content.ContextCompat
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import nl.mpcjanssen.simpletask.task.Task
import nl.mpcjanssen.simpletask.util.createAlertDialog
class FilterScriptFragment : Fragment() {
private var txtScript: EditText? = null
private var cbUseScript: CheckBox? = null
private var txtTestTask: EditText? = null
private var spnCallback: Spinner? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate() this:" + this)
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy() this:" + this)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Log.d(TAG, "onSaveInstanceState() this:" + this)
outState.putString(Query.INTENT_SCRIPT_FILTER, script)
outState.putString(Query.INTENT_SCRIPT_TEST_TASK_FILTER, testTask)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
Log.d(TAG, "onCreateView() this:" + this)
val arguments = arguments
Log.d(TAG, "Fragment bundle:" + this)
val layout = inflater.inflate(R.layout.script_filter,
container, false) as LinearLayout
cbUseScript = layout.findViewById(R.id.cb_use_script) as CheckBox
txtScript = layout.findViewById(R.id.txt_script) as EditText
txtTestTask = layout.findViewById(R.id.txt_testtask) as EditText
spnCallback = layout.findViewById(R.id.spnCallback) as Spinner
val callbacks = arrayOf<String>(Interpreter.ON_DISPLAY_NAME, Interpreter.ON_FILTER_NAME, Interpreter.ON_GROUP_NAME, Interpreter.ON_SORT_NAME)
val spnAdapter = activity?.let { ArrayAdapter(it, R.layout.spinner_item, callbacks) }
spnCallback?.adapter = spnAdapter
activity?.let { act ->
val btnTest = layout.findViewById(R.id.btnTest) as Button
btnTest.setOnClickListener {
val callbackToTest = selectedCallback
val t = Task(testTask)
try {
Log.i(TAG, "Running $callbackToTest test Lua callback in module $environment")
val script = script
val snackBar = Snackbar.make(act.findViewById(android.R.id.content), "", Snackbar.LENGTH_LONG)
val barView = snackBar.view
when (callbackToTest) {
Interpreter.ON_DISPLAY_NAME -> testOnDisplayCallback(barView, script, snackBar, t)
Interpreter.ON_FILTER_NAME -> testOnFilterCallback(barView, script, snackBar, t)
Interpreter.ON_GROUP_NAME -> testOnGroupCallback(barView, script, snackBar, t)
Interpreter.ON_SORT_NAME -> testOnSortCallback(barView, script, snackBar, t)
}
} catch (e: Exception) {
Log.d(TAG, "Lua execution failed " + e.message)
createAlertDialog(act, R.string.lua_error, e.message ?: "").show()
}
}
}
if (savedInstanceState != null) {
cbUseScript!!.isChecked = savedInstanceState.getBoolean(Query.INTENT_USE_SCRIPT_FILTER, false)
txtScript!!.setText(savedInstanceState.getString(Query.INTENT_SCRIPT_FILTER, ""))
txtTestTask!!.setText(savedInstanceState.getString(Query.INTENT_SCRIPT_TEST_TASK_FILTER, ""))
} else {
cbUseScript!!.isChecked = arguments?.getBoolean(Query.INTENT_USE_SCRIPT_FILTER, false) ?: false
txtScript!!.setText(arguments?.getString(Query.INTENT_SCRIPT_FILTER, "") ?:"")
txtTestTask!!.setText(arguments?.getString(Query.INTENT_SCRIPT_TEST_TASK_FILTER, "")?:"")
}
return layout
}
private fun testOnFilterCallback(barView: View, script: String, snackBar: Snackbar, t: Task) {
val (toShow, result) = Interpreter.evalScript(environment, script).onFilterCallback(environment, t)
if (toShow) {
snackBar.setText(result +": " + getString(R.string.script_tab_true_task_shown))
barView.setBackgroundColor(0xff43a047.toInt())
} else {
snackBar.setText(result +": " + getString(R.string.script_tab_false_task_not_shown))
barView.setBackgroundColor(0xffe53935.toInt())
}
snackBar.show()
}
private fun testOnGroupCallback(barView: View, script: String, snackBar: Snackbar, t: Task) {
activity?.let {act ->
if (!script.trim { it <= ' ' }.isEmpty()) {
snackBar.setText("Group: " + Interpreter.evalScript(environment, script).onGroupCallback(environment, t))
barView.setBackgroundColor(ContextCompat.getColor(act, R.color.gray74))
} else {
snackBar.setText("Callback not defined")
barView.setBackgroundColor(0xffe53935.toInt())
}
snackBar.show()
}
}
private fun testOnDisplayCallback(barView: View, script: String, snackBar: Snackbar, t: Task) {
activity?.let { act ->
if (!script.trim { it <= ' ' }.isEmpty()) {
snackBar.setText("Display: " + Interpreter.evalScript(environment, script).onDisplayCallback(environment, t))
barView.setBackgroundColor(ContextCompat.getColor(act, R.color.gray74))
} else {
snackBar.setText("Callback not defined")
barView.setBackgroundColor(0xffe53935.toInt())
}
snackBar.show()
}
}
private fun testOnSortCallback(barView: View, script: String, snackBar: Snackbar, t: Task) {
activity?.let { act ->
if (!script.trim { it <= ' ' }.isEmpty()) {
snackBar.setText("Display: " + Interpreter.evalScript(environment, script).onSortCallback(environment, t))
barView.setBackgroundColor(ContextCompat.getColor(act, R.color.gray74))
} else {
snackBar.setText("Callback not defined")
barView.setBackgroundColor(0xffe53935.toInt())
}
snackBar.show()
}
}
val useScript: Boolean
get() {
val arguments = arguments
if (cbUseScript == null) {
return arguments?.getBoolean(Query.INTENT_USE_SCRIPT_FILTER, false) ?: false
} else {
return cbUseScript?.isChecked ?: false
}
}
val environment: String
get() {
val arguments = arguments
return arguments?.getString(Query.INTENT_LUA_MODULE, "main") ?: "main"
}
var script: String
get() {
val arguments = arguments
if (txtScript == null) {
return arguments?.getString(Query.INTENT_SCRIPT_FILTER, "") ?: ""
} else {
return txtScript!!.text.toString()
}
}
set(script) {
txtScript?.setText(script)
}
val testTask: String
get() {
val arguments = arguments
if (txtTestTask == null) {
return arguments?.getString(Query.INTENT_SCRIPT_TEST_TASK_FILTER, "") ?: ""
} else {
return txtTestTask!!.text.toString()
}
}
val selectedCallback: String
get() {
if (spnCallback == null) {
return Interpreter.ON_FILTER_NAME
}
return spnCallback?.selectedItem.toString()
}
companion object {
internal val TAG = FilterScriptFragment::class.java.simpleName
}
}
| gpl-3.0 | 99931ee8d99a6975d6f555168c77f694 | 40.663212 | 149 | 0.602164 | 4.53781 | false | true | false | false |
nrkv/HypeAPI | src/test/kotlin/io/nrkv/HypeAPI/task/dao/TaskDAOTest.kt | 1 | 2095 | package io.nrkv.HypeAPI.task.dao
import org.junit.Before
import org.junit.Test
import io.nrkv.HypeAPI.task.dao.implementation.TaskDAOImpl
import io.nrkv.HypeAPI.task.model.implementation.TaskRequestModel
import java.util.*
/**
* Created by Ivan Nyrkov on 08/06/17.
*/
class TaskDAOTest {
lateinit var taskDAO: TaskDAO
@Before
fun setup() {
taskDAO = TaskDAOImpl()
}
@Test
fun taskCRUDTest() {
// Empty
assert(taskDAO.getAll().isEmpty())
assert(taskDAO.getById(UUID.randomUUID().toString()) == null)
// Update on not-existing record won't create it (upsert)
assert(taskDAO.update(UUID.randomUUID().toString(), TaskRequestModel(title = "Test")) == null)
assert(taskDAO.getById(UUID.randomUUID().toString()) == null)
// Task will be successfully created
val task1Title = "Test"
val task1 = taskDAO.create(TaskRequestModel(title = task1Title))
assert(taskDAO.getAll().isNotEmpty())
assert(taskDAO.getAll().count() == 1)
assert(taskDAO.getById(task1.id) != null)
assert(task1.title == task1Title)
// Another one task will be created
val task2Title = "Test2"
val task2 = taskDAO.create(TaskRequestModel(title = task2Title))
assert(taskDAO.getAll().count() == 2)
assert(taskDAO.getById(task2.id) != null)
assert(task2.title == task2Title)
// Update task (only specified task must be updated)
val task1TitleUpdated = "TestUpdated"
val updatedTask = taskDAO.update(task1.id, TaskRequestModel(title = task1TitleUpdated))!!
assert(updatedTask == taskDAO.getById(task1.id))
assert(updatedTask.title == task1TitleUpdated)
assert(taskDAO.getById(task2.id)!!.title == task2Title)
// Delete tasks
taskDAO.delete(task2.id)
assert(taskDAO.getById(task2.id) == null)
assert(taskDAO.getAll().count() == 1)
taskDAO.delete(task1.id)
assert(taskDAO.getById(task1.id) == null)
assert(taskDAO.getAll().isEmpty())
}
} | mit | a36ab28829d52458e91a96ed80c1cefc | 33.360656 | 102 | 0.647733 | 3.68838 | false | true | false | false |
AndroidX/androidx | lifecycle/lifecycle-viewmodel/src/main/java/androidx/lifecycle/viewmodel/InitializerViewModelFactory.kt | 3 | 3850 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.lifecycle.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import kotlin.reflect.KClass
@DslMarker
public annotation class ViewModelFactoryDsl
/**
* Creates an [InitializerViewModelFactory] with the initializers provided in the builder.
*/
public inline fun viewModelFactory(
builder: InitializerViewModelFactoryBuilder.() -> Unit
): ViewModelProvider.Factory = InitializerViewModelFactoryBuilder().apply(builder).build()
/**
* DSL for constructing a new [ViewModelProvider.Factory]
*/
@ViewModelFactoryDsl
public class InitializerViewModelFactoryBuilder {
private val initializers = mutableListOf<ViewModelInitializer<*>>()
/**
* Add the initializer for the given ViewModel class.
*
* @param clazz the class the initializer is associated with.
* @param initializer lambda used to create an instance of the ViewModel class
*/
fun <T : ViewModel> addInitializer(clazz: KClass<T>, initializer: CreationExtras.() -> T) {
initializers.add(ViewModelInitializer(clazz.java, initializer))
}
/**
* Build the InitializerViewModelFactory.
*/
fun build(): ViewModelProvider.Factory =
InitializerViewModelFactory(*initializers.toTypedArray())
}
/**
* Add an initializer to the [InitializerViewModelFactoryBuilder]
*/
inline fun <reified VM : ViewModel> InitializerViewModelFactoryBuilder.initializer(
noinline initializer: CreationExtras.() -> VM
) {
addInitializer(VM::class, initializer)
}
/**
* Holds a [ViewModel] class and initializer for that class
*/
class ViewModelInitializer<T : ViewModel>(
internal val clazz: Class<T>,
internal val initializer: CreationExtras.() -> T,
)
/**
* A [ViewModelProvider.Factory] that allows you to add lambda initializers for handling
* particular ViewModel classes using [CreationExtras], while using the default behavior for any
* other classes.
*
* ```
* val factory = viewModelFactory {
* initializer { TestViewModel(this[key]) }
* }
* val viewModel: TestViewModel = factory.create(TestViewModel::class.java, extras)
* ```
*/
internal class InitializerViewModelFactory(
private vararg val initializers: ViewModelInitializer<*>
) : ViewModelProvider.Factory {
/**
* Creates a new instance of the given `Class`.
*
* This will use the initializer if one has been set for the class, otherwise it throw an
* [IllegalArgumentException].
*
* @param modelClass a `Class` whose instance is requested
* @param extras an additional information for this creation request
* @return a newly created ViewModel
*
* @throws IllegalArgumentException if no initializer has been set for the given class.
*/
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
var viewModel: T? = null
@Suppress("UNCHECKED_CAST")
initializers.forEach {
if (it.clazz == modelClass) {
viewModel = it.initializer.invoke(extras) as? T
}
}
return viewModel ?: throw IllegalArgumentException(
"No initializer set for given class ${modelClass.name}"
)
}
}
| apache-2.0 | e513afc0c349f077647cba45a29657da | 32.77193 | 96 | 0.711688 | 4.788557 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/ListConstraint.kt | 12 | 2106 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors.inference
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.PsiType
import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula
import com.intellij.psi.impl.source.resolve.graphInference.constraints.TypeCompatibilityConstraint
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap
import org.jetbrains.plugins.groovy.lang.typing.EmptyListLiteralType
import org.jetbrains.plugins.groovy.lang.typing.EmptyMapLiteralType
class ListConstraint(private val leftType: PsiType?, private val literal: GrListOrMap) : GrConstraintFormula() {
override fun reduce(session: GroovyInferenceSession, constraints: MutableList<in ConstraintFormula>): Boolean {
val type = literal.type
if (type is EmptyMapLiteralType) {
val result = type.resolveResult ?: return true
val clazz = result.element
val contextSubstitutor = result.contextSubstitutor
require(contextSubstitutor === PsiSubstitutor.EMPTY)
val typeParameters = clazz.typeParameters
session.startNestedSession(typeParameters, contextSubstitutor, literal, result) { nested ->
runNestedSession(nested, clazz)
}
return true
}
if (leftType != null) {
val rightType = if (type is EmptyListLiteralType) type.resolve()?.rawType() else type
constraints.add(TypeConstraint(leftType, rightType, literal))
}
return true
}
private fun runNestedSession(nested: GroovyInferenceSession, clazz: PsiClass) {
if (leftType != null) {
val left = nested.substituteWithInferenceVariables(leftType)
val classType = nested.substituteWithInferenceVariables(clazz.type())
nested.addConstraint(TypeCompatibilityConstraint(left, classType))
nested.repeatInferencePhases()
}
}
override fun toString(): String = "${leftType?.presentableText} <- ${literal.text}"
}
| apache-2.0 | d86befbab699c3a4d3e69d42291a31ef | 45.8 | 140 | 0.766382 | 4.669623 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/vfilefinder/fileIndexes.kt | 1 | 11127 | // 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.vfilefinder
import com.intellij.ide.highlighter.JavaClassFileType
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.indexing.*
import com.intellij.util.io.IOUtil
import com.intellij.util.io.KeyDescriptor
import org.jetbrains.kotlin.builtins.jvm.JvmBuiltInsPackageFragmentProvider
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.caches.IDEKotlinBinaryClassCache
import org.jetbrains.kotlin.idea.decompiler.builtIns.BuiltInDefinitionFile
import org.jetbrains.kotlin.idea.decompiler.builtIns.KotlinBuiltInFileType
import org.jetbrains.kotlin.idea.decompiler.js.KotlinJavaScriptMetaFileType
import org.jetbrains.kotlin.idea.klib.KlibLoadingMetadataCache
import org.jetbrains.kotlin.idea.klib.KlibMetaFileType
import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf
import org.jetbrains.kotlin.metadata.js.JsProtoBuf
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.serialization.deserialization.MetadataPackageFragment
import org.jetbrains.kotlin.serialization.deserialization.getClassId
import org.jetbrains.kotlin.utils.JsMetadataVersion
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.lang.manifest.ManifestFileType
import java.io.ByteArrayInputStream
import java.io.DataInput
import java.io.DataOutput
import java.util.*
import java.util.jar.Manifest
abstract class KotlinFileIndexBase<T>(classOfIndex: Class<T>) : ScalarIndexExtension<FqName>() {
val KEY: ID<FqName, Void> = ID.create(classOfIndex.canonicalName)
private val KEY_DESCRIPTOR: KeyDescriptor<FqName> = object : KeyDescriptor<FqName> {
override fun save(output: DataOutput, value: FqName) = IOUtil.writeUTF(output, value.asString())
override fun read(input: DataInput) = FqName(IOUtil.readUTF(input))
override fun getHashCode(value: FqName) = value.asString().hashCode()
override fun isEqual(val1: FqName?, val2: FqName?) = val1 == val2
}
protected val LOG = Logger.getInstance(classOfIndex)
override fun getName() = KEY
override fun dependsOnFileContent() = true
override fun getKeyDescriptor() = KEY_DESCRIPTOR
protected fun indexer(f: (FileContent) -> FqName?): DataIndexer<FqName, Void, FileContent> =
DataIndexer {
try {
val fqName = f(it)
if (fqName != null) {
Collections.singletonMap<FqName, Void>(fqName, null)
} else {
emptyMap()
}
} catch (e: ProcessCanceledException) {
throw e
} catch (e: Throwable) {
LOG.warn("Error while indexing file " + it.fileName, e)
emptyMap()
}
}
}
fun <T> KotlinFileIndexBase<T>.hasSomethingInPackage(fqName: FqName, scope: GlobalSearchScope): Boolean =
!FileBasedIndex.getInstance().processValues(name, fqName, null, { _, _ -> false }, scope)
object KotlinPartialPackageNamesIndex: KotlinFileIndexBase<KotlinPartialPackageNamesIndex>(KotlinPartialPackageNamesIndex::class.java) {
override fun getIndexer() = INDEXER
override fun getInputFilter(): DefaultFileTypeSpecificInputFilter {
return DefaultFileTypeSpecificInputFilter(JavaClassFileType.INSTANCE, KotlinFileType.INSTANCE)
}
override fun getVersion() = VERSION
private const val VERSION = 1
private val INDEXER = DataIndexer<FqName, Void, FileContent> { fileContent ->
try {
val fqName =
fileContent.takeIf { it.fileType == KotlinFileType.INSTANCE }?.psiFile.safeAs<KtFile>()?.packageFqName?.asString()
?: IDEKotlinBinaryClassCache.getInstance()
.getKotlinBinaryClassHeaderData(fileContent.file, fileContent.content)?.packageName
fqName?.let {
val voidValue = null as Void?
mapOf<FqName, Void?>(FqName(it) to voidValue, toPartialFqName(it) to voidValue)
} ?: emptyMap()
} catch (e: ProcessCanceledException) {
throw e
} catch (e: Throwable) {
LOG.warn("Error while indexing file " + fileContent.fileName, e)
emptyMap()
}
}
fun toPartialFqName(fqName: FqName): FqName = toPartialFqName(fqName.asString())
/**
* Picks partial name from `fqName`,
* actually it is the most top segment from `fqName`
*
* @param fqName
* @return
*/
fun toPartialFqName(fqName: String): FqName {
// so far we use only the most top segment frm fqName if it is not a root
// i.e. only `foo` from `foo.bar.zoo`
val dotIndex = fqName.indexOf('.')
return FqName(if (dotIndex > 0) fqName.substring(0, dotIndex) else fqName)
}
}
object KotlinClassFileIndex : KotlinFileIndexBase<KotlinClassFileIndex>(KotlinClassFileIndex::class.java) {
override fun getIndexer() = INDEXER
override fun getInputFilter() = DefaultFileTypeSpecificInputFilter(JavaClassFileType.INSTANCE)
override fun getVersion() = VERSION
private const val VERSION = 3
private val INDEXER = indexer { fileContent ->
val headerInfo = IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClassHeaderData(fileContent.file, fileContent.content)
if (headerInfo != null && headerInfo.metadataVersion.isCompatible()) headerInfo.classId.asSingleFqName() else null
}
}
object KotlinJavaScriptMetaFileIndex : KotlinFileIndexBase<KotlinJavaScriptMetaFileIndex>(KotlinJavaScriptMetaFileIndex::class.java) {
override fun getIndexer() = INDEXER
override fun getInputFilter() = DefaultFileTypeSpecificInputFilter(KotlinJavaScriptMetaFileType)
override fun getVersion() = VERSION
private const val VERSION = 4
private val INDEXER = indexer { fileContent ->
val stream = ByteArrayInputStream(fileContent.content)
if (JsMetadataVersion.readFrom(stream).isCompatible()) {
FqName(JsProtoBuf.Header.parseDelimitedFrom(stream).packageFqName)
} else null
}
}
open class KotlinMetadataFileIndexBase<T>(classOfIndex: Class<T>, indexFunction: (ClassId) -> FqName) :
KotlinFileIndexBase<T>(classOfIndex) {
override fun getIndexer() = INDEXER
override fun getInputFilter() = DefaultFileTypeSpecificInputFilter(KotlinBuiltInFileType)
override fun getVersion() = VERSION
private val VERSION = 1
private val INDEXER = indexer { fileContent ->
if (fileContent.fileType == KotlinBuiltInFileType &&
fileContent.fileName.endsWith(MetadataPackageFragment.DOT_METADATA_FILE_EXTENSION)
) {
val builtins = BuiltInDefinitionFile.read(fileContent.content, fileContent.file)
(builtins as? BuiltInDefinitionFile)?.let { builtinDefFile ->
val proto = builtinDefFile.proto
proto.class_List.singleOrNull()?.let { cls ->
indexFunction(builtinDefFile.nameResolver.getClassId(cls.fqName))
} ?: indexFunction(
ClassId(
builtinDefFile.packageFqName,
Name.identifier(fileContent.fileName.substringBeforeLast(MetadataPackageFragment.DOT_METADATA_FILE_EXTENSION))
)
)
}
} else null
}
}
object KotlinMetadataFileIndex : KotlinMetadataFileIndexBase<KotlinMetadataFileIndex>(
KotlinMetadataFileIndex::class.java, ClassId::asSingleFqName
)
object KotlinMetadataFilePackageIndex : KotlinMetadataFileIndexBase<KotlinMetadataFilePackageIndex>(
KotlinMetadataFilePackageIndex::class.java, ClassId::getPackageFqName
)
object KotlinBuiltInsMetadataIndex : KotlinFileIndexBase<KotlinBuiltInsMetadataIndex>(KotlinBuiltInsMetadataIndex::class.java) {
override fun getIndexer() = INDEXER
override fun getInputFilter() = FileBasedIndex.InputFilter { file -> FileTypeRegistry.getInstance().isFileOfType(file, KotlinBuiltInFileType) }
override fun getVersion() = VERSION
private val VERSION = 1
private val INDEXER = indexer { fileContent ->
if (fileContent.fileType == KotlinBuiltInFileType &&
fileContent.fileName.endsWith(JvmBuiltInsPackageFragmentProvider.DOT_BUILTINS_METADATA_FILE_EXTENSION)) {
val builtins = BuiltInDefinitionFile.read(fileContent.content, fileContent.file.parent)
(builtins as? BuiltInDefinitionFile)?.packageFqName
} else null
}
}
object KotlinStdlibIndex : KotlinFileIndexBase<KotlinStdlibIndex>(KotlinStdlibIndex::class.java) {
private const val LIBRARY_NAME_MANIFEST_ATTRIBUTE = "Implementation-Title"
private const val STDLIB_TAG_MANIFEST_ATTRIBUTE = "Kotlin-Runtime-Component"
val KOTLIN_STDLIB_NAME = FqName("kotlin-stdlib")
val KOTLIN_STDLIB_COMMON_NAME = FqName("kotlin-stdlib-common")
val STANDARD_LIBRARY_DEPENDENCY_NAMES = setOf(
KOTLIN_STDLIB_COMMON_NAME,
)
override fun getIndexer() = INDEXER
override fun getInputFilter() = FileBasedIndex.InputFilter { file -> file.fileType is ManifestFileType }
override fun getVersion() = VERSION
private val VERSION = 1
// TODO: refactor [KotlinFileIndexBase] and get rid of FqName here, it's never a proper fully qualified name, just a String wrapper
private val INDEXER = indexer { fileContent ->
if (fileContent.fileType is ManifestFileType) {
val manifest = Manifest(ByteArrayInputStream(fileContent.content))
val attributes = manifest.mainAttributes
attributes.getValue(STDLIB_TAG_MANIFEST_ATTRIBUTE) ?: return@indexer null
val libraryName = attributes.getValue(LIBRARY_NAME_MANIFEST_ATTRIBUTE) ?: return@indexer null
FqName(libraryName)
} else null
}
}
object KlibMetaFileIndex : KotlinFileIndexBase<KlibMetaFileIndex>(KlibMetaFileIndex::class.java) {
override fun getIndexer() = INDEXER
override fun getInputFilter() = DefaultFileTypeSpecificInputFilter(KlibMetaFileType)
override fun getVersion() = VERSION
// This is to express intention to index all Kotlin/Native metadata files irrespectively to file size:
override fun getFileTypesWithSizeLimitNotApplicable() = listOf(KlibMetaFileType)
private const val VERSION = 4
/*todo: check version?!*/
private val INDEXER = indexer { fileContent ->
val fragment = KlibLoadingMetadataCache
.getInstance().getCachedPackageFragment(fileContent.file)
if (fragment != null)
FqName(fragment.getExtension(KlibMetadataProtoBuf.fqName))
else
null
}
}
| apache-2.0 | 85c71dc2f24ca35c7e5aed87068be047 | 40.059041 | 158 | 0.715287 | 4.890989 | false | false | false | false |
mgouline/android-samples | kotlin-demo/app/src/main/java/net/gouline/kotlindemo/model/WifiStation.kt | 1 | 1028 | package net.gouline.kotlindemo.model
import android.net.wifi.ScanResult
import java.io.Serializable
/**
* Data container for a Wi-Fi base station.
*/
data class WifiStation(
val ssid: String?,
val bssid: String? = null,
val frequency: Int? = null,
val level: Int? = null) : Serializable {
companion object {
/**
* Creates a new instance from a scan result.
*
* @param sr A scan result.
*/
fun newInstance(sr: ScanResult): WifiStation {
return WifiStation(
ssid = sr.SSID,
bssid = sr.BSSID,
frequency = sr.frequency,
level = sr.level
)
}
/**
* Creates a new list of Wi-Fi stations from a list of scan results.
*
* @param srs List of scan results.
*/
fun newList(srs: List<ScanResult>): List<WifiStation> {
return srs.map { newInstance(it) }
}
}
} | mit | d44fe9c3d1f5b35ee259cb3247676cd6 | 24.725 | 76 | 0.518482 | 4.412017 | false | false | false | false |
KaratsuFr/kyori | src/main/kotlin/fr/netsah/photoServ/repo/Mongo.kt | 1 | 724 | package fr.netsah.photoServ.repo
import com.google.gson.Gson
import com.mongodb.rx.client.MongoClients
import com.mongodb.rx.client.MongoDatabase
/**
* Database Helper
*/
class Mongo private constructor() {
private var db: MongoDatabase
init {
if(settings == null) {
db = MongoClients.create().getDatabase(dbName)
}else{
db = MongoClients.create(settings).getDatabase(dbName)
}
}
private object Holder {
val INSTANCE = Mongo().db
}
companion object {
var settings : String? = null
var dbName : String = "dbname"
val gson : Gson = Gson()
val instance: MongoDatabase by lazy { Holder.INSTANCE }
}
}
| mit | dd9177c7cc109600126332500b0285b1 | 19.685714 | 66 | 0.618785 | 4.233918 | false | false | false | false |
kivensolo/UiUsingListView | database/src/main/java/com/kingz/database/entity/UserEntity.kt | 1 | 966 | package com.kingz.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import java.io.Serializable
/**
* author: King.Z <br>
* date: 2020/7/24 22:12 <br>
* description: ๆฐๆฎๅบไฟๅญ็็จๆทไฟกๆฏๆก็ฎ <br>
*/
@Entity(tableName = "user", primaryKeys = ["id"])
class UserEntity(
@ColumnInfo(name = "admin") var admin: Boolean = false,
@ColumnInfo(name = "nickname") var nickname: String = "",
@ColumnInfo(name = "username") var username: String = "",
@ColumnInfo(name = "publicName")var publicName: String = "",
@ColumnInfo(name = "token") var token: String = "",
@ColumnInfo(name = "cookies") var cookies: String = "",
@ColumnInfo(name = "id") var id: Int = -1)
: Serializable {
override fun toString(): String {
return "UserEntity(admin=$admin, nickname='$nickname', username='$username', publicName='$publicName', token='$token', cookies='$cookies', id=$id)"
}
} | gpl-2.0 | 5f2572646caf7d4a38d67c1912549ec9 | 35.269231 | 155 | 0.642251 | 3.609195 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/hypervisor/virtualbox/VirtualBoxHypervisor.kt | 2 | 841 | package com.github.kerubistan.kerub.hypervisor.virtualbox
import com.github.kerubistan.kerub.hypervisor.Hypervisor
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.VirtualMachine
import com.github.kerubistan.kerub.utils.junix.virt.vbox.VBoxManage
import org.apache.sshd.client.session.ClientSession
class VirtualBoxHypervisor(private val client: ClientSession) : Hypervisor {
override fun stopVm(vm: VirtualMachine) {
VBoxManage.stopVm(session = client, vm = vm)
}
override fun migrate(vm: VirtualMachine, source: Host, target: Host) {
TODO()
}
override fun suspend(vm: VirtualMachine) {
VBoxManage.pauseVm(session = client, vm = vm)
}
override fun resume(vm: VirtualMachine) {
VBoxManage.resetVm(session = client, vm = vm)
}
override fun startMonitoringProcess() {
TODO()
}
} | apache-2.0 | a6f44b71d5f581390314c97741c038b5 | 27.066667 | 76 | 0.775268 | 3.504167 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/KtFileClassProviderImpl.kt | 1 | 2921 | // 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.caches.resolve
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiManager
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacadeImpl
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.idea.caches.project.getModuleInfo
import org.jetbrains.kotlin.idea.caches.resolve.util.isInDumbMode
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFileClassProvider
import org.jetbrains.kotlin.psi.analysisContext
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.scripting.definitions.runReadAction
class KtFileClassProviderImpl(val project: Project) : KtFileClassProvider {
override fun getFileClasses(file: KtFile): Array<PsiClass> {
if (file.project.isInDumbMode()) {
return PsiClass.EMPTY_ARRAY
}
// TODO We don't currently support finding light classes for scripts
if (file.isCompiled || runReadAction { file.isScript() }) {
return PsiClass.EMPTY_ARRAY
}
val moduleInfo = file.getModuleInfo()
// prohibit obtaining light classes for non-jvm modules trough KtFiles
// common files might be in fact compiled to jvm and thus correspond to a PsiClass
// this API does not provide context (like GSS) to be able to determine if this file is in fact seen through a jvm module
// this also fixes a problem where a Java JUnit run configuration producer would produce run configurations for a common file
if (!moduleInfo.platform.isJvm()) return emptyArray()
val result = arrayListOf<PsiClass>()
file.declarations.filterIsInstance<KtClassOrObject>().mapNotNullTo(result) { it.toLightClass() }
val jvmClassInfo = JvmFileClassUtil.getFileClassInfoNoResolve(file)
if (!jvmClassInfo.withJvmMultifileClass && !file.hasTopLevelCallables()) return result.toTypedArray()
val kotlinAsJavaSupport = KotlinAsJavaSupport.getInstance(project)
if (file.analysisContext == null) {
kotlinAsJavaSupport
.getFacadeClasses(file.javaFileFacadeFqName, moduleInfo.contentScope())
.filterTo(result) { it is KtLightClassForFacade && file in it.files }
} else {
result.add(kotlinAsJavaSupport.createFacadeForSyntheticFile(file.javaFileFacadeFqName, file))
}
return result.toTypedArray()
}
}
| apache-2.0 | 637a4a79c601fc9e80226accb2b93e57 | 48.508475 | 158 | 0.752824 | 4.852159 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticOverloadsRenamer.kt | 4 | 4046 | // 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.rename
import com.intellij.java.refactoring.JavaRefactoringBundle
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiElement
import com.intellij.refactoring.rename.naming.AutomaticRenamer
import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory
import com.intellij.usageView.UsageInfo
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings
import org.jetbrains.kotlin.idea.util.expectedDescriptor
import org.jetbrains.kotlin.idea.util.getAllAccessibleFunctions
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.UserDataProperty
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.source.getPsi
class AutomaticOverloadsRenamer(function: KtNamedFunction, newName: String) : AutomaticRenamer() {
companion object {
@get:TestOnly
@set:TestOnly
var PsiElement.elementFilter: ((PsiElement) -> Boolean)? by UserDataProperty(Key.create("ELEMENT_FILTER"))
}
init {
val filter = function.elementFilter
function.getOverloads().mapNotNullTo(myElements) {
val candidate = it.source.getPsi() as? KtNamedFunction ?: return@mapNotNullTo null
if (filter != null && !filter(candidate)) return@mapNotNullTo null
if (candidate != function) candidate else null
}
suggestAllNames(function.name, newName)
}
override fun getDialogTitle() = KotlinBundle.message("text.rename.overloads.title")
override fun getDialogDescription() = KotlinBundle.message("title.rename.overloads.to")
override fun entityName() = KotlinBundle.message("text.overload")
override fun isSelectedByDefault(): Boolean = true
}
private fun KtNamedFunction.getOverloads(): Collection<FunctionDescriptor> {
val name = nameAsName ?: return emptyList()
val resolutionFacade = getResolutionFacade()
val descriptor = this.unsafeResolveToDescriptor() as FunctionDescriptor
val context = resolutionFacade.analyze(this, BodyResolveMode.FULL)
val scope = getResolutionScope(context, resolutionFacade)
val extensionReceiverClass = descriptor.extensionReceiverParameter?.type?.constructor?.declarationDescriptor as? ClassDescriptor
if (descriptor.isActual && descriptor.expectedDescriptor() != null) return emptyList()
val result = LinkedHashSet<FunctionDescriptor>()
result += scope.getAllAccessibleFunctions(name)
if (extensionReceiverClass != null) {
result += extensionReceiverClass.unsubstitutedMemberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE)
}
return result
}
class AutomaticOverloadsRenamerFactory : AutomaticRenamerFactory {
override fun isApplicable(element: PsiElement): Boolean {
if (element !is KtNamedFunction) return false
if (element.isLocal) return false
return element.getOverloads().size > 1
}
override fun getOptionName() = JavaRefactoringBundle.message("rename.overloads")
override fun isEnabled() = KotlinRefactoringSettings.instance.renameOverloads
override fun setEnabled(enabled: Boolean) {
KotlinRefactoringSettings.instance.renameOverloads = enabled
}
override fun createRenamer(element: PsiElement, newName: String, usages: Collection<UsageInfo>) =
AutomaticOverloadsRenamer(element as KtNamedFunction, newName)
} | apache-2.0 | aa07f73203db8ffd855c30436574c5f1 | 46.05814 | 158 | 0.782007 | 5.044888 | false | false | false | false |
yschimke/okhttp | okhttp/src/jvmTest/java/okhttp3/internal/http2/HttpOverHttp2Test.kt | 1 | 76581 | /*
* Copyright (C) 2013 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.internal.http2
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.net.SocketTimeoutException
import java.time.Duration
import java.util.Arrays
import java.util.concurrent.BlockingQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicReference
import javax.net.ssl.SSLException
import mockwebserver3.Dispatcher
import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer
import mockwebserver3.PushPromise
import mockwebserver3.QueueDispatcher
import mockwebserver3.RecordedRequest
import mockwebserver3.SocketPolicy
import okhttp3.Cache
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Connection
import okhttp3.Cookie
import okhttp3.Credentials.basic
import okhttp3.EventListener
import okhttp3.Headers.Companion.headersOf
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.OkHttpClientTestRule
import okhttp3.Protocol
import okhttp3.RecordingCookieJar
import okhttp3.RecordingHostnameVerifier
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.Route
import okhttp3.SimpleProvider
import okhttp3.TestLogHandler
import okhttp3.TestUtil.assumeNotWindows
import okhttp3.TestUtil.repeat
import okhttp3.internal.DoubleInetAddressDns
import okhttp3.internal.EMPTY_REQUEST
import okhttp3.internal.RecordingOkAuthenticator
import okhttp3.internal.connection.RealConnection
import okhttp3.internal.discard
import okhttp3.testing.Flaky
import okhttp3.testing.PlatformRule
import okhttp3.tls.HandshakeCertificates
import okhttp3.tls.internal.TlsUtil.localhost
import okio.Buffer
import okio.BufferedSink
import okio.GzipSink
import okio.buffer
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.data.Offset
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.fail
import org.junit.jupiter.api.Assumptions.assumeTrue
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Timeout
import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.io.TempDir
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource
/** Test how HTTP/2 interacts with HTTP features. */
@Timeout(60)
@Flaky
@Tag("Slow")
class HttpOverHttp2Test {
class ProtocolParamProvider : SimpleProvider() {
override fun arguments() = listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_2)
}
@TempDir
lateinit var tempDir: File
@RegisterExtension
val platform: PlatformRule = PlatformRule()
@RegisterExtension
val clientTestRule = configureClientTestRule()
@RegisterExtension
val testLogHandler: TestLogHandler = TestLogHandler(Http2::class.java)
private lateinit var server: MockWebServer
private lateinit var protocol: Protocol
private lateinit var client: OkHttpClient
private lateinit var cache: Cache
private lateinit var scheme: String
private fun configureClientTestRule(): OkHttpClientTestRule {
val clientTestRule = OkHttpClientTestRule()
clientTestRule.recordTaskRunner = true
return clientTestRule
}
fun setUp(protocol: Protocol, server: MockWebServer) {
this.server = server
this.protocol = protocol
platform.assumeNotOpenJSSE()
platform.assumeNotBouncyCastle()
if (protocol === Protocol.HTTP_2) {
platform.assumeHttp2Support()
server.useHttps(handshakeCertificates.sslSocketFactory(), false)
client = clientTestRule.newClientBuilder()
.protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))
.sslSocketFactory(
handshakeCertificates.sslSocketFactory(),
handshakeCertificates.trustManager
)
.hostnameVerifier(RecordingHostnameVerifier())
.build()
scheme = "https"
} else {
server.protocols = listOf(Protocol.H2_PRIOR_KNOWLEDGE)
client = clientTestRule.newClientBuilder()
.protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE))
.build()
scheme = "http"
}
cache = Cache(tempDir, Int.MAX_VALUE.toLong())
}
@AfterEach fun tearDown() {
java.net.Authenticator.setDefault(null)
}
@ParameterizedTest
@ArgumentsSource(ProtocolParamProvider::class)
operator fun get(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setBody("ABCDE")
.setStatus("HTTP/1.1 200 Sweet")
)
val call = client.newCall(
Request.Builder()
.url(server.url("/foo"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABCDE")
assertThat(response.code).isEqualTo(200)
assertThat(response.message).isEqualTo("")
assertThat(response.protocol).isEqualTo(protocol)
val request = server.takeRequest()
assertThat(request.requestLine).isEqualTo("GET /foo HTTP/1.1")
assertThat(request.getHeader(":scheme")).isEqualTo(scheme)
assertThat(request.getHeader(":authority")).isEqualTo("${server.hostName}:${server.port}")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun get204Response(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val responseWithoutBody = MockResponse()
responseWithoutBody.status = "HTTP/1.1 204"
responseWithoutBody.removeHeader("Content-Length")
server.enqueue(responseWithoutBody)
val call = client.newCall(
Request.Builder()
.url(server.url("/foo"))
.build()
)
val response = call.execute()
// Body contains nothing.
assertThat(response.body!!.bytes().size).isEqualTo(0)
assertThat(response.body!!.contentLength()).isEqualTo(0)
// Content-Length header doesn't exist in a 204 response.
assertThat(response.header("content-length")).isNull()
assertThat(response.code).isEqualTo(204)
val request = server.takeRequest()
assertThat(request.requestLine).isEqualTo("GET /foo HTTP/1.1")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun head(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val mockResponse = MockResponse().setHeader("Content-Length", 5)
mockResponse.status = "HTTP/1.1 200"
server.enqueue(mockResponse)
val call = client.newCall(
Request.Builder()
.head()
.url(server.url("/foo"))
.build()
)
val response = call.execute()
// Body contains nothing.
assertThat(response.body!!.bytes().size).isEqualTo(0)
assertThat(response.body!!.contentLength()).isEqualTo(0)
// Content-Length header stays correctly.
assertThat(response.header("content-length")).isEqualTo("5")
val request = server.takeRequest()
assertThat(request.requestLine).isEqualTo("HEAD /foo HTTP/1.1")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun emptyResponse(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(MockResponse())
val call = client.newCall(
Request.Builder()
.url(server.url("/foo"))
.build()
)
val response = call.execute()
assertThat(response.body!!.byteStream().read()).isEqualTo(-1)
response.body!!.close()
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun noDefaultContentLengthOnStreamingPost(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val postBytes = "FGHIJ".toByteArray()
server.enqueue(MockResponse().setBody("ABCDE"))
val call = client.newCall(
Request.Builder()
.url(server.url("/foo"))
.post(object : RequestBody() {
override fun contentType(): MediaType = "text/plain; charset=utf-8".toMediaType()
override fun writeTo(sink: BufferedSink) {
sink.write(postBytes)
}
})
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABCDE")
val request = server.takeRequest()
assertThat(request.requestLine).isEqualTo("POST /foo HTTP/1.1")
org.junit.jupiter.api.Assertions.assertArrayEquals(postBytes, request.body.readByteArray())
assertThat(request.getHeader("Content-Length")).isNull()
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun userSuppliedContentLengthHeader(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val postBytes = "FGHIJ".toByteArray()
server.enqueue(MockResponse().setBody("ABCDE"))
val call = client.newCall(
Request.Builder()
.url(server.url("/foo"))
.post(object : RequestBody() {
override fun contentType(): MediaType = "text/plain; charset=utf-8".toMediaType()
override fun contentLength(): Long = postBytes.size.toLong()
override fun writeTo(sink: BufferedSink) {
sink.write(postBytes)
}
})
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABCDE")
val request = server.takeRequest()
assertThat(request.requestLine).isEqualTo("POST /foo HTTP/1.1")
org.junit.jupiter.api.Assertions.assertArrayEquals(postBytes, request.body.readByteArray())
assertThat(request.getHeader("Content-Length")!!.toInt()).isEqualTo(
postBytes.size.toLong()
)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun closeAfterFlush(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
val postBytes = "FGHIJ".toByteArray()
server.enqueue(MockResponse().setBody("ABCDE"))
val call = client.newCall(
Request.Builder()
.url(server.url("/foo"))
.post(object : RequestBody() {
override fun contentType(): MediaType = "text/plain; charset=utf-8".toMediaType()
override fun contentLength(): Long = postBytes.size.toLong()
override fun writeTo(sink: BufferedSink) {
sink.write(postBytes) // push bytes into the stream's buffer
sink.flush() // Http2Connection.writeData subject to write window
sink.close() // Http2Connection.writeData empty frame
}
})
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABCDE")
val request = server.takeRequest()
assertThat(request.requestLine).isEqualTo("POST /foo HTTP/1.1")
org.junit.jupiter.api.Assertions.assertArrayEquals(postBytes, request.body.readByteArray())
assertThat(request.getHeader("Content-Length")!!.toInt())
.isEqualTo(postBytes.size.toLong())
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun connectionReuse(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(MockResponse().setBody("ABCDEF"))
server.enqueue(MockResponse().setBody("GHIJKL"))
val call1 = client.newCall(
Request.Builder()
.url(server.url("/r1"))
.build()
)
val call2 = client.newCall(
Request.Builder()
.url(server.url("/r1"))
.build()
)
val response1 = call1.execute()
val response2 = call2.execute()
assertThat(response1.body!!.source().readUtf8(3)).isEqualTo("ABC")
assertThat(response2.body!!.source().readUtf8(3)).isEqualTo("GHI")
assertThat(response1.body!!.source().readUtf8(3)).isEqualTo("DEF")
assertThat(response2.body!!.source().readUtf8(3)).isEqualTo("JKL")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
response1.close()
response2.close()
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun connectionWindowUpdateAfterCanceling(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setBody(Buffer().write(ByteArray(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE + 1)))
)
server.enqueue(
MockResponse()
.setBody("abc")
)
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response1 = call1.execute()
waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE)
// Cancel the call and discard what we've buffered for the response body. This should free up
// the connection flow-control window so new requests can proceed.
call1.cancel()
assertThat(response1.body!!.source().discard(1, TimeUnit.SECONDS))
.overridingErrorMessage("Call should not have completed successfully.")
.isFalse
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
assertThat(response2.body!!.string()).isEqualTo("abc")
}
/** Wait for the client to receive `dataLength` DATA frames. */
private fun waitForDataFrames(dataLength: Int) {
val expectedFrameCount = dataLength / 16384
var dataFrameCount = 0
while (dataFrameCount < expectedFrameCount) {
val log = testLogHandler.take()
if (log == "FINE: << 0x00000003 16384 DATA ") {
dataFrameCount++
}
}
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun connectionWindowUpdateOnClose(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setBody(Buffer().write(ByteArray(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE + 1)))
)
server.enqueue(
MockResponse()
.setBody("abc")
)
// Enqueue an additional response that show if we burnt a good prior response.
server.enqueue(
MockResponse()
.setBody("XXX")
)
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response1 = call1.execute()
waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE)
// Cancel the call and close the response body. This should discard the buffered data and update
// the connection flow-control window.
call1.cancel()
response1.close()
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
assertThat(response2.body!!.string()).isEqualTo("abc")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun concurrentRequestWithEmptyFlowControlWindow(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setBody(Buffer().write(ByteArray(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE)))
)
server.enqueue(
MockResponse()
.setBody("abc")
)
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response1 = call1.execute()
waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE)
assertThat(response1.body!!.contentLength()).isEqualTo(
Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE.toLong()
)
val read = response1.body!!.source().read(ByteArray(8192))
assertThat(read).isEqualTo(8192)
// Make a second call that should transmit the response headers. The response body won't be
// transmitted until the flow-control window is updated from the first request.
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
assertThat(response2.code).isEqualTo(200)
// Close the response body. This should discard the buffered data and update the connection
// flow-control window.
response1.close()
assertThat(response2.body!!.string()).isEqualTo("abc")
}
/** https://github.com/square/okhttp/issues/373 */
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
@Disabled
fun synchronousRequest(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(MockResponse().setBody("A"))
server.enqueue(MockResponse().setBody("A"))
val executor = Executors.newCachedThreadPool()
val countDownLatch = CountDownLatch(2)
executor.execute(AsyncRequest("/r1", countDownLatch))
executor.execute(AsyncRequest("/r2", countDownLatch))
countDownLatch.await()
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun gzippedResponseBody(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.addHeader("Content-Encoding: gzip")
.setBody(gzip("ABCABCABC"))
)
val call = client.newCall(
Request.Builder()
.url(server.url("/r1"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABCABCABC")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun authenticate(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED)
.addHeader("www-authenticate: Basic realm=\"protected area\"")
.setBody("Please authenticate.")
)
server.enqueue(
MockResponse()
.setBody("Successful auth!")
)
val credential = basic("username", "password")
client = client.newBuilder()
.authenticator(RecordingOkAuthenticator(credential, "Basic"))
.build()
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("Successful auth!")
val denied = server.takeRequest()
assertThat(denied.getHeader("Authorization")).isNull()
val accepted = server.takeRequest()
assertThat(accepted.requestLine).isEqualTo("GET / HTTP/1.1")
assertThat(accepted.getHeader("Authorization")).isEqualTo(credential)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun redirect(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: /foo")
.setBody("This page has moved!")
)
server.enqueue(MockResponse().setBody("This is the new location!"))
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("This is the new location!")
val request1 = server.takeRequest()
assertThat(request1.path).isEqualTo("/")
val request2 = server.takeRequest()
assertThat(request2.path).isEqualTo("/foo")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun readAfterLastByte(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(MockResponse().setBody("ABC"))
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
val inputStream = response.body!!.byteStream()
assertThat(inputStream.read()).isEqualTo('A'.code)
assertThat(inputStream.read()).isEqualTo('B'.code)
assertThat(inputStream.read()).isEqualTo('C'.code)
assertThat(inputStream.read()).isEqualTo(-1)
assertThat(inputStream.read()).isEqualTo(-1)
inputStream.close()
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun readResponseHeaderTimeout(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE))
server.enqueue(MockResponse().setBody("A"))
client = client.newBuilder()
.readTimeout(Duration.ofSeconds(1))
.build()
// Make a call expecting a timeout reading the response headers.
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
try {
call1.execute()
fail<Any?>("Should have timed out!")
} catch (expected: SocketTimeoutException) {
assertThat(expected.message).isEqualTo("timeout")
}
// Confirm that a subsequent request on the same connection is not impacted.
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
assertThat(response2.body!!.string()).isEqualTo("A")
// Confirm that the connection was reused.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
}
/**
* Test to ensure we don't throw a read timeout on responses that are progressing. For this
* case, we take a 4KiB body and throttle it to 1KiB/second. We set the read timeout to two
* seconds. If our implementation is acting correctly, it will not throw, as it is progressing.
*/
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun readTimeoutMoreGranularThanBodySize(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val body = CharArray(4096) // 4KiB to read.
Arrays.fill(body, 'y')
server.enqueue(
MockResponse().setBody(String(body))
.throttleBody(1024, 1, TimeUnit.SECONDS) // Slow connection 1KiB/second.
)
client = client.newBuilder()
.readTimeout(Duration.ofSeconds(2))
.build()
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo(String(body))
}
/**
* Test to ensure we throw a read timeout on responses that are progressing too slowly. For this
* case, we take a 2KiB body and throttle it to 1KiB/second. We set the read timeout to half a
* second. If our implementation is acting correctly, it will throw, as a byte doesn't arrive in
* time.
*/
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun readTimeoutOnSlowConnection(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val body = repeat('y', 2048)
server.enqueue(
MockResponse()
.setBody(body)
.throttleBody(1024, 1, TimeUnit.SECONDS)
) // Slow connection 1KiB/second.
server.enqueue(
MockResponse()
.setBody(body)
)
client = client.newBuilder()
.readTimeout(Duration.ofMillis(500)) // Half a second to read something.
.build()
// Make a call expecting a timeout reading the response body.
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response1 = call1.execute()
try {
response1.body!!.string()
fail<Any?>("Should have timed out!")
} catch (expected: SocketTimeoutException) {
assertThat(expected.message).isEqualTo("timeout")
}
// Confirm that a subsequent request on the same connection is not impacted.
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
assertThat(response2.body!!.string()).isEqualTo(body)
// Confirm that the connection was reused.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun connectionTimeout(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setBody("A")
.setBodyDelay(1, TimeUnit.SECONDS)
)
val client1 = client.newBuilder()
.readTimeout(Duration.ofSeconds(2))
.build()
val call1 = client1
.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val client2 = client.newBuilder()
.readTimeout(Duration.ofMillis(200))
.build()
val call2 = client2
.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response1 = call1.execute()
assertThat(response1.body!!.string()).isEqualTo("A")
try {
call2.execute()
fail<Any?>()
} catch (expected: IOException) {
}
// Confirm that the connection was reused.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun responsesAreCached(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
client = client.newBuilder()
.cache(cache)
.build()
server.enqueue(
MockResponse()
.addHeader("cache-control: max-age=60")
.setBody("A")
)
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response1 = call1.execute()
assertThat(response1.body!!.string()).isEqualTo("A")
assertThat(cache.requestCount()).isEqualTo(1)
assertThat(cache.networkCount()).isEqualTo(1)
assertThat(cache.hitCount()).isEqualTo(0)
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
assertThat(response2.body!!.string()).isEqualTo("A")
val call3 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response3 = call3.execute()
assertThat(response3.body!!.string()).isEqualTo("A")
assertThat(cache.requestCount()).isEqualTo(3)
assertThat(cache.networkCount()).isEqualTo(1)
assertThat(cache.hitCount()).isEqualTo(2)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun conditionalCache(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
client = client.newBuilder()
.cache(cache)
.build()
server.enqueue(
MockResponse()
.addHeader("ETag: v1")
.setBody("A")
)
server.enqueue(
MockResponse()
.setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED)
)
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response1 = call1.execute()
assertThat(response1.body!!.string()).isEqualTo("A")
assertThat(cache.requestCount()).isEqualTo(1)
assertThat(cache.networkCount()).isEqualTo(1)
assertThat(cache.hitCount()).isEqualTo(0)
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
assertThat(response2.body!!.string()).isEqualTo("A")
assertThat(cache.requestCount()).isEqualTo(2)
assertThat(cache.networkCount()).isEqualTo(2)
assertThat(cache.hitCount()).isEqualTo(1)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun responseCachedWithoutConsumingFullBody(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
client = client.newBuilder()
.cache(cache)
.build()
server.enqueue(
MockResponse()
.addHeader("cache-control: max-age=60")
.setBody("ABCD")
)
server.enqueue(
MockResponse()
.addHeader("cache-control: max-age=60")
.setBody("EFGH")
)
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response1 = call1.execute()
assertThat(response1.body!!.source().readUtf8(2)).isEqualTo("AB")
response1.body!!.close()
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
assertThat(response2.body!!.source().readUtf8()).isEqualTo("ABCD")
response2.body!!.close()
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun sendRequestCookies(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val cookieJar = RecordingCookieJar()
val requestCookie = Cookie.Builder()
.name("a")
.value("b")
.domain(server.hostName)
.build()
cookieJar.enqueueRequestCookies(requestCookie)
client = client.newBuilder()
.cookieJar(cookieJar)
.build()
server.enqueue(MockResponse())
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("")
val request = server.takeRequest()
assertThat(request.getHeader("Cookie")).isEqualTo("a=b")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun receiveResponseCookies(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val cookieJar = RecordingCookieJar()
client = client.newBuilder()
.cookieJar(cookieJar)
.build()
server.enqueue(
MockResponse()
.addHeader("set-cookie: a=b")
)
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("")
cookieJar.assertResponseCookies("a=b; path=/")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun cancelWithStreamNotCompleted(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setBody("abc")
)
server.enqueue(
MockResponse()
.setBody("def")
)
// Disconnect before the stream is created. A connection is still established!
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call1.execute()
call1.cancel()
// That connection is pooled, and it works.
assertThat(client.connectionPool.connectionCount()).isEqualTo(1)
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
assertThat(response2.body!!.string()).isEqualTo("def")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
// Clean up the connection.
response.close()
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun noRecoveryFromOneRefusedStream(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setBody("abc")
)
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
try {
call.execute()
fail<Any?>()
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)
}
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun recoverFromRefusedStreamWhenAnotherRouteExists(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
client = client.newBuilder()
.dns(DoubleInetAddressDns()) // Two routes!
.build()
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setBody("abc")
)
val request = Request.Builder()
.url(server.url("/"))
.build()
val response = client.newCall(request).execute()
assertThat(response.body!!.string()).isEqualTo("abc")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
// Note that although we have two routes available, we only use one. The retry is permitted
// because there are routes available, but it chooses the existing connection since it isn't
// yet considered unhealthy.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun noRecoveryWhenRoutesExhausted(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
client = client.newBuilder()
.dns(DoubleInetAddressDns()) // Two routes!
.build()
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
val request = Request.Builder()
.url(server.url("/"))
.build()
try {
client.newCall(request).execute()
fail<Any?>()
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)
}
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) // New connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1) // Pooled connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) // New connection.
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun connectionWithOneRefusedStreamIsPooled(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setBody("abc")
)
val request = Request.Builder()
.url(server.url("/"))
.build()
// First call fails because it only has one route.
try {
client.newCall(request).execute()
fail<Any?>()
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)
}
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
// Second call succeeds on the pooled connection.
val response = client.newCall(request).execute()
assertThat(response.body!!.string()).isEqualTo("abc")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun connectionWithTwoRefusedStreamsIsNotPooled(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setBody("abc")
)
server.enqueue(
MockResponse()
.setBody("def")
)
val request = Request.Builder()
.url(server.url("/"))
.build()
// First call makes a new connection and fails because it is the only route.
try {
client.newCall(request).execute()
fail<Any?>()
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)
}
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) // New connection.
// Second call attempts the pooled connection, and it fails. Then it retries a new route which
// succeeds.
val response2 = client.newCall(request).execute()
assertThat(response2.body!!.string()).isEqualTo("abc")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1) // Pooled connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0) // New connection.
// Third call reuses the second connection.
val response3 = client.newCall(request).execute()
assertThat(response3.body!!.string()).isEqualTo("def")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1) // New connection.
}
/**
* We had a bug where we'd perform infinite retries of route that fail with connection shutdown
* errors. The problem was that the logic that decided whether to reuse a route didn't track
* certain HTTP/2 errors. https://github.com/square/okhttp/issues/5547
*/
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun noRecoveryFromTwoRefusedStreams(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setBody("abc")
)
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
try {
call.execute()
fail<Any?>()
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)
}
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun recoverFromOneInternalErrorRequiresNewConnection(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
recoverFromOneHttp2ErrorRequiresNewConnection(ErrorCode.INTERNAL_ERROR)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun recoverFromOneCancelRequiresNewConnection(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
recoverFromOneHttp2ErrorRequiresNewConnection(ErrorCode.CANCEL)
}
private fun recoverFromOneHttp2ErrorRequiresNewConnection(errorCode: ErrorCode?) {
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(errorCode!!.httpCode)
)
server.enqueue(
MockResponse()
.setBody("abc")
)
client = client.newBuilder()
.dns(DoubleInetAddressDns())
.build()
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("abc")
// New connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
// New connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun recoverFromMultipleRefusedStreamsRequiresNewConnection(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode)
)
server.enqueue(
MockResponse()
.setBody("abc")
)
client = client.newBuilder()
.dns(DoubleInetAddressDns())
.build()
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("abc")
// New connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
// Reused connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
// New connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun recoverFromCancelReusesConnection(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val responseDequeuedLatches = listOf(
CountDownLatch(1), // No synchronization for the last request, which is not canceled.
CountDownLatch(0)
)
val requestCanceledLatches = listOf(
CountDownLatch(1),
CountDownLatch(0)
)
val dispatcher = RespondAfterCancelDispatcher(responseDequeuedLatches, requestCanceledLatches)
dispatcher.enqueueResponse(
MockResponse()
.setBodyDelay(10, TimeUnit.SECONDS)
.setBody("abc")
)
dispatcher.enqueueResponse(
MockResponse()
.setBody("def")
)
server.dispatcher = dispatcher
client = client.newBuilder()
.dns(DoubleInetAddressDns())
.build()
callAndCancel(0, responseDequeuedLatches[0], requestCanceledLatches[0])
// Make a second request to ensure the connection is reused.
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("def")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun recoverFromMultipleCancelReusesConnection(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val responseDequeuedLatches = Arrays.asList(
CountDownLatch(1),
CountDownLatch(1), // No synchronization for the last request, which is not canceled.
CountDownLatch(0)
)
val requestCanceledLatches = Arrays.asList(
CountDownLatch(1),
CountDownLatch(1),
CountDownLatch(0)
)
val dispatcher = RespondAfterCancelDispatcher(responseDequeuedLatches, requestCanceledLatches)
dispatcher.enqueueResponse(
MockResponse()
.setBodyDelay(10, TimeUnit.SECONDS)
.setBody("abc")
)
dispatcher.enqueueResponse(
MockResponse()
.setBodyDelay(10, TimeUnit.SECONDS)
.setBody("def")
)
dispatcher.enqueueResponse(
MockResponse()
.setBody("ghi")
)
server.dispatcher = dispatcher
client = client.newBuilder()
.dns(DoubleInetAddressDns())
.build()
callAndCancel(0, responseDequeuedLatches[0], requestCanceledLatches[0])
callAndCancel(1, responseDequeuedLatches[1], requestCanceledLatches[1])
// Make a third request to ensure the connection is reused.
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ghi")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(2)
}
private class RespondAfterCancelDispatcher(
private val responseDequeuedLatches: List<CountDownLatch>,
private val requestCanceledLatches: List<CountDownLatch>
) : QueueDispatcher() {
private var responseIndex = 0
@Synchronized
override fun dispatch(request: RecordedRequest): MockResponse {
// This guarantees a deterministic sequence when handling the canceled request:
// 1. Server reads request and dequeues first response
// 2. Client cancels request
// 3. Server tries to send response on the canceled stream
// Otherwise, there is no guarantee for the sequence. For example, the server may use the
// first mocked response to respond to the second request.
val response = super.dispatch(request)
responseDequeuedLatches[responseIndex].countDown()
requestCanceledLatches[responseIndex].await()
responseIndex++
return response
}
}
/** Make a call and canceling it as soon as it's accepted by the server. */
private fun callAndCancel(
expectedSequenceNumber: Int, responseDequeuedLatch: CountDownLatch?,
requestCanceledLatch: CountDownLatch?
) {
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val latch = CountDownLatch(1)
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
latch.countDown()
}
override fun onResponse(call: Call, response: Response) {
fail<Any?>()
}
})
assertThat(server.takeRequest().sequenceNumber)
.isEqualTo(expectedSequenceNumber.toLong())
responseDequeuedLatch!!.await()
call.cancel()
requestCanceledLatch!!.countDown()
latch.await()
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun noRecoveryFromRefusedStreamWithRetryDisabled(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
noRecoveryFromErrorWithRetryDisabled(ErrorCode.REFUSED_STREAM)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun noRecoveryFromInternalErrorWithRetryDisabled(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
noRecoveryFromErrorWithRetryDisabled(ErrorCode.INTERNAL_ERROR)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun noRecoveryFromCancelWithRetryDisabled(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
noRecoveryFromErrorWithRetryDisabled(ErrorCode.CANCEL)
}
private fun noRecoveryFromErrorWithRetryDisabled(errorCode: ErrorCode?) {
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(errorCode!!.httpCode)
)
server.enqueue(
MockResponse()
.setBody("abc")
)
client = client.newBuilder()
.retryOnConnectionFailure(false)
.build()
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
try {
call.execute()
fail<Any?>()
} catch (expected: StreamResetException) {
assertThat(expected.errorCode).isEqualTo(errorCode)
}
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun recoverFromConnectionNoNewStreamsOnFollowUp(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setResponseCode(401)
)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
.setHttp2ErrorCode(ErrorCode.INTERNAL_ERROR.httpCode)
)
server.enqueue(
MockResponse()
.setBody("DEF")
)
server.enqueue(
MockResponse()
.setResponseCode(301)
.addHeader("Location", "/foo")
)
server.enqueue(
MockResponse()
.setBody("ABC")
)
val latch = CountDownLatch(1)
val responses: BlockingQueue<String?> = SynchronousQueue()
val authenticator = okhttp3.Authenticator { route: Route?, response: Response? ->
responses.offer(response!!.body!!.string())
try {
latch.await()
} catch (e: InterruptedException) {
throw AssertionError()
}
response.request
}
val blockingAuthClient = client.newBuilder()
.authenticator(authenticator)
.build()
val callback: Callback = object : Callback {
override fun onFailure(call: Call, e: IOException) {
fail<Any?>()
}
override fun onResponse(call: Call, response: Response) {
responses.offer(response.body!!.string())
}
}
// Make the first request waiting until we get our auth challenge.
val request = Request.Builder()
.url(server.url("/"))
.build()
blockingAuthClient.newCall(request).enqueue(callback)
val response1 = responses.take()
assertThat(response1).isEqualTo("")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
// Now make the second request which will restrict the first HTTP/2 connection from creating new
// streams.
client.newCall(request).enqueue(callback)
val response2 = responses.take()
assertThat(response2).isEqualTo("DEF")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
// Let the first request proceed. It should discard the the held HTTP/2 connection and get a new
// one.
latch.countDown()
val response3 = responses.take()
assertThat(response3).isEqualTo("ABC")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(2)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun nonAsciiResponseHeader(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.addHeaderLenient("Alpha", "ฮฑ")
.addHeaderLenient("ฮฒ", "Beta")
)
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
response.close()
assertThat(response.header("Alpha")).isEqualTo("ฮฑ")
assertThat(response.header("ฮฒ")).isEqualTo("Beta")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun serverSendsPushPromise_GET(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val pushPromise = PushPromise(
"GET", "/foo/bar", headersOf("foo", "bar"),
MockResponse().setBody("bar").setStatus("HTTP/1.1 200 Sweet")
)
server.enqueue(
MockResponse()
.setBody("ABCDE")
.setStatus("HTTP/1.1 200 Sweet")
.withPush(pushPromise)
)
val call = client.newCall(
Request.Builder()
.url(server.url("/foo"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABCDE")
assertThat(response.code).isEqualTo(200)
assertThat(response.message).isEqualTo("")
val request = server.takeRequest()
assertThat(request.requestLine).isEqualTo("GET /foo HTTP/1.1")
assertThat(request.getHeader(":scheme")).isEqualTo(scheme)
assertThat(request.getHeader(":authority")).isEqualTo(
server.hostName + ":" + server.port
)
val pushedRequest = server.takeRequest()
assertThat(pushedRequest.requestLine).isEqualTo("GET /foo/bar HTTP/1.1")
assertThat(pushedRequest.getHeader("foo")).isEqualTo("bar")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun serverSendsPushPromise_HEAD(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val pushPromise = PushPromise(
"HEAD", "/foo/bar", headersOf("foo", "bar"),
MockResponse().setStatus("HTTP/1.1 204 Sweet")
)
server.enqueue(
MockResponse()
.setBody("ABCDE")
.setStatus("HTTP/1.1 200 Sweet")
.withPush(pushPromise)
)
val call = client.newCall(
Request.Builder()
.url(server.url("/foo"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABCDE")
assertThat(response.code).isEqualTo(200)
assertThat(response.message).isEqualTo("")
val request = server.takeRequest()
assertThat(request.requestLine).isEqualTo("GET /foo HTTP/1.1")
assertThat(request.getHeader(":scheme")).isEqualTo(scheme)
assertThat(request.getHeader(":authority")).isEqualTo(
server.hostName + ":" + server.port
)
val pushedRequest = server.takeRequest()
assertThat(pushedRequest.requestLine).isEqualTo(
"HEAD /foo/bar HTTP/1.1"
)
assertThat(pushedRequest.getHeader("foo")).isEqualTo("bar")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun noDataFramesSentWithNullRequestBody(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setBody("ABC")
)
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.method("DELETE", null)
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABC")
assertThat(response.protocol).isEqualTo(protocol)
val logs = testLogHandler.takeAll()
assertThat(firstFrame(logs, "HEADERS"))
.overridingErrorMessage("header logged")
.contains("HEADERS END_STREAM|END_HEADERS")
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun emptyDataFrameSentWithEmptyBody(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setBody("ABC")
)
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.method("DELETE", EMPTY_REQUEST)
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABC")
assertThat(response.protocol).isEqualTo(protocol)
val logs = testLogHandler.takeAll()
assertThat(firstFrame(logs, "HEADERS"))
.overridingErrorMessage("header logged")
.contains("HEADERS END_HEADERS")
// While MockWebServer waits to read the client's HEADERS frame before sending the response, it
// doesn't wait to read the client's DATA frame and may send a DATA frame before the client
// does. So we can't assume the client's empty DATA will be logged first.
assertThat(countFrames(logs, "FINE: >> 0x00000003 0 DATA END_STREAM"))
.isEqualTo(2L)
assertThat(countFrames(logs, "FINE: >> 0x00000003 3 DATA "))
.isEqualTo(1L)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun pingsTransmitted(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
// Ping every 500 ms, starting at 500 ms.
client = client.newBuilder()
.pingInterval(Duration.ofMillis(500))
.build()
// Delay the response to give 1 ping enough time to be sent and replied to.
server.enqueue(
MockResponse()
.setBodyDelay(750, TimeUnit.MILLISECONDS)
.setBody("ABC")
)
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABC")
assertThat(response.protocol).isEqualTo(protocol)
// Confirm a single ping was sent and received, and its reply was sent and received.
val logs = testLogHandler.takeAll()
assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING "))
.isEqualTo(1L)
assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING "))
.isEqualTo(1L)
assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ACK"))
.isEqualTo(1L)
assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK"))
.isEqualTo(1L)
}
@Flaky @ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun missingPongsFailsConnection(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
if (protocol === Protocol.HTTP_2) {
// https://github.com/square/okhttp/issues/5221
platform.expectFailureOnJdkVersion(12)
}
// Ping every 500 ms, starting at 500 ms.
client = client.newBuilder()
.readTimeout(Duration.ofSeconds(10)) // Confirm we fail before the read timeout.
.pingInterval(Duration.ofMillis(500))
.build()
// Set up the server to ignore the socket. It won't respond to pings!
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.STALL_SOCKET_AT_START)
)
// Make a call. It'll fail as soon as our pings detect a problem.
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val executeAtNanos = System.nanoTime()
try {
call.execute()
fail<Any?>()
} catch (expected: StreamResetException) {
assertThat(expected.message).isEqualTo(
"stream was reset: PROTOCOL_ERROR"
)
}
val elapsedUntilFailure = System.nanoTime() - executeAtNanos
assertThat(TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure).toDouble())
.isCloseTo(1000.0, Offset.offset(250.0))
// Confirm a single ping was sent but not acknowledged.
val logs = testLogHandler.takeAll()
assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING "))
.isEqualTo(1L)
assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK"))
.isEqualTo(0L)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun streamTimeoutDegradesConnectionAfterNoPong(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
assumeNotWindows()
client = client.newBuilder()
.readTimeout(Duration.ofMillis(500))
.build()
// Stalling the socket will cause TWO requests to time out!
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.STALL_SOCKET_AT_START)
)
// The 3rd request should be sent to a fresh connection.
server.enqueue(
MockResponse()
.setBody("fresh connection")
)
// The first call times out.
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
try {
call1.execute()
fail<Any?>()
} catch (expected: SocketTimeoutException) {
} catch (expected: SSLException) {
}
// The second call times out because it uses the same bad connection.
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
try {
call2.execute()
fail<Any?>()
} catch (expected: SocketTimeoutException) {
}
// But after the degraded pong timeout, that connection is abandoned.
Thread.sleep(TimeUnit.NANOSECONDS.toMillis(Http2Connection.DEGRADED_PONG_TIMEOUT_NS.toLong()))
val call3 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
call3.execute().use { response ->
assertThat(
response.body!!.string()
).isEqualTo("fresh connection")
}
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun oneStreamTimeoutDoesNotBreakConnection(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
client = client.newBuilder()
.readTimeout(Duration.ofMillis(500))
.build()
server.enqueue(
MockResponse()
.setBodyDelay(1000, TimeUnit.MILLISECONDS)
.setBody("a")
)
server.enqueue(
MockResponse()
.setBody("b")
)
server.enqueue(
MockResponse()
.setBody("c")
)
// The first call times out.
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
try {
call1.execute().use { response ->
response.body!!.string()
fail<Any?>()
}
} catch (expected: SocketTimeoutException) {
}
// The second call succeeds.
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
call2.execute().use { response ->
assertThat(
response.body!!.string()
).isEqualTo("b")
}
// Calls succeed after the degraded pong timeout because the degraded pong was received.
Thread.sleep(TimeUnit.NANOSECONDS.toMillis(Http2Connection.DEGRADED_PONG_TIMEOUT_NS.toLong()))
val call3 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
call3.execute().use { response ->
assertThat(
response.body!!.string()
).isEqualTo("c")
}
// All calls share a connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(2)
}
private fun firstFrame(logs: List<String>, type: String): String? {
for (log in logs) {
if (type in log) {
return log
}
}
return null
}
private fun countFrames(logs: List<String>, message: String): Int {
var result = 0
for (log in logs) {
if (log == message) {
result++
}
}
return result
}
/**
* Push a setting that permits up to 2 concurrent streams, then make 3 concurrent requests and
* confirm that the third concurrent request prepared a new connection.
*/
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun settingsLimitsMaxConcurrentStreams(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val settings = Settings()
settings[Settings.MAX_CONCURRENT_STREAMS] = 2
// Read & write a full request to confirm settings are accepted.
server.enqueue(MockResponse().withSettings(settings))
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("")
server.enqueue(
MockResponse()
.setBody("ABC")
)
server.enqueue(
MockResponse()
.setBody("DEF")
)
server.enqueue(
MockResponse()
.setBody("GHI")
)
val call1 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response1 = call1.execute()
val call2 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
val call3 = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response3 = call3.execute()
assertThat(response1.body!!.string()).isEqualTo("ABC")
assertThat(response2.body!!.string()).isEqualTo("DEF")
assertThat(response3.body!!.string()).isEqualTo("GHI")
// Settings connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
// Reuse settings connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(1)
// Reuse settings connection.
assertThat(server.takeRequest().sequenceNumber).isEqualTo(2)
// New connection!
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun connectionNotReusedAfterShutdown(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)
.setBody("ABC")
)
server.enqueue(
MockResponse()
.setBody("DEF")
)
// Enqueue an additional response that show if we burnt a good prior response.
server.enqueue(
MockResponse()
.setBody("XXX")
)
val connections: MutableList<RealConnection?> = ArrayList()
val localClient = client.newBuilder().eventListener(object : EventListener() {
override fun connectionAcquired(call: Call, connection: Connection) {
connections.add(connection as RealConnection)
}
}).build()
val call1 = localClient.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response1 = call1.execute()
assertThat(response1.body!!.string()).isEqualTo("ABC")
// Add delays for DISCONNECT_AT_END to propogate
waitForConnectionShutdown(connections[0])
val call2 = localClient.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response2 = call2.execute()
assertThat(response2.body!!.string()).isEqualTo("DEF")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
}
@Throws(InterruptedException::class, TimeoutException::class)
private fun waitForConnectionShutdown(connection: RealConnection?) {
if (connection!!.isHealthy(false)) {
Thread.sleep(100L)
}
if (connection.isHealthy(false)) {
Thread.sleep(2000L)
}
if (connection.isHealthy(false)) {
throw TimeoutException("connection didn't shutdown within timeout")
}
}
/**
* This simulates a race condition where we receive a healthy HTTP/2 connection and just prior to
* writing our request, we get a GOAWAY frame from the server.
*/
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun connectionShutdownAfterHealthCheck(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)
.setBody("ABC")
)
server.enqueue(
MockResponse()
.setBody("DEF")
)
val client2 = client.newBuilder()
.addNetworkInterceptor(object : Interceptor {
var executedCall = false
override fun intercept(chain: Interceptor.Chain): Response {
if (!executedCall) {
// At this point, we have a healthy HTTP/2 connection. This call will trigger the
// server to send a GOAWAY frame, leaving the connection in a shutdown state.
executedCall = true
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("ABC")
// Wait until the GOAWAY has been processed.
val connection = chain.connection() as RealConnection?
while (connection!!.isHealthy(false));
}
return chain.proceed(chain.request())
}
})
.build()
val call = client2.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("DEF")
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)
}
@Flaky @ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun responseHeadersAfterGoaway(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
server.enqueue(
MockResponse()
.setHeadersDelay(1, TimeUnit.SECONDS)
.setBody("ABC")
)
server.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)
.setBody("DEF")
)
val latch = CountDownLatch(2)
val errors = ArrayList<IOException?>()
val bodies: BlockingQueue<String?> = LinkedBlockingQueue()
val callback: Callback = object : Callback {
override fun onResponse(call: Call, response: Response) {
bodies.add(response.body!!.string())
latch.countDown()
}
override fun onFailure(call: Call, e: IOException) {
errors.add(e)
latch.countDown()
}
}
client.newCall(Request.Builder().url(server.url("/")).build()).enqueue(
callback
)
client.newCall(Request.Builder().url(server.url("/")).build()).enqueue(
callback
)
latch.await()
assertThat(bodies.remove()).isEqualTo("DEF")
if (errors.isEmpty()) {
assertThat(bodies.remove()).isEqualTo("ABC")
assertThat(server.requestCount).isEqualTo(2)
} else {
// https://github.com/square/okhttp/issues/4836
// As documented in SocketPolicy, this is known to be flaky.
val error = errors[0]
if (error !is StreamResetException) {
throw error!!
}
}
}
/**
* We don't know if the connection will support HTTP/2 until after we've connected. When multiple
* connections are requested concurrently OkHttp will pessimistically connect multiple times, then
* close any unnecessary connections. This test confirms that behavior works as intended.
*
* This test uses proxy tunnels to get a hook while a connection is being established.
*/
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun concurrentHttp2ConnectionsDeduplicated(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
assumeTrue(protocol === Protocol.HTTP_2)
server.useHttps(handshakeCertificates.sslSocketFactory(), true)
val queueDispatcher = QueueDispatcher()
queueDispatcher.enqueueResponse(
MockResponse()
.setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
.clearHeaders()
)
queueDispatcher.enqueueResponse(
MockResponse()
.setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END)
.clearHeaders()
)
queueDispatcher.enqueueResponse(
MockResponse()
.setBody("call2 response")
)
queueDispatcher.enqueueResponse(
MockResponse()
.setBody("call1 response")
)
// We use a re-entrant dispatcher to initiate one HTTPS connection while the other is in flight.
server.dispatcher = object : Dispatcher() {
var requestCount = 0
override fun dispatch(request: RecordedRequest): MockResponse {
val result = queueDispatcher.dispatch(request)
requestCount++
if (requestCount == 1) {
// Before handling call1's CONNECT we do all of call2. This part re-entrant!
try {
val call2 = client.newCall(
Request.Builder()
.url("https://android.com/call2")
.build()
)
val response2 = call2.execute()
assertThat(response2.body!!.string()).isEqualTo("call2 response")
} catch (e: IOException) {
throw RuntimeException(e)
}
}
return result
}
override fun peek(): MockResponse = queueDispatcher.peek()
override fun shutdown() {
queueDispatcher.shutdown()
}
}
client = client.newBuilder()
.proxy(server.toProxyAddress())
.build()
val call1 = client.newCall(
Request.Builder()
.url("https://android.com/call1")
.build()
)
val response2 = call1.execute()
assertThat(response2.body!!.string()).isEqualTo("call1 response")
val call1Connect = server.takeRequest()
assertThat(call1Connect.method).isEqualTo("CONNECT")
assertThat(call1Connect.sequenceNumber).isEqualTo(0)
val call2Connect = server.takeRequest()
assertThat(call2Connect.method).isEqualTo("CONNECT")
assertThat(call2Connect.sequenceNumber).isEqualTo(0)
val call2Get = server.takeRequest()
assertThat(call2Get.method).isEqualTo("GET")
assertThat(call2Get.path).isEqualTo("/call2")
assertThat(call2Get.sequenceNumber).isEqualTo(0)
val call1Get = server.takeRequest()
assertThat(call1Get.method).isEqualTo("GET")
assertThat(call1Get.path).isEqualTo("/call1")
assertThat(call1Get.sequenceNumber).isEqualTo(1)
assertThat(client.connectionPool.connectionCount()).isEqualTo(1)
}
/** https://github.com/square/okhttp/issues/3103 */
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun domainFronting(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
client = client.newBuilder()
.addNetworkInterceptor(Interceptor { chain: Interceptor.Chain? ->
val request = chain!!.request().newBuilder()
.header("Host", "privateobject.com")
.build()
chain.proceed(request)
})
.build()
server.enqueue(MockResponse())
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("")
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.getHeader(":authority")).isEqualTo("privateobject.com")
}
private fun gzip(bytes: String): Buffer {
val bytesOut = Buffer()
val sink = GzipSink(bytesOut).buffer()
sink.writeUtf8(bytes)
sink.close()
return bytesOut
}
internal inner class AsyncRequest(
val path: String,
val countDownLatch: CountDownLatch
) : Runnable {
override fun run() {
try {
val call = client.newCall(
Request.Builder()
.url(server.url(path))
.build()
)
val response = call.execute()
assertThat(response.body!!.string()).isEqualTo("A")
countDownLatch.countDown()
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
/** https://github.com/square/okhttp/issues/4875 */
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun shutdownAfterLateCoalescing(protocol: Protocol, mockWebServer: MockWebServer) {
setUp(protocol, mockWebServer)
val latch = CountDownLatch(2)
val callback: Callback = object : Callback {
override fun onResponse(call: Call, response: Response) {
fail<Any?>()
}
override fun onFailure(call: Call, e: IOException) {
latch.countDown()
}
}
client =
client.newBuilder().eventListenerFactory(clientTestRule.wrap(object : EventListener() {
var callCount = 0
override fun connectionAcquired(call: Call, connection: Connection) {
try {
if (callCount++ == 1) {
server.shutdown()
}
} catch (e: IOException) {
fail<Any?>()
}
}
})).build()
client.newCall(Request.Builder().url(server.url("")).build()).enqueue(
callback
)
client.newCall(Request.Builder().url(server.url("")).build()).enqueue(
callback
)
latch.await()
}
@ParameterizedTest @ArgumentsSource(ProtocolParamProvider::class)
fun cancelWhileWritingRequestBodySendsCancelToServer(
protocol: Protocol, mockWebServer: MockWebServer
) {
setUp(protocol, mockWebServer)
server.enqueue(MockResponse())
val callReference = AtomicReference<Call?>()
val call = client.newCall(
Request.Builder()
.url(server.url("/"))
.post(object : RequestBody() {
override fun contentType() = "text/plain; charset=utf-8".toMediaType()
override fun writeTo(sink: BufferedSink) {
callReference.get()!!.cancel()
}
})
.build()
)
callReference.set(call)
try {
call.execute()
fail<Any?>()
} catch (expected: IOException) {
assertThat(call.isCanceled()).isTrue
}
val recordedRequest = server.takeRequest()
assertThat(recordedRequest.failure).hasMessage("stream was reset: CANCEL")
}
companion object {
// Flaky https://github.com/square/okhttp/issues/4632
// Flaky https://github.com/square/okhttp/issues/4633
private val handshakeCertificates: HandshakeCertificates = localhost()
}
}
| apache-2.0 | ce586749bfc7b6f3f180a6da3121c1eb | 32.601141 | 100 | 0.673531 | 4.454223 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/ClickableInScrollableViewGroupTest.kt | 3 | 9359 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation
import android.content.Context
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.viewinterop.AndroidView
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Test for [clickable] [PressInteraction] behavior in scrollable [ViewGroup]s.
*/
@MediumTest
@RunWith(AndroidJUnit4::class)
@OptIn(ExperimentalFoundationApi::class)
class ClickableInScrollableViewGroupTest {
@get:Rule
val rule = createAndroidComposeRule<ComponentActivity>()
@Test
fun clickable_scrollableViewGroup() {
val interactionSource = MutableInteractionSource()
lateinit var scope: CoroutineScope
rule.mainClock.autoAdvance = false
class ScrollingViewGroup(context: Context) : FrameLayout(context) {
override fun shouldDelayChildPressedState() = true
}
rule.activityRule.scenario.onActivity { activity ->
ComposeView(activity).apply {
activity.setContentView(ScrollingViewGroup(activity).also { it.addView(this) })
setContent {
scope = rememberCoroutineScope()
Box {
BasicText(
"ClickableText",
modifier = Modifier
.testTag("myClickable")
.combinedClickable(
interactionSource = interactionSource,
indication = null
) {}
)
}
}
}
}
val interactions = mutableListOf<Interaction>()
scope.launch {
interactionSource.interactions.collect { interactions.add(it) }
}
rule.runOnIdle {
assertThat(interactions).isEmpty()
}
rule.onNodeWithTag("myClickable")
.performTouchInput { down(center) }
val halfTapIndicationDelay = TapIndicationDelay / 2
rule.mainClock.advanceTimeBy(halfTapIndicationDelay)
// Haven't reached the tap delay yet, so we shouldn't have started a press
rule.runOnIdle {
assertThat(interactions).isEmpty()
}
// Advance past the tap delay
rule.mainClock.advanceTimeBy(halfTapIndicationDelay)
rule.runOnIdle {
assertThat(interactions).hasSize(1)
assertThat(interactions.first()).isInstanceOf(PressInteraction.Press::class.java)
}
rule.onNodeWithTag("myClickable")
.performTouchInput { up() }
rule.runOnIdle {
assertThat(interactions).hasSize(2)
assertThat(interactions.first()).isInstanceOf(PressInteraction.Press::class.java)
assertThat(interactions[1]).isInstanceOf(PressInteraction.Release::class.java)
assertThat((interactions[1] as PressInteraction.Release).press)
.isEqualTo(interactions[0])
}
}
/**
* Test case for a [clickable] inside an [AndroidView] inside a scrollable Compose container
*/
@Test
fun clickable_androidViewInScrollableContainer() {
val interactionSource = MutableInteractionSource()
lateinit var scope: CoroutineScope
rule.mainClock.autoAdvance = false
rule.setContent {
scope = rememberCoroutineScope()
Box(Modifier.verticalScroll(rememberScrollState())) {
AndroidView({ context -> ComposeView(context).apply {
setContent {
Box {
BasicText(
"ClickableText",
modifier = Modifier
.testTag("myClickable")
.combinedClickable(
interactionSource = interactionSource,
indication = null
) {}
)
}
}
} })
}
}
val interactions = mutableListOf<Interaction>()
scope.launch {
interactionSource.interactions.collect { interactions.add(it) }
}
rule.runOnIdle {
assertThat(interactions).isEmpty()
}
rule.onNodeWithTag("myClickable")
.performTouchInput { down(center) }
val halfTapIndicationDelay = TapIndicationDelay / 2
rule.mainClock.advanceTimeBy(halfTapIndicationDelay)
// Haven't reached the tap delay yet, so we shouldn't have started a press
rule.runOnIdle {
assertThat(interactions).isEmpty()
}
// Advance past the tap delay
rule.mainClock.advanceTimeBy(halfTapIndicationDelay)
rule.runOnIdle {
assertThat(interactions).hasSize(1)
assertThat(interactions.first()).isInstanceOf(PressInteraction.Press::class.java)
}
rule.onNodeWithTag("myClickable")
.performTouchInput { up() }
rule.runOnIdle {
assertThat(interactions).hasSize(2)
assertThat(interactions.first()).isInstanceOf(PressInteraction.Press::class.java)
assertThat(interactions[1]).isInstanceOf(PressInteraction.Release::class.java)
assertThat((interactions[1] as PressInteraction.Release).press)
.isEqualTo(interactions[0])
}
}
/**
* Test case for a [clickable] inside an [AndroidView] inside a non-scrollable Compose container
*/
@Test
fun clickable_androidViewInNotScrollableContainer() {
val interactionSource = MutableInteractionSource()
lateinit var scope: CoroutineScope
rule.mainClock.autoAdvance = false
rule.setContent {
scope = rememberCoroutineScope()
Box {
AndroidView({ context -> ComposeView(context).apply {
setContent {
Box {
BasicText(
"ClickableText",
modifier = Modifier
.testTag("myClickable")
.combinedClickable(
interactionSource = interactionSource,
indication = null
) {}
)
}
}
} })
}
}
val interactions = mutableListOf<Interaction>()
scope.launch {
interactionSource.interactions.collect { interactions.add(it) }
}
rule.runOnIdle {
assertThat(interactions).isEmpty()
}
rule.onNodeWithTag("myClickable")
.performTouchInput { down(center) }
// No scrollable container, so there should be no delay and we should instantly appear
// pressed
rule.runOnIdle {
assertThat(interactions).hasSize(1)
assertThat(interactions.first()).isInstanceOf(PressInteraction.Press::class.java)
}
rule.onNodeWithTag("myClickable")
.performTouchInput { up() }
rule.runOnIdle {
assertThat(interactions).hasSize(2)
assertThat(interactions.first()).isInstanceOf(PressInteraction.Press::class.java)
assertThat(interactions[1]).isInstanceOf(PressInteraction.Release::class.java)
assertThat((interactions[1] as PressInteraction.Release).press)
.isEqualTo(interactions[0])
}
}
} | apache-2.0 | aaadc996a0142869d5e877ae68d1fece | 34.18797 | 100 | 0.597393 | 5.816656 | false | true | false | false |
vickychijwani/kotlin-koans-android | app/src/main/code/me/vickychijwani/kotlinkoans/KoanActivity.kt | 1 | 20137 | package me.vickychijwani.kotlinkoans
import android.animation.Animator
import android.arch.lifecycle.*
import android.content.*
import android.os.*
import android.support.annotation.IdRes
import android.support.design.widget.*
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.drawable.DrawableCompat
import android.support.v4.view.GravityCompat
import android.support.v7.app.*
import android.view.*
import android.widget.Toast
import com.getkeepsafe.taptargetview.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.progress_widget.*
import me.vickychijwani.kotlinkoans.analytics.Analytics
import me.vickychijwani.kotlinkoans.data.*
import me.vickychijwani.kotlinkoans.features.IntroTour
import me.vickychijwani.kotlinkoans.features.about.AboutActivity
import me.vickychijwani.kotlinkoans.features.common.*
import me.vickychijwani.kotlinkoans.features.listkoans.ListKoansViewModel
import me.vickychijwani.kotlinkoans.features.settings.SettingsActivity
import me.vickychijwani.kotlinkoans.features.viewkoan.*
import me.vickychijwani.kotlinkoans.util.*
class KoanActivity : BaseActivity(),
NavigationView.OnNavigationItemSelectedListener {
@IdRes private val STARTING_MENU_ITEM_ID = 1
private val mMenuItemIdToKoan = mutableMapOf<Int, KoanMetadata>()
private val mKoanIdToMenuItemId = mutableMapOf<String, Int>()
private val mKoanIds = mutableListOf<String>()
private val APP_STATE_INTRO_SEEN = "state:intro-seen"
private val APP_STATE_TIP1_SEEN = "state:seen:tip1"
private var mIsIntroSeen: Boolean = false
private var mIsTip1Seen: Boolean = false
private val APP_STATE_LAST_VIEWED_KOAN = "state:last-viewed-koan"
private var mSelectedKoanId: String? = null
private var mDisplayedKoan: Koan? = null
private var mIsUiHidden = false
private var mListKoansObserver: Observer<ListKoansViewModel.KoanFolderData>? = null
private var mViewKoanObserver: Observer<KoanViewModel.KoanData>? = null
private val REQUEST_CODE_SETTINGS = 100
// NOTE: must keep a strong reference to this because the preference manager does not currently
// store a reference to it
private val appStateChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
when (key) {
// don't update koan code because it's already updated, as the user themselves typed it
//KoanRepository.APP_STATE_CODE ->
// ViewModelProviders.of(this).get(KoanViewModel::class.java).update()
KoanRepository.APP_STATE_LAST_RUN_STATUS ->
ViewModelProviders.of(this).get(ListKoansViewModel::class.java).update()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
run_btn.setOnClickListener {
showRunProgress()
val koanToRun = (view_pager.adapter as KoanViewPagerAdapter).getKoanToRun()
resetRunResults(koanToRun, isRunning = true)
KoanRepository.saveKoan(koanToRun)
KoanRepository.runKoan(koanToRun, this::showRunResults, this::runKoanFailed)
}
run_status_msg.setOnClickListener {
BottomSheetBehavior.from(run_status).toggleState()
}
Prefs.with(this).registerOnSharedPreferenceChangeListener(appStateChangeListener)
val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
view_pager.adapter = KoanViewPagerAdapter(this, supportFragmentManager, Koan.EMPTY)
view_pager.offscreenPageLimit = 10
tabbar.setupWithViewPager(view_pager)
// NOTE: Don't create the observer again if it exists. This is important to ensure we
// don't add multiple observers for the same Activity. Quoting LiveData#observe() docs:
// "If the given owner, observer tuple is already in the list, the call is ignored."
mListKoansObserver = mListKoansObserver ?: Observer { data ->
if (data?.folders == null) {
showGenericError()
return@Observer
}
val folders = data.folders
populateIndex(nav_view.menu, folders)
// app crashes on rotation without the waitForMeasurement call
// I have no idea why koan_progress_* views are null while others are non-null
// maybe a bug in LiveData - it's calling the observer too early?
nav_view.waitForMeasurement {
val doneKoans = folders.sumBy { it.koans.count { it.lastRunStatus == RunStatus.OK } }
val maxKoans = folders.sumBy { it.koans.size }
updateProgressBar(doneKoans, maxKoans)
}
if (mSelectedKoanId == null) {
val lastViewedKoanId: String? = Prefs.with(this)
.getString(APP_STATE_LAST_VIEWED_KOAN, mMenuItemIdToKoan[STARTING_MENU_ITEM_ID]?.id)
lastViewedKoanId?.let { loadKoan(lastViewedKoanId) }
}
}
ViewModelProviders.of(this).get(ListKoansViewModel::class.java)
.getFolders().observe(this, mListKoansObserver!!)
// NOTE: Don't create the observer again if it exists. This is important to ensure we
// don't add multiple observers for the same Activity. Quoting LiveData#observe() docs:
// "If the given owner, observer tuple is already in the list, the call is ignored."
mViewKoanObserver = mViewKoanObserver ?: Observer { data ->
if (data?.koan != null) {
showKoan(data.koan)
} else {
showGenericError()
}
}
ViewModelProviders.of(this).get(KoanViewModel::class.java).liveData
.observe(this, mViewKoanObserver!!)
mIsIntroSeen = Prefs.with(this).getBoolean(APP_STATE_INTRO_SEEN, false)
mIsTip1Seen = Prefs.with(this).getBoolean(APP_STATE_TIP1_SEEN, false)
// hide/show UI when keyboard is opened on phones in landscape mode
val MIN_CONTENT_HEIGHT = (getSizeDimen(this, R.dimen.toolbar_height)
+ getSizeDimen(this, R.dimen.tabbar_height)
+ 2 * getSizeDimen(this, R.dimen.touch_size_comfy)
+ getSizeDimen(this, R.dimen.run_status_collapsed))
addKeyboardVisibilityChangedListener(this, { _, contentHeight ->
if (contentHeight < MIN_CONTENT_HEIGHT) hideUi() else showUi()
})
nav_view.setNavigationItemSelectedListener(this)
}
override fun onStop() {
super.onStop()
saveSelectedKoanId()
try {
val koanWithUserCode = (view_pager.adapter as KoanViewPagerAdapter).getKoanToRun()
KoanRepository.saveKoan(koanWithUserCode)
ViewModelProviders.of(this).get(KoanViewModel::class.java).update()
} catch (e: NoSuchElementException) {
logError { "User code not found when saving, no idea how this happens" }
logException(e)
}
}
override fun onDestroy() {
super.onDestroy()
Prefs.with(this).unregisterOnSharedPreferenceChangeListener(appStateChangeListener)
}
override fun onBackPressed() {
val bottomSheet = BottomSheetBehavior.from(run_status)
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else if (bottomSheet.isExpanded()) {
bottomSheet.collapse()
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val KOTLIN_DOCS_URL = "http://kotlinlang.org/docs/reference/"
return when (item.itemId) {
R.id.action_next -> { loadNextKoan(); true }
R.id.action_show_answer -> { showAnswer(); true }
R.id.action_revert -> { revertCode(); true }
R.id.action_docs -> { browse(this, KOTLIN_DOCS_URL); true }
R.id.action_send_feedback -> { emailDeveloper(this); true }
R.id.action_settings -> { startSettingsActivity(); true }
R.id.action_about -> { startActivity(Intent(this, AboutActivity::class.java)); true }
else -> super.onOptionsItemSelected(item)
}
}
private fun startSettingsActivity() {
startActivityForResult(Intent(this, SettingsActivity::class.java), REQUEST_CODE_SETTINGS)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// recreate the current activity if ANY setting was changed
if (requestCode == REQUEST_CODE_SETTINGS &&
resultCode == SettingsActivity.RESULT_CODE_SETTINGS_CHANGED) {
recreate()
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
val id = item.itemId
val koanMetadata = mMenuItemIdToKoan[id]!!
loadKoan(koanMetadata)
drawer_layout.closeDrawer(GravityCompat.START)
Analytics.logKoanSelectedFromList(koanMetadata)
return true
}
fun switchToFile(fileName: String) {
(view_pager.adapter as? KoanViewPagerAdapter)?.let { adapter ->
val tabPosition = adapter.getPositionFromPageTitle(fileName)
if (tabPosition >= 0 && tabPosition < adapter.count) {
view_pager.setCurrentItem(tabPosition, true)
}
}
}
private fun showRunResults(results: KoanRunResults) {
hideRunProgress()
val runStatus = results.getStatus()
run_status_msg.text = runStatus.uiLabel
run_status_msg.setTextColor(runStatus.toColor(this))
run_status_msg.setCompoundDrawablesWithIntrinsicBounds(runStatus.toFilledIcon(this), null, null, null)
run_status_details.removeAllViews()
run_status_details.addView(RunResultsView(this, results))
BottomSheetBehavior.from(run_status).expand()
}
private fun resetRunResults(koan: Koan, isRunning: Boolean) {
val COLOR_STATUS_NONE = ContextCompat.getColor(this, R.color.status_none)
if (isRunning) {
run_status_msg.text = getString(R.string.status_running)
run_status_msg.setCompoundDrawablesWithIntrinsicBounds(R.drawable.status_none, 0, 0, 0)
} else if (koan.lastRunStatus != null) {
run_status_msg.text = "${getString(R.string.last_run_status)}: ${koan.lastRunStatus.uiLabel}"
val icon = koan.lastRunStatus.toFilledIcon(this).mutate()
DrawableCompat.setTint(icon, COLOR_STATUS_NONE)
run_status_msg.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null)
} else {
run_status_msg.text = getString(R.string.status_none)
run_status_msg.setCompoundDrawablesWithIntrinsicBounds(R.drawable.status_none, 0, 0, 0)
}
run_status_msg.setTextColor(COLOR_STATUS_NONE)
run_status_details.removeAllViews()
run_status_details.addView(RunResultsView(this))
}
private fun runKoanFailed(koan: Koan) {
if (run_progress.isVisible) {
hideRunProgress()
resetRunResults(koan, isRunning = false)
}
showGenericError()
}
private fun saveSelectedKoanId() {
mSelectedKoanId?.let {
Prefs.with(this).edit().putString(APP_STATE_LAST_VIEWED_KOAN, mSelectedKoanId).apply()
}
}
private fun loadKoan(koanMetadata: KoanMetadata) {
koan_name.text = koanMetadata.name // show the title immediately
loadKoan(koanMetadata.id)
}
private fun loadKoan(koanId: String) {
if (mSelectedKoanId == koanId) return
background_progress.show()
val viewKoanVM = ViewModelProviders.of(this).get(KoanViewModel::class.java)
viewKoanVM.loadKoan(koanId)
val menuItemId = mKoanIdToMenuItemId[koanId]
menuItemId?.let { nav_view.setCheckedItem(menuItemId) }
mSelectedKoanId = koanId
}
private fun loadNextKoan() {
mSelectedKoanId?.let {
val nextIndex = mKoanIds.indexOf(it)+1
if (nextIndex < mKoanIds.size) {
loadKoan(mKoanIds[nextIndex])
Analytics.logNextKoanBtnClicked()
} else {
Toast.makeText(this, R.string.no_koans_left, Toast.LENGTH_LONG).show()
}
}
}
private fun showKoan(koan: Koan) {
if (mDisplayedKoan == null) {
splash.animate().withLayer()
.alpha(0f)
.setListener(object : Animator.AnimatorListener {
override fun onAnimationEnd(animation: Animator?) {
splash.visibility = View.GONE
}
override fun onAnimationCancel(animation: Animator?) {}
override fun onAnimationStart(animation: Animator?) {}
override fun onAnimationRepeat(animation: Animator?) {}
})
.start()
if (!mIsIntroSeen) {
Handler(mainLooper).postDelayed({
IntroTour(this, toolbar, tabbar, run_btn, {
drawer_layout.openDrawer(GravityCompat.START)
Prefs.with(this).edit().putBoolean(APP_STATE_INTRO_SEEN, true).apply()
}).startTour()
}, 100)
} else if (!mIsTip1Seen) {
// FIXME remove this tip after a few weeks
Handler(mainLooper).postDelayed({
TapTargetView.showFor(this,
TapTarget.forToolbarOverflow(toolbar, "New settings: auto-indent and bracket auto-pairing", "These are enabled by default")
.styleWithDefaults())
Prefs.with(this).edit().putBoolean(APP_STATE_TIP1_SEEN, true).apply()
}, 100)
}
}
logInfo { "Koan selected: ${koan.name}" }
background_progress.hide()
koan_name.text = koan.name
(view_pager.adapter as? KoanViewPagerAdapter)?.let { adapter ->
adapter.koan = koan
adapter.notifyDataSetChanged()
}
hideRunProgress()
resetRunResults(koan, isRunning = false)
BottomSheetBehavior.from(run_status).collapse()
saveSelectedKoanId()
// this is false when "revert code" action is selected
if (koan.id != mDisplayedKoan?.id) {
view_pager.currentItem = 0
Analytics.logKoanViewed(koan)
}
mDisplayedKoan = koan
}
private fun updateProgressBar(done: Int, max: Int) {
if (koan_progress_done == null || koan_progress_max == null || koan_progress_bar == null) {
// FIXME no idea why this happens, I'm just suppressing the crash here
logError { "Some progress widgets are null! Logging non-fatal..." }
reportNonFatal(ProgressWidgetIsNullException())
return
}
koan_progress_done.text = "$done"
koan_progress_max.text = " / $max"
koan_progress_bar.progress = done
koan_progress_bar.max = max
}
private fun showAnswer() {
val koan = mDisplayedKoan ?: return
val solutions = koan.getModifiableFile().solutions
if (solutions == null || solutions.isEmpty()) {
return
}
val solution = solutions[0]
val rootView = layoutInflater.inflate(R.layout.code_editor, null, false)
val codeViewer = rootView.findViewById(R.id.code_editor) as CodeEditText
codeViewer.setText(solution)
codeViewer.setupForViewing()
AlertDialog.Builder(this)
.setTitle(R.string.answer)
.setView(rootView)
.setPositiveButton(R.string.code_copy, { _, _ ->
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboard.primaryClip = ClipData.newPlainText(
getString(R.string.code_copy_clipboard_label), solution)
Toast.makeText(this, R.string.code_copied, Toast.LENGTH_SHORT).show()
})
.setNegativeButton(android.R.string.cancel, { dialog, _ -> dialog.dismiss() })
.create().show()
Analytics.logAnswerShown(koan)
}
private fun revertCode() {
AlertDialog.Builder(this)
.setTitle(R.string.revert_prompt_title)
.setMessage(R.string.revert_prompt_message)
.setPositiveButton(R.string.revert, { _, _ ->
mDisplayedKoan?.let { Analytics.logCodeReverted(it) }
ViewModelProviders.of(this).get(KoanViewModel::class.java)
.update(deleteSavedData = true)
})
.setNegativeButton(android.R.string.cancel, { dialog, _ -> dialog.dismiss() })
.create().show()
mDisplayedKoan?.let { Analytics.logRevertCodeClicked(it) }
}
private fun populateIndex(menu: Menu, folders: KoanFolders) {
val NO_STATUS_ICON = ContextCompat.getDrawable(this, R.drawable.status_none)
menu.clear()
mMenuItemIdToKoan.clear()
mKoanIdToMenuItemId.clear()
mKoanIds.clear()
@IdRes var menuItemId = STARTING_MENU_ITEM_ID
for (folder in folders) {
val submenu = menu.addSubMenu(folder.name.toUpperCase())
// doesn't work
// submenu.item.icon = folder.getRunStatus()?.toFilledIcon(this) ?: NO_STATUS_ICON
for (koan in folder.koans) {
val item = submenu.add(Menu.NONE, menuItemId, Menu.NONE, koan.name)
item.icon = koan.lastRunStatus?.toFilledIcon(this) ?: NO_STATUS_ICON
item.isCheckable = true
mMenuItemIdToKoan[menuItemId] = koan
mKoanIdToMenuItemId[koan.id] = menuItemId
mKoanIds.add(koan.id)
++menuItemId
}
}
}
private fun hideUi() {
if (mIsUiHidden) return
val appbarHeight = appbar.measuredHeight
appbar.invisible()
run_status.invisible()
run_btn.invisible()
run_status_shadow.invisible()
view_pager.translationY = -appbarHeight.toFloat()
val lp = view_pager.layoutParams as? CoordinatorLayout.LayoutParams
lp?.bottomMargin = view_pager.translationY.toInt()
view_pager.layoutParams = lp
mIsUiHidden = true
}
private fun showUi() {
if (!mIsUiHidden) return
appbar.show()
run_status.show()
run_btn.show()
run_status_shadow.show()
view_pager.translationY = 0f
val lp = view_pager.layoutParams as? CoordinatorLayout.LayoutParams
lp?.bottomMargin = getSizeDimen(this, R.dimen.view_koan_margin_bottom)
view_pager.layoutParams = lp
mIsUiHidden = false
}
private fun showRunProgress() {
run_btn.isEnabled = false
run_btn.setImageDrawable(null)
run_progress.show()
}
private fun hideRunProgress() {
run_btn.isEnabled = true
run_btn.setImageResource(R.drawable.play)
run_progress.invisible()
}
private fun showGenericError() {
Toast.makeText(this, R.string.error_generic, Toast.LENGTH_SHORT).show()
}
private class ProgressWidgetIsNullException
: RuntimeException("Progress widget is null!")
}
| mit | 9d60d8bef858b3e406f5541582a49f82 | 42.119914 | 151 | 0.629091 | 4.396725 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/NodeChooseTypeAction.kt | 2 | 2629 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark.actions
import com.intellij.ide.bookmark.Bookmark
import com.intellij.ide.bookmark.BookmarkBundle
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.ui.popup.PopupState
internal class NodeChooseTypeAction : DumbAwareAction(BookmarkBundle.messagePointer("mnemonic.chooser.mnemonic.change.action.text")) {
private val popupState = PopupState.forPopup()
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = false
if (popupState.isShowing) return
val manager = event.bookmarksManager ?: return
val bookmark = event.bookmarkNodes?.singleOrNull()?.value as? Bookmark ?: return
val type = manager.getType(bookmark) ?: return
if (type == BookmarkType.DEFAULT) event.presentation.text = BookmarkBundle.message("mnemonic.chooser.mnemonic.assign.action.text")
event.presentation.isEnabledAndVisible = true
}
override fun actionPerformed(event: AnActionEvent) {
if (popupState.isRecentlyHidden) return
val manager = event.bookmarksManager ?: return
val bookmark = event.bookmarkNodes?.singleOrNull()?.value as? Bookmark ?: return
val type = manager.getType(bookmark) ?: return
val chooser = BookmarkTypeChooser(type, manager.assignedTypes, bookmark.firstGroupWithDescription?.getDescription(bookmark)) { chosenType, description ->
popupState.hidePopup()
manager.setType(bookmark, chosenType)
if (description != "") {
manager.getGroups(bookmark).firstOrNull()?.setDescription(bookmark, description)
}
}
val title = when (type) {
BookmarkType.DEFAULT -> BookmarkBundle.message("mnemonic.chooser.mnemonic.assign.popup.title")
else -> BookmarkBundle.message("mnemonic.chooser.mnemonic.change.popup.title")
}
JBPopupFactory.getInstance().createComponentPopupBuilder(chooser.content, chooser.firstButton)
.setFocusable(true).setRequestFocus(true)
.setMovable(false).setResizable(false)
.setTitle(title).createPopup()
.also { popupState.prepareToShow(it) }
.showInBestPositionFor(event.dataContext)
}
init {
isEnabledInModalContext = true
}
}
| apache-2.0 | 5a91bfe659eca841871e0342ad328277 | 46.8 | 158 | 0.766831 | 4.797445 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/renderingUtils.kt | 1 | 3585 | // 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
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.util.PsiFormatUtil
import com.intellij.psi.util.PsiFormatUtilBase
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
fun wrapOrSkip(s: String, inCode: Boolean) = if (inCode) "<code>$s</code>" else s
fun formatClassDescriptor(classDescriptor: DeclarationDescriptor) =
IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(classDescriptor)
fun formatPsiClass(
psiClass: PsiClass,
markAsJava: Boolean,
inCode: Boolean
): String {
var description: String
val kind = if (psiClass.isInterface) "interface " else "class "
description = kind + PsiFormatUtil.formatClass(
psiClass,
PsiFormatUtilBase.SHOW_CONTAINING_CLASS or PsiFormatUtilBase.SHOW_NAME or PsiFormatUtilBase.SHOW_PARAMETERS or PsiFormatUtilBase.SHOW_TYPE
)
description = wrapOrSkip(description, inCode)
return if (markAsJava) "[Java] $description" else description
}
fun formatClass(classDescriptor: DeclarationDescriptor, inCode: Boolean): String {
val element = DescriptorToSourceUtils.descriptorToDeclaration(classDescriptor)
return if (element is PsiClass) {
formatPsiClass(element, false, inCode)
} else {
wrapOrSkip(formatClassDescriptor(classDescriptor), inCode)
}
}
fun formatFunction(functionDescriptor: DeclarationDescriptor, inCode: Boolean): String {
val element = DescriptorToSourceUtils.descriptorToDeclaration(functionDescriptor)
return if (element is PsiMethod) {
formatPsiMethod(element, false, inCode)
} else {
wrapOrSkip(formatFunctionDescriptor(functionDescriptor), inCode)
}
}
private fun formatFunctionDescriptor(functionDescriptor: DeclarationDescriptor) = DescriptorRenderer.COMPACT.render(functionDescriptor)
fun formatPsiMethod(
psiMethod: PsiMethod,
showContainingClass: Boolean,
inCode: Boolean
): String {
var options = PsiFormatUtilBase.SHOW_NAME or PsiFormatUtilBase.SHOW_PARAMETERS or PsiFormatUtilBase.SHOW_TYPE
if (showContainingClass) {
//noinspection ConstantConditions
options = options or PsiFormatUtilBase.SHOW_CONTAINING_CLASS
}
var description = PsiFormatUtil.formatMethod(psiMethod, PsiSubstitutor.EMPTY, options, PsiFormatUtilBase.SHOW_TYPE)
description = wrapOrSkip(description, inCode)
return "[Java] $description"
}
fun formatJavaOrLightMethod(method: PsiMethod): String {
val originalDeclaration = method.unwrapped
return if (originalDeclaration is KtDeclaration) {
formatFunctionDescriptor(originalDeclaration.unsafeResolveToDescriptor())
} else {
formatPsiMethod(method, showContainingClass = false, inCode = false)
}
}
fun formatClass(classOrObject: KtClassOrObject) = formatClassDescriptor(classOrObject.unsafeResolveToDescriptor() as ClassDescriptor) | apache-2.0 | ffe6ca9cb22a081aa83ae57bd9314ac8 | 39.75 | 158 | 0.786332 | 4.812081 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/utils/junix/common/OsCommand.kt | 2 | 798 | package com.github.kerubistan.kerub.utils.junix.common
import com.github.kerubistan.kerub.model.HostCapabilities
import com.github.kerubistan.kerub.model.SoftwarePackage
/**
* Interface for operating system commands, see subtypes for examples.
*/
interface OsCommand {
fun providedBy() = listOf<Pair<(SoftwarePackage) -> Boolean, List<String>>>()
fun available(osVersion: SoftwarePackage, packages: List<SoftwarePackage>) =
providedBy().firstOrNull { (selector, _) ->
selector(osVersion)
}?.second?.all { wantedPkg -> packages.any { installedPkg -> installedPkg.name == wantedPkg } }
?: false
fun available(hostCapabilities: HostCapabilities?) =
hostCapabilities?.distribution != null
&& available(hostCapabilities.distribution, hostCapabilities.installedSoftware)
} | apache-2.0 | f2410424b43bbc56a3614a35b77e5ee8 | 37.047619 | 98 | 0.756892 | 4.222222 | false | false | false | false |
jwren/intellij-community | notebooks/visualization/test/org/jetbrains/plugins/notebooks/visualization/NotebookIntervalPointerTest.kt | 4 | 7296 | package org.jetbrains.plugins.notebooks.visualization
import com.intellij.util.EventDispatcher
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.catchThrowable
import org.assertj.core.api.Descriptable
import org.assertj.core.description.Description
import org.jetbrains.plugins.notebooks.visualization.NotebookCellLines.Interval
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class NotebookIntervalPointerTest {
private val exampleIntervals = listOf(
makeIntervals(),
makeIntervals(0..1),
makeIntervals(0..1, 2..4),
makeIntervals(0..1, 2..4, 5..8),
)
@Test
fun testInitialization() {
for (intervals in exampleIntervals) {
val env = TestEnv(intervals)
env.shouldBeValid(intervals)
env.shouldBeInvalid(makeInterval(10, 10..11))
}
}
@Test
fun testAddAllIntervals() {
for (intervals in exampleIntervals) {
val env = TestEnv(listOf())
env.shouldBeInvalid(intervals)
env.changeSegment(listOf(), intervals, intervals)
env.shouldBeValid(intervals)
}
}
@Test
fun testRemoveAllIntervals() {
for (intervals in exampleIntervals) {
val env = TestEnv(intervals)
env.shouldBeValid(intervals)
env.changeSegment(intervals, listOf(), listOf())
env.shouldBeInvalid(intervals)
}
}
@Test
fun testChangeElements() {
val initialIntervals = makeIntervals(0..1, 2..4, 5..8, 9..13)
val optionsToRemove = listOf(
listOf(),
initialIntervals.subList(1, 2),
initialIntervals.subList(1, 3),
initialIntervals.subList(1, 4)
)
val optionsToAdd = listOf(
listOf(),
makeIntervals(2..10).map { it.copy(ordinal = it.ordinal + 1, type = NotebookCellLines.CellType.CODE) },
makeIntervals(2..10, 11..20).map { it.copy(ordinal = it.ordinal + 1, type = NotebookCellLines.CellType.CODE) }
)
for (toRemove in optionsToRemove) {
for (toAdd in optionsToAdd) {
val start = initialIntervals.subList(0, 1)
val end = initialIntervals.subList(1 + toRemove.size, 4)
val finalIntervals = fixOrdinalsAndOffsets(start + toAdd + end)
val env = TestEnv(initialIntervals)
val pointersToUnchangedIntervals = (start + end).map { env.pointersFactory.create(it) }
val pointersToRemovedIntervals = toRemove.map { env.pointersFactory.create(it) }
pointersToUnchangedIntervals.forEach { assertThat(it.get()).isNotNull() }
pointersToRemovedIntervals.forEach { assertThat(it.get()).isNotNull }
env.changeSegment(toRemove, toAdd, finalIntervals)
pointersToUnchangedIntervals.forEach { pointer -> assertThat(pointer.get()).isNotNull() }
pointersToRemovedIntervals.forEach { pointer -> assertThat(pointer.get()).isNull() }
env.shouldBeValid(finalIntervals)
env.shouldBeInvalid(toRemove)
}
}
}
@Test
fun testReuseInterval() {
val initialIntervals = makeIntervals(0..1, 2..19, 20..199)
for ((i, selected) in initialIntervals.withIndex()) {
val dsize = 1
val changed = selected.copy(lines = selected.lines.first..selected.lines.last + dsize)
val allIntervals = fixOrdinalsAndOffsets(initialIntervals.subList(0, i) + listOf(changed) + initialIntervals.subList(i + 1, initialIntervals.size))
val env = TestEnv(initialIntervals)
val pointers = initialIntervals.map { env.pointersFactory.create(it) }
pointers.zip(initialIntervals).forEach { (pointer, interval) -> assertThat(pointer.get()).isEqualTo(interval) }
env.changeSegment(listOf(selected), listOf(changed), allIntervals)
pointers.zip(allIntervals).forEach { (pointer, interval) -> assertThat(pointer.get()).isEqualTo(interval)}
}
}
private fun fixOrdinalsAndOffsets(intervals: List<Interval>): List<Interval> {
val result = mutableListOf<Interval>()
for ((index, interval) in intervals.withIndex()) {
val expectedOffset = result.lastOrNull()?.let { it.lines.last + 1 } ?: 0
val correctInterval =
if (interval.lines.first == expectedOffset && interval.ordinal == index)
interval
else
interval.copy(ordinal = index, lines = expectedOffset..(expectedOffset + interval.lines.last - interval.lines.first))
result.add(correctInterval)
}
return result
}
private fun makeInterval(ordinal: Int, lines: IntRange) =
Interval(ordinal, NotebookCellLines.CellType.RAW, lines, NotebookCellLines.MarkersAtLines.NO)
private fun makeIntervals(vararg lines: IntRange): List<Interval> =
lines.withIndex().map { (index, lines) -> makeInterval(index, lines) }
}
private class TestEnv(intervals: List<Interval>) {
val notebookCellLines = MockNotebookCellLines(intervals = mutableListOf(*intervals.toTypedArray()))
val pointersFactory = NotebookIntervalPointerFactoryImpl(notebookCellLines)
fun changeSegment(old: List<Interval>, new: List<Interval>, allIntervals: List<Interval>) {
old.firstOrNull()?.let { firstOld ->
new.firstOrNull()?.let { firstNew ->
assertThat(firstOld.ordinal).isEqualTo(firstNew.ordinal)
}
}
notebookCellLines.intervals.clear()
notebookCellLines.intervals.addAll(allIntervals)
notebookCellLines.intervalListeners.multicaster.segmentChanged(old, old, new, new)
}
fun shouldBeValid(interval: Interval) {
assertThat(pointersFactory.create(interval).get())
.describedAs { "pointer for ${interval} should be valid, but current pointers = ${describe(notebookCellLines.intervals)}" }
.isEqualTo(interval)
}
fun shouldBeInvalid(interval: Interval) {
val error = catchThrowable {
pointersFactory.create(interval).get()
}
assertThat(error)
.describedAs { "pointer for ${interval} should be null, but current pointers = ${describe(notebookCellLines.intervals)}" }
.isNotNull()
}
fun shouldBeValid(intervals: List<Interval>): Unit = intervals.forEach { shouldBeValid(it) }
fun shouldBeInvalid(intervals: List<Interval>): Unit = intervals.forEach { shouldBeInvalid(it) }
}
private class MockNotebookCellLines(override val intervals: MutableList<Interval> = mutableListOf()) : NotebookCellLines {
init {
checkIntervals(intervals)
}
override val intervalListeners = EventDispatcher.create(NotebookCellLines.IntervalListener::class.java)
override fun intervalsIterator(startLine: Int): ListIterator<Interval> = TODO("stub")
override val modificationStamp: Long
get() = TODO("stub")
}
private fun describe(intervals: List<Interval>): String =
intervals.joinToString(separator = ",", prefix = "[", postfix = "]")
private fun checkIntervals(intervals: List<Interval>) {
intervals.zipWithNext().forEach { (prev, next) ->
assertThat(prev.lines.last + 1).describedAs { "wrong intervals: ${describe(intervals)}" }.isEqualTo(next.lines.first)
}
intervals.withIndex().forEach { (index, interval) ->
assertThat(interval.ordinal).describedAs { "wrong interval ordinal: ${describe(intervals)}" }.isEqualTo(index)
}
}
fun <Self> Descriptable<Self>.describedAs(lazyMsg: () -> String): Self =
describedAs(object : Description() {
override fun value(): String = lazyMsg()
})
| apache-2.0 | cbae32eb5176e72a03cade266c6ae349 | 34.417476 | 153 | 0.706552 | 4.332542 | false | true | false | false |
craftsmenlabs/gareth-jvm | gareth-core/src/test/kotlin/org/craftsmenlabs/gareth/validator/integration/MockGlueLineMatcherEndpoint.kt | 1 | 1873 | package org.craftsmenlabs.gareth.validator.integration
import org.craftsmenlabs.gareth.validator.model.GlueLineSearchResultDTO
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("gareth/validator/v1/")
class MockGlueLineMatcherEndpoint {
@RequestMapping(value = "search/baseline/{glueline}", method = arrayOf(RequestMethod.GET))
fun getBaselineByGlueline(@PathVariable("glueline") glueLine: String): GlueLineSearchResultDTO =
GlueLineSearchResultDTO(suggestions = listOf(glueLine), exact = glueLine)
@RequestMapping(value = "search/assume/{glueline}", method = arrayOf(RequestMethod.GET))
fun getAssumeByGlueline(@PathVariable("glueline") glueLine: String): GlueLineSearchResultDTO =
GlueLineSearchResultDTO(suggestions = listOf(glueLine), exact = glueLine)
@RequestMapping(value = "search/success/{glueline}", method = arrayOf(RequestMethod.GET))
fun getSuccessByGlueline(@PathVariable("glueline") glueLine: String): GlueLineSearchResultDTO =
GlueLineSearchResultDTO(suggestions = listOf(glueLine), exact = glueLine)
@RequestMapping(value = "search/failure/{glueline}", method = arrayOf(RequestMethod.GET))
fun getFailureByGlueline(@PathVariable("glueline") glueLine: String): GlueLineSearchResultDTO =
GlueLineSearchResultDTO(suggestions = listOf(glueLine), exact = glueLine)
@RequestMapping(value = "search/time/{glueline}", method = arrayOf(RequestMethod.GET))
fun getDurationByGlueline(@PathVariable("glueline") glueLine: String): GlueLineSearchResultDTO =
GlueLineSearchResultDTO(suggestions = listOf(glueLine), exact = glueLine)
}
| gpl-2.0 | dab02219f1fd1ff36fe14487fe5f6291 | 54.088235 | 100 | 0.777363 | 4.266515 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/mpp-additional/src/macosMain/kotlin/callingCommonized/WCommonizedCalls.kt | 12 | 715 | // !CHECK_HIGHLIGHTING
package callingCommonized
import kotlinx.cinterop.CEnum
import platform.Accelerate.AtlasConj
import platform.Accelerate.CBLAS_TRANSPOSE
import platform.Accelerate.__CLPK_real
import platform.CoreFoundation.CFAllocatorGetTypeID
import platform.CoreFoundation.CFTypeID
import platform.darwin.NSObject
import platform.posix.ns_r_notauth
actual class WCommonizedCalls actual constructor(pc: __CLPK_real) {
val eFunCall: CFTypeID = CFAllocatorGetTypeID()
actual val eClass: NSObject
get() = TODO("Not yet implemented")
actual val enumInteroped: CEnum
get() = TODO("Not yet implemented")
val eVal: CBLAS_TRANSPOSE = AtlasConj
val theCall = ns_r_notauth
}
| apache-2.0 | 166d8749bce8548375bcf2bc0de19acb | 26.5 | 67 | 0.772028 | 3.704663 | false | false | false | false |
android/storage-samples | ScopedStorage/app/src/main/java/com/samples/storage/scopedstorage/common/FilePreviewCard.kt | 1 | 3906 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.samples.storage.scopedstorage.common
import android.graphics.Bitmap
import android.text.format.Formatter
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.skydoves.landscapist.glide.GlideImage
@Composable
fun MediaFilePreviewCard(resource: FileResource) {
val context = LocalContext.current
val formattedFileSize = Formatter.formatShortFileSize(context, resource.size)
val fileMetadata = "${resource.mimeType} - $formattedFileSize"
Card(
elevation = 0.dp,
border = BorderStroke(width = 1.dp, color = compositeBorderColor()),
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
Column {
GlideImage(
imageModel = resource.uri,
contentScale = ContentScale.FillWidth,
contentDescription = null
)
Column(modifier = Modifier.padding(16.dp)) {
Text(text = resource.filename, style = MaterialTheme.typography.subtitle2)
Spacer(modifier = Modifier.height(4.dp))
Text(text = fileMetadata, style = MaterialTheme.typography.caption)
Spacer(modifier = Modifier.height(12.dp))
resource.path?.let { Text(text = it, style = MaterialTheme.typography.caption) }
}
}
}
}
@Composable
fun DocumentFilePreviewCard(resource: FileResource) {
val context = LocalContext.current
val formattedFileSize = Formatter.formatShortFileSize(context, resource.size)
val fileMetadata = "${resource.mimeType} - $formattedFileSize"
val thumbnail by produceState<Bitmap?>(null, resource.uri) {
value = SafUtils.getThumbnail(context, resource.uri)
}
Card(
elevation = 0.dp,
border = BorderStroke(width = 1.dp, color = compositeBorderColor()),
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
Column {
thumbnail?.let { Image(bitmap = it.asImageBitmap(), contentDescription = null) }
Column(modifier = Modifier.padding(16.dp)) {
Text(text = resource.filename, style = MaterialTheme.typography.subtitle2)
Spacer(modifier = Modifier.height(4.dp))
Text(text = fileMetadata, style = MaterialTheme.typography.caption)
Spacer(modifier = Modifier.height(12.dp))
resource.path?.let { Text(text = it, style = MaterialTheme.typography.caption) }
}
}
}
} | apache-2.0 | 46c41926f8b519fc4fb5eaab200fba69 | 37.303922 | 96 | 0.694828 | 4.579132 | false | false | false | false |
smmribeiro/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/personalization/session/ElementSessionFactorsStorage.kt | 12 | 750 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.ml.personalization.session
class ElementSessionFactorsStorage {
private var visiblePosition: Int = -1
private var elementFactors: Map<String, Any> = emptyMap()
fun lastUsedElementFactors(): Map<String, Any> = elementFactors
fun getVisiblePosition(): Int = visiblePosition
val selectionTracker: CompletionSelectionTrackerImpl = CompletionSelectionTrackerImpl()
fun computeSessionFactors(visiblePosition: Int, compute: (ElementSessionFactorsStorage) -> Map<String, Any>) {
this.visiblePosition = visiblePosition
this.elementFactors = compute(this)
}
} | apache-2.0 | d9d8f732bedd2a02f8b02363188e9236 | 38.526316 | 140 | 0.782667 | 4.518072 | false | false | false | false |
Keniobyte/PoliceReportsMobile | app/src/main/java/com/keniobyte/bruino/minsegapp/features/location_police_report/LocationPoliceReportActivity.kt | 1 | 7750 | package com.keniobyte.bruino.minsegapp.features.location_police_report
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import com.google.android.gms.maps.model.LatLng
import com.keniobyte.bruino.minsegapp.R
import com.keniobyte.bruino.minsegapp.features.police_report.PoliceReportActivity
import com.keniobyte.bruino.minsegapp.models.PoliceReport
import kotlinx.android.synthetic.main.activity_location_police_report2.*
import org.jetbrains.anko.alert
import org.jetbrains.anko.toast
import org.jetbrains.anko.yesButton
class LocationPoliceReportActivity : AppCompatActivity(), ILocationPoliceReportView
, MapFragment.OnPositionSelectedListener, StreetViewFragment.OnChangedPositionStreetView{
private val presenter: ILocationPoliceReportPresenter<ILocationPoliceReportView>? by lazy { LocationPoliceReportPresenter(this) }
private var mSectionsPagerAdapter: SectionsPagerAdapter? = null
private var mViewPager: ViewPager? = null
private var mLatLngPoliceReport: LatLng? = null
private var mBearingPoliceReport: Float = 0F
private var mTiltPoliceReport: Float = 0F
private var mAddressPoliceReport: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_location_police_report2)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
mViewPager = findViewById(R.id.container) as ViewPager
mViewPager!!.adapter = mSectionsPagerAdapter
val tabLayout = findViewById(R.id.tabs) as TabLayout
tabLayout.setupWithViewPager(mViewPager)
tabLayout.setOnTabSelectedListener(object : TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
override fun onTabSelected(tab: TabLayout.Tab?) {
super.onTabSelected(tab)
if (tab?.position == 1) [email protected](getString(R.string.street_view_selected))
}
})
next.visibility = View.INVISIBLE
next.setOnClickListener { presenter?.nextStep() }
setTitleToolbar(getTypePoliceReport())
}
override fun onDestroy() {
super.onDestroy()
presenter?.unregisterReceiver()
}
fun getTypePoliceReport(): String = intent.extras.getString("type_report")
override fun setLocationPoliceReport(location: LatLng) {
onPositionSelected(location)
}
override fun setEnableNextStepButton(i: Boolean) {
next.visibility = if (i) View.VISIBLE else View.INVISIBLE
}
override fun setTextPlaceAutocomplete(address: String) {
mAddressPoliceReport = address
mSectionsPagerAdapter?.updateAddress(address)
}
override fun navigationToPoliceReportActivity() {
startActivity(Intent(this, PoliceReportActivity::class.java)
.putExtra("type_report", getTypePoliceReport())
.putExtra("latitude", mLatLngPoliceReport?.latitude)
.putExtra("longitude", mLatLngPoliceReport?.longitude)
.putExtra("address", mAddressPoliceReport)
.putExtra("bearing", mBearingPoliceReport)
.putExtra("tilt", mTiltPoliceReport))
}
override fun reverseGeocodingMessageError() {
alert {
setTitle(R.string.title_attention)
messageResource = R.string.text_reverse_geocode
yesButton { [email protected](R.string.title_error) }
}
}
override fun onPositionSelected(latLng: LatLng) {
mLatLngPoliceReport = latLng
presenter?.geocodingReverse(latLng)
mSectionsPagerAdapter?.update(latLng)
//Reset bearing and tilt camera
mBearingPoliceReport = 0F
mTiltPoliceReport = 0F
}
override fun onChangedLatLngStreetView(latLng: LatLng) {
// Change the location move in tab streetview, keep the angles camera
mLatLngPoliceReport = latLng
mSectionsPagerAdapter?.update(latLng)
setEnableNextStepButton(true)
}
override fun onChangedCameraStreetView(bearing: Float, tilt: Float) {
mBearingPoliceReport = bearing
mTiltPoliceReport = tilt
}
fun setTitleToolbar(typeReport: String){
when(typeReport) {
PoliceReport.TYPE_POLICE_REPORT_AFFAIR -> {
supportActionBar?.apply {
setTitle(R.string.optional)
setSubtitle(R.string.incident_location)
}
setEnableNextStepButton(true)
}
PoliceReport.TYPE_POLICE_REPORT_AIRCRAFT -> {
supportActionBar?.apply {
setTitle(R.string.required)
setSubtitle(R.string.description_aircraft_map)
}
}
PoliceReport.TYPE_POLICE_REPORT_DRUGS -> {
supportActionBar?.apply {
setTitle(R.string.required)
setSubtitle(R.string.selected_map_drug)
}
}
PoliceReport.TYPE_POLICE_REPORT_ONLINE -> {
supportActionBar?.apply {
setTitle(R.string.required)
setSubtitle(R.string.incident_location)
}
}
PoliceReport.TYPE_OTHER_POLICE_REPORT -> {
supportActionBar?.apply {
setTitle(R.string.required)
setSubtitle(R.string.incident_location)
}
}
}
toolbar.apply {
setNavigationIcon(R.drawable.ic_arrow_back_white_24dp)
setNavigationOnClickListener { onBackPressed() }
}
}
inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
var positionPoliceReport: LatLng = LatLng(-26.8312148,-65.2033459)
var address: String? = null
override fun getItem(position: Int): Fragment? {
when (position) {
0 -> return MapFragment()
1 -> return StreetViewFragment().newInstance(positionPoliceReport.latitude, positionPoliceReport.longitude)
else -> return null
}
}
override fun getCount(): Int {
return 2
}
override fun getPageTitle(position: Int): CharSequence? {
when (position) {
0 -> return getString(R.string.map)
1 -> return getString(R.string.street_view)
}
return null
}
fun update(data: LatLng) {
this.positionPoliceReport = data
notifyDataSetChanged()
}
fun updateAddress(address: String?) {
this.address = address
}
override fun getItemPosition(`object`: Any?): Int {
if (`object` is IUpdateableStreetView) {
`object`.update(positionPoliceReport)
[email protected](getString(R.string.street_view_optional))
}
if (`object` is IUpdateAddressPlaceAutocomplete) `object`.update(address)
if (`object` is IUpdateLocationMapFragment) `object`.update(positionPoliceReport)
return super.getItemPosition(`object`)
}
}
}
| gpl-3.0 | bc82baed304d98cda33fa8d50679aba9 | 36.08134 | 133 | 0.650452 | 4.740061 | false | false | false | false |
dreampany/framework | frame/src/main/kotlin/com/dreampany/framework/ui/activity/BaseBottomNavigationActivity.kt | 1 | 1941 | package com.dreampany.framework.ui.activity
import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
import android.view.Menu
import android.view.MenuItem
import com.dreampany.framework.misc.Constants
/**
* Created by Hawladar Roman on 5/22/2018.
* BJIT Group
* [email protected]
*/
abstract class BaseBottomNavigationActivity : BaseMenuActivity(), BottomNavigationView.OnNavigationItemSelectedListener {
private var currentNavigationId: Int = 0
open fun getNavigationViewId(): Int {
return 0
}
open fun getDefaultSelectedNavigationItemId(): Int {
return 0
}
protected abstract fun onNavigationItem(navigationItemId: Int)
override fun onCreate(savedInstanceState: Bundle?) {
fireOnStartUi = false
super.onCreate(savedInstanceState)
val navigationView = findViewById<BottomNavigationView>(getNavigationViewId())
navigationView?.setOnNavigationItemSelectedListener(this)
setSelectedItem(getDefaultSelectedNavigationItemId())
onStartUi(savedInstanceState)
getApp().throwAnalytics(Constants.Event.ACTIVITY, getScreen())
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
val targetNavigationId = item.itemId
if (targetNavigationId != currentNavigationId) {
onNavigationItem(targetNavigationId)
currentNavigationId = targetNavigationId
return true
}
return false
}
override fun onMenuCreated(menu: Menu) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun setSelectedItem(navigationItemId: Int) {
if (navigationItemId != 0) {
val navView = findViewById<BottomNavigationView>(getNavigationViewId())
navView?.post { navView.selectedItemId = navigationItemId }
}
}
} | apache-2.0 | a631df76f01efb732b84d5fa1feab95d | 31.915254 | 121 | 0.715611 | 5.406685 | false | false | false | false |
intrigus/jtransc | jtransc-core/test/com/jtransc/ast/optimize/OptimizeTests.kt | 1 | 3148 | package com.jtransc.ast.optimize
import com.jtransc.ast.*
import org.junit.Assert
import org.junit.Test
class OptimizeTests {
val types = AstTypes()
val flags = AstBodyFlags(strictfp = false, types = types)
fun <T> build(callback: AstBuilder2.() -> T): T = types.build2 { callback() }
@Test fun test1() {
val expr = build { null.lit.castToUnoptimized(OBJECT).castToUnoptimized(CLASS).castToUnoptimized(STRING) }
Assert.assertEquals("((java.lang.String)((java.lang.Class)((java.lang.Object)null)))", expr.exprDump(types))
val result = expr.optimize(flags)
Assert.assertEquals("((java.lang.String)null)", result.exprDump(types))
}
@Test fun test2() {
Assert.assertEquals("1", build { 1.lit.castTo(INT) }.optimize(flags).exprDump(types))
Assert.assertEquals("(Class1.array).length", AstExpr.ARRAY_LENGTH(
AstExpr.FIELD_STATIC_ACCESS(AstFieldRef("Class1".fqname, "array", AstType.ARRAY(AstType.INT)))
).optimize(flags).exprDump(types))
}
@Test fun test3() {
Assert.assertEquals("test", AstExpr.BINOP(AstType.BOOL, AstExpr.CAST(AstExpr.LOCAL(AstLocal(0, "test", AstType.BOOL)), AstType.INT, dummy = true), AstBinop.EQ, 1.lit).optimize(flags).exprDump(types))
Assert.assertEquals("test", AstExpr.BINOP(AstType.BOOL, AstExpr.CAST(AstExpr.LOCAL(AstLocal(0, "test", AstType.BOOL)), AstType.INT, dummy = true), AstBinop.NE, 0.lit).optimize(flags).exprDump(types))
Assert.assertEquals("(!test)", AstExpr.BINOP(AstType.BOOL, AstExpr.CAST(AstExpr.LOCAL(AstLocal(0, "test", AstType.BOOL)), AstType.INT, dummy = true), AstBinop.EQ, 0.lit).optimize(flags).exprDump(types))
Assert.assertEquals("(!test)", AstExpr.BINOP(AstType.BOOL, AstExpr.CAST(AstExpr.LOCAL(AstLocal(0, "test", AstType.BOOL)), AstType.INT, dummy = true), AstBinop.NE, 1.lit).optimize(flags).exprDump(types))
}
@Test fun test4() {
Assert.assertEquals("true", AstExpr.BINOP(AstType.BOOL, AstExpr.CAST(true.lit, AstType.INT, dummy = true), AstBinop.EQ, 1.lit).optimize(flags).exprDump(types))
Assert.assertEquals("false", build { 0.lit.castTo(BOOL) }.optimize(flags).exprDump(types))
Assert.assertEquals("true", build { 1.lit.castTo(BOOL) }.optimize(flags).exprDump(types))
}
@Test fun test5() {
val test = AstExpr.LOCAL(AstLocal(0, "test", AstType.INT))
Assert.assertEquals("(test != 10)", build { test ne 10.lit }.optimize(flags).exprDump(types))
Assert.assertEquals("(test == 10)", build { (test ne 10.lit).not() }.optimize(flags).exprDump(types))
Assert.assertEquals("(test != 10)", build { (test ne 10.lit).not().not() }.optimize(flags).exprDump(types))
}
@Test fun test7() {
val stms = types.buildStms {
val obj by LOCAL(AstType.OBJECT)
val StringBuilder = AstType.REF("java.lang.StringBuilder")
val StringBuilderAppend = StringBuilder.method("append", AstType.METHOD(StringBuilder, listOf(AstType.STRING)))
SET(obj, StringBuilder.constructor().newInstance())
STM(obj[StringBuilderAppend]("hello".lit))
STM(obj[StringBuilderAppend]("hello".lit))
STM(obj[StringBuilderAppend]("hello".lit))
}
val stm2 = stms.stm().optimize(AstBodyFlags(types))
println(stms.dump(types))
println(stm2.dump(types))
}
} | apache-2.0 | a5a2399a0b4f7e0906c7eff3a4b76099 | 49.790323 | 204 | 0.718551 | 3.173387 | false | true | false | false |
jorgefranconunes/jeedemos | spring/spring-kotlin-HelloWorldController/src/main/kotlin/com/varmateo/controller/HelloWorldController.kt | 1 | 1139 | package com.varmateo.controller
import com.varmateo.controller.GreetMessageResponse
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
@RestController
class HelloWorldController {
@GetMapping(
path = ["/hello"],
produces = [MediaType.TEXT_PLAIN_VALUE])
fun hello() = "Hello, world!"
@GetMapping(
path = ["/greetings"],
produces = [MediaType.TEXT_PLAIN_VALUE])
fun greetings(
@RequestParam(value = "name", required = true)
name: String) : String {
return "Hello, ${name}!"
}
@GetMapping(
path = ["/greet-message"],
produces = [MediaType.APPLICATION_JSON_VALUE])
fun greetMessage(
@RequestParam(value = "input", required = true)
input: String) : GreetMessageResponse {
return GreetMessageResponse(
input = input,
output = "Hello, ${input.capitalize()}!")
}
}
| gpl-3.0 | e5ef352561bbf33ee8e250596775391b | 26.119048 | 61 | 0.625988 | 4.484252 | false | false | false | false |
google/intellij-gn-plugin | src/main/java/com/google/idea/gn/psi/builtin/StringSplit.kt | 1 | 1208 | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package com.google.idea.gn.psi.builtin
import com.google.idea.gn.completion.CompletionIdentifier
import com.google.idea.gn.psi.Function
import com.google.idea.gn.psi.GnCall
import com.google.idea.gn.psi.GnPsiUtil
import com.google.idea.gn.psi.GnValue
import com.google.idea.gn.psi.scope.Scope
class StringSplit : Function {
override fun execute(call: GnCall, targetScope: Scope): GnValue? {
val exprList = call.exprList.exprList
if (exprList.isEmpty()) {
return null
}
val str = GnPsiUtil.evaluate(exprList[0], targetScope)?.string ?: return null
val sep = exprList.getOrNull(1)?.let { GnPsiUtil.evaluate(it, targetScope)?.string } ?: " "
return GnValue(str.split(sep).filter { it.isNotEmpty() }.map { GnValue(it) })
}
override val isBuiltin: Boolean
get() = true
override val identifierName: String
get() = NAME
override val identifierType: CompletionIdentifier.IdentifierType
get() = CompletionIdentifier.IdentifierType.FUNCTION
companion object {
const val NAME = "string_split"
}
}
| bsd-3-clause | b561bef156c67557f4eefe8558109d6a | 34.529412 | 95 | 0.73096 | 3.847134 | false | false | false | false |
kaminomobile/AndroidVersion | plugin/src/main/kotlin/si/kamino/gradle/task/CalculateVariantVersionTask.kt | 1 | 3541 | package si.kamino.gradle.task
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import si.kamino.gradle.extensions.VersionExtension
import si.kamino.gradle.extensions.name.internal.StaticVersion
abstract class CalculateVariantVersionTask : DefaultTask() {
@get:Input
abstract val productFlavors: ListProperty<Pair<String, String>>
@get:Input
abstract val buildType: Property<String?>
@get:Nested
abstract val versionExtension: Property<VersionExtension>
@get:OutputFile
abstract val versionOutputFile: RegularFileProperty
@TaskAction
fun taskAction() {
val versionName = versionExtension.get().versionName
val variantVersion = StaticVersion(
versionName.getKeys().map { it to versionName.getValue(it) }
.toMap(LinkedHashMap())
)
// Build version names
applyFlavorVersion(versionExtension.get(), variantVersion)
applyBuildTypeVersion(versionExtension.get(), variantVersion)
applyVariantCombinationVersion(versionExtension.get(), variantVersion)
// TODO splits!! How do we get manifest file transformation for splits.
// applyOutputVersions(versionExtension, variantVersion)
versionOutputFile.get().asFile.writeText(
variantVersion.versionName()
+ "\n"
+ versionExtension.get().versionCode.getVersionCode(variantVersion).toString()
)
}
private fun applyFlavorVersion(versionExtension: VersionExtension, variantVersion: StaticVersion) {
productFlavors.get().forEach { (name, _) ->
applyVariantVersion(versionExtension, variantVersion, name)
}
}
//
private fun applyBuildTypeVersion(versionExtension: VersionExtension, variantVersion: StaticVersion) {
// TODO why could this be null?
applyVariantVersion(versionExtension, variantVersion, buildType.get()!!)
}
private fun applyVariantCombinationVersion(versionExtension: VersionExtension, variantVersion: StaticVersion) {
if (productFlavors.get().isNotEmpty()) {
var variantName = ""
productFlavors.get().forEachIndexed { index, (flavorName, _) ->
// TODO is name first or second parameter in pair?
if (index == 0) {
variantName = flavorName
} else {
variantName = "$variantName${flavorName.capitalize()}"
applyVariantVersion(versionExtension, variantVersion, variantName)
}
}
// TODO when could build type ve null?
variantName = "$variantName${buildType.get()!!.capitalize()}"
applyVariantVersion(versionExtension, variantVersion, variantName)
}
}
private fun applyVariantVersion(
versionExtension: VersionExtension,
variantVersion: StaticVersion,
variantName: String
) {
versionExtension.variants.findByName(variantName)?.let { extending ->
variantVersion.version.keys.forEach { key ->
extending.version[key]?.let { variantVersion.version[key] = it }
}
extending.suffix?.let { variantVersion.appendSuffix(it) }
}
}
} | mit | 1fdc4ddac8943de7f570806e43d5fab0 | 35.895833 | 115 | 0.668455 | 4.952448 | false | false | false | false |
gordon0001/vitaorganizer | src/com/soywiz/vitaorganizer/tasks/CheckForUpdatesTask.kt | 1 | 1257 | package com.soywiz.vitaorganizer.tasks
import com.soywiz.vitaorganizer.Texts
import com.soywiz.vitaorganizer.VitaOrganizer
import com.soywiz.vitaorganizer.VitaOrganizerVersion
import com.soywiz.vitaorganizer.ext.openWebpage
import java.net.URL
import javax.swing.JOptionPane
class CheckForUpdatesTask(vitaOrganizer: VitaOrganizer) : VitaTask(vitaOrganizer) {
override fun perform() {
val text = URL("https://raw.githubusercontent.com/soywiz/vitaorganizer/master/lastVersion.txt").readText()
val parts = text.lines()
val lastVersion = parts[0]
val lastVersionUrl = parts[1]
if (lastVersion == VitaOrganizerVersion.currentVersion) {
JOptionPane.showMessageDialog(
vitaOrganizer,
Texts.format("YOU_HAVE_LASTEST_VERSION", "version" to VitaOrganizerVersion.currentVersion),
Texts.format("ACTIONS_TITLE"),
JOptionPane.INFORMATION_MESSAGE
);
} else {
val result = JOptionPane.showConfirmDialog(
vitaOrganizer,
Texts.format("NEW_VERSION_AVAILABLE", "lastVersion" to lastVersion, "currentVersion" to VitaOrganizerVersion.currentVersion),
Texts.format("ACTIONS_TITLE"),
JOptionPane.YES_NO_OPTION
);
if (result == JOptionPane.OK_OPTION) {
openWebpage(URL(lastVersionUrl))
}
}
println(parts)
}
} | gpl-3.0 | 48b08ed5fcc63093e2a71a0c56cc3dac | 33.944444 | 129 | 0.763723 | 3.867692 | false | true | false | false |
jayrave/falkon | falkon-sql-builder-test-common/src/main/kotlin/com/jayrave/falkon/sqlBuilders/test/ResultSetExtn.kt | 1 | 640 | package com.jayrave.falkon.sqlBuilders.test
import java.sql.ResultSet
import java.util.*
fun ResultSet.extractRecordsAsMap(columnNamesInQuery: List<String>): List<Map<String, String?>> {
val allRecords = ArrayList<Map<String, String?>>()
while (!isAfterLast) {
allRecords.add(columnNamesInQuery.associate { columnName ->
val columnIndex = findColumn(columnName)
val string: String? = when {
getObject(columnIndex) == null -> null
else -> getString(columnIndex)
}
columnName to string
})
next()
}
return allRecords
} | apache-2.0 | 6686283d38087e7250af3882dfde7e42 | 26.869565 | 97 | 0.621875 | 4.885496 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/main/tut11/blinnVsPhongLighting.kt | 2 | 13215 | package main.tut11
import com.jogamp.newt.event.KeyEvent
import com.jogamp.newt.event.MouseEvent
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL3
import com.jogamp.opengl.GL3.GL_DEPTH_CLAMP
import glNext.*
import glm.f
import glm.glm
import glm.mat.Mat4
import glm.quat.Quat
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import main.framework.Framework
import main.framework.Semantic
import main.framework.component.Mesh
import main.tut11.BlinnVsPhongLighting_.LightingModel.PhongSpecular
import main.tut11.BlinnVsPhongLighting_.LightingModel.BlinnOnly
import main.tut11.BlinnVsPhongLighting_.LightingModel.BlinnSpecular
import main.tut11.BlinnVsPhongLighting_.LightingModel.PhongOnly
import uno.buffer.destroy
import uno.buffer.intBufferBig
import uno.glm.MatrixStack
import uno.glsl.programOf
import uno.mousePole.*
import uno.time.Timer
/**
* Created by GBarbieri on 24.03.2017.
*/
fun main(args: Array<String>) {
BlinnVsPhongLighting_().setup("Tutorial 11 - Blinn vs Phong Lighting")
}
class BlinnVsPhongLighting_ : Framework() {
lateinit var programs: Array<ProgramPairs>
lateinit var unlit: UnlitProgData
val initialViewData = ViewData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f),
5.0f,
0.0f)
val viewScale = ViewScale(
3.0f, 20.0f,
1.5f, 0.5f,
0.0f, 0.0f, //No camera movement.
90.0f / 250.0f)
val initialObjectData = ObjectData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(1.0f, 0.0f, 0.0f, 0.0f))
val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1)
val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole)
lateinit var cylinder: Mesh
lateinit var plane: Mesh
lateinit var cube: Mesh
var lightModel = LightingModel.BlinnSpecular
var drawColoredCyl = false
var drawLightSource = false
var scaleCyl = false
var drawDark = false
var lightHeight = 1.5f
var lightRadius = 1.0f
val lightAttenuation = 1.2f
val darkColor = Vec4(0.2f, 0.2f, 0.2f, 1.0f)
val lightColor = Vec4(1.0f)
val lightTimer = Timer(Timer.Type.Loop, 5.0f)
val projectionUniformBuffer = intBufferBig(1)
override fun init(gl: GL3) = with(gl) {
initializePrograms(gl)
cylinder = Mesh(gl, javaClass, "tut11/UnitCylinder.xml")
plane = Mesh(gl, javaClass, "tut11/LargePlane.xml")
cube = Mesh(gl, javaClass, "tut11/UnitCube.xml")
val depthZNear = 0.0f
val depthZFar = 1.0f
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
glFrontFace(GL_CW)
glEnable(GL_DEPTH_TEST)
glDepthMask(true)
glDepthFunc(GL_LEQUAL)
glDepthRangef(depthZNear, depthZFar)
glEnable(GL_DEPTH_CLAMP)
glGenBuffer(projectionUniformBuffer)
glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer)
glBufferData(GL_UNIFORM_BUFFER, Mat4.SIZE, GL_DYNAMIC_DRAW)
//Bind the static buffers.
glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.PROJECTION, projectionUniformBuffer, 0, Mat4.SIZE)
glBindBuffer(GL_UNIFORM_BUFFER)
}
fun initializePrograms(gl: GL3) {
val FRAGMENTS = arrayOf("phong-lighting", "phong-only", "blinn-lighting", "blinn-only")
programs = Array(LightingModel.MAX, {
ProgramPairs(ProgramData(gl, "pn.vert", "${FRAGMENTS[it]}.frag"), ProgramData(gl, "pcn.vert", "${FRAGMENTS[it]}.frag"))
})
unlit = UnlitProgData(gl, "pos-transform.vert", "uniform-color.frag")
}
override fun display(gl: GL3) = with(gl) {
lightTimer.update()
glClearBufferf(GL_COLOR, 0)
glClearBufferf(GL_DEPTH)
val modelMatrix = MatrixStack()
modelMatrix.setMatrix(viewPole.calcMatrix())
val worldLightPos = calcLightPosition()
val lightPosCameraSpace = modelMatrix.top() * worldLightPos
val whiteProg = programs[lightModel].whiteProgram
val colorProg = programs[lightModel].colorProgram
glUseProgram(whiteProg.theProgram)
glUniform4f(whiteProg.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f)
glUniform4f(whiteProg.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f)
glUniform3f(whiteProg.cameraSpaceLightPosUnif, lightPosCameraSpace)
glUniform1f(whiteProg.lightAttenuationUnif, lightAttenuation)
glUniform1f(whiteProg.shininessFactorUnif, MaterialParameters.getSpecularValue(lightModel))
glUniform4f(whiteProg.baseDiffuseColorUnif, if (drawDark) darkColor else lightColor)
glUseProgram(colorProg.theProgram)
glUniform4f(colorProg.lightIntensityUnif, 0.8f, 0.8f, 0.8f, 1.0f)
glUniform4f(colorProg.ambientIntensityUnif, 0.2f, 0.2f, 0.2f, 1.0f)
glUniform3f(colorProg.cameraSpaceLightPosUnif, lightPosCameraSpace)
glUniform1f(colorProg.lightAttenuationUnif, lightAttenuation)
glUniform1f(colorProg.shininessFactorUnif, MaterialParameters.getSpecularValue(lightModel))
glUseProgram()
modelMatrix run {
//Render the ground plane.
run {
val normMatrix = top().toMat3()
normMatrix.inverse_().transpose_()
glUseProgram(whiteProg.theProgram)
glUniformMatrix4f(whiteProg.modelToCameraMatrixUnif, top())
glUniformMatrix3f(whiteProg.normalModelToCameraMatrixUnif, normMatrix)
plane.render(gl)
glUseProgram()
}
//Render the Cylinder
run {
applyMatrix(objectPole.calcMatrix())
if (scaleCyl)
scale(1.0f, 1.0f, 0.2f)
val normMatrix = top().toMat3()
normMatrix.inverse_().transpose_()
val prog = if (drawColoredCyl) colorProg else whiteProg
glUseProgram(prog.theProgram)
glUniformMatrix4f(prog.modelToCameraMatrixUnif, top())
glUniformMatrix3f(prog.normalModelToCameraMatrixUnif, normMatrix)
cylinder.render(gl, if (drawColoredCyl) "lit-color" else "lit")
glUseProgram()
}
//Render the light
if (drawLightSource)
run {
translate(worldLightPos)
scale(0.1f)
glUseProgram(unlit.theProgram)
glUniformMatrix4f(unlit.modelToCameraMatrixUnif, top())
glUniform4f(unlit.objectColorUnif, 0.8078f, 0.8706f, 0.9922f, 1.0f)
cube.render(gl, "flat")
}
}
}
fun calcLightPosition(): Vec4 {
val currentTimeThroughLoop = lightTimer.getAlpha()
val ret = Vec4(0.0f, lightHeight, 0.0f, 1.0f)
ret.x = glm.cos(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius
ret.z = glm.sin(currentTimeThroughLoop * (glm.PIf * 2.0f)) * lightRadius
return ret
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
val zNear = 1.0f
val zFar = 1_000f
val perspMatrix = MatrixStack()
val proj = perspMatrix.perspective(45.0f, w.f / h, zNear, zFar).top()
glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer)
glBufferSubData(GL_UNIFORM_BUFFER, proj)
glBindBuffer(GL_UNIFORM_BUFFER)
glViewport(w, h)
}
override fun mousePressed(e: MouseEvent) {
viewPole.mousePressed(e)
objectPole.mousePressed(e)
}
override fun mouseDragged(e: MouseEvent) {
viewPole.mouseDragged(e)
objectPole.mouseDragged(e)
}
override fun mouseReleased(e: MouseEvent) {
viewPole.mouseReleased(e)
objectPole.mouseReleased(e)
}
override fun mouseWheelMoved(e: MouseEvent) {
viewPole.mouseWheel(e)
}
override fun keyPressed(e: KeyEvent) {
var changedShininess = false
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_SPACE -> drawColoredCyl = !drawColoredCyl
KeyEvent.VK_I -> lightHeight += if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_K -> lightHeight -= if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_L -> lightRadius += if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_J -> lightRadius -= if (e.isShiftDown) 0.05f else 0.2f
KeyEvent.VK_O -> {
MaterialParameters.increment(lightModel, !e.isShiftDown)
changedShininess = true
}
KeyEvent.VK_U -> {
MaterialParameters.decrement(lightModel, !e.isShiftDown)
changedShininess = true
}
KeyEvent.VK_Y -> drawLightSource = !drawLightSource
KeyEvent.VK_T -> scaleCyl = !scaleCyl
KeyEvent.VK_B -> lightTimer.togglePause()
KeyEvent.VK_G -> drawDark = !drawDark
KeyEvent.VK_H -> {
if (e.isShiftDown)
if (lightModel % 2 != 0)
lightModel -= 1
else
lightModel += 1
else
lightModel = (lightModel + 2) % LightingModel.MAX
println(when (lightModel) {
PhongSpecular -> "PhongSpecular"
PhongOnly -> "PhongOnly"
BlinnSpecular -> "BlinnSpecular"
else -> "BlinnOnly"
})
}
}
if (lightRadius < 0.2f)
lightRadius = 0.2f
if (changedShininess)
println("Shiny: " + MaterialParameters.getSpecularValue(lightModel))
}
override fun end(gl: GL3) = with(gl) {
programs.forEach { glDeletePrograms(it.whiteProgram.theProgram, it.colorProgram.theProgram) }
glDeleteProgram(unlit.theProgram)
glDeleteBuffer(projectionUniformBuffer)
cylinder.dispose(gl)
plane.dispose(gl)
cube.dispose(gl)
projectionUniformBuffer.destroy()
}
object LightingModel {
val PhongSpecular = 0
val PhongOnly = 1
val BlinnSpecular = 2
val BlinnOnly = 3
val MAX = 4
}
class ProgramPairs(var whiteProgram: ProgramData, var colorProgram: ProgramData)
class ProgramData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut11", vertex, fragment)
val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
val lightIntensityUnif = gl.glGetUniformLocation(theProgram, "lightIntensity")
val ambientIntensityUnif = gl.glGetUniformLocation(theProgram, "ambientIntensity")
val normalModelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "normalModelToCameraMatrix")
val cameraSpaceLightPosUnif = gl.glGetUniformLocation(theProgram, "cameraSpaceLightPos")
val lightAttenuationUnif = gl.glGetUniformLocation(theProgram, "lightAttenuation")
val shininessFactorUnif = gl.glGetUniformLocation(theProgram, "shininessFactor")
val baseDiffuseColorUnif = gl.glGetUniformLocation(theProgram, "baseDiffuseColor")
init {
gl.glUniformBlockBinding(
theProgram,
gl.glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
}
}
class UnlitProgData(gl: GL3, vertex: String, fragment: String) {
val theProgram = programOf(gl, javaClass, "tut11", vertex, fragment)
val objectColorUnif = gl.glGetUniformLocation(theProgram, "objectColor")
val modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
init {
gl.glUniformBlockBinding(
theProgram,
gl.glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
}
}
object MaterialParameters {
private var phongExponent = 4.0f
private var blinnExponent = 4.0f
fun getSpecularValue(model: Int) = when (model) {
PhongSpecular, PhongOnly -> phongExponent
else -> blinnExponent
}
fun increment(model: Int, isLarge: Boolean) {
when (model) {
PhongSpecular, PhongOnly -> phongExponent += if (isLarge) 0.5f else 0.1f
else -> blinnExponent += if (isLarge) 0.5f else 0.1f
}
clampParam(model)
}
fun decrement(model: Int, isLarge: Boolean) {
when (model) {
PhongSpecular, PhongOnly -> phongExponent -= if (isLarge) 0.5f else 0.1f
else -> blinnExponent -= if (isLarge) 0.5f else 0.1f
}
clampParam(model)
}
fun clampParam(model: Int) {
when (model) {
PhongSpecular, PhongOnly -> if (phongExponent <= 0.0f) phongExponent = 0.0001f
else -> if (blinnExponent <= 0.0f) blinnExponent = 0.0001f
}
}
}
} | mit | 5035340c246df0b92d7bea2a40629967 | 31.794045 | 131 | 0.619296 | 4.067405 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy | src/main/kotlin/com/zj/example/kotlin/basicsknowledge/5.RangeExample.kt | 1 | 570 | package com.zj.example.kotlin.basicsknowledge
/**
* Created by zhengjiong
* date: 2017/9/10 17:28
*/
val range1: IntRange = 1..100 //[1,100]
var range2: IntRange = 1 until 100 //[1, 99)
var range3: IntRange = 1..-1 //null
fun main(args: Array<String>) {
println(range1.contains(1))//true
println(1 in range2)//true
println(range3.isEmpty())//true
println(range3 == null)//false, range3ๆฏempty่ไธๆฏnull
println(range3)//1..-1
for (i in range3) {
//ๅ ไธบrange3ๆฏempty, ๆไปฅไธไผ่ฟๅ
ฅforๅพช็ฏ
println(i)
}
} | mit | 14540b93bb0c7c0cc12eb43629a8bc98 | 21.541667 | 55 | 0.637037 | 3.050847 | false | false | false | false |
nguyenhoanglam/ImagePicker | imagepicker/src/main/java/com/nguyenhoanglam/imagepicker/ui/imagepicker/ImagePicker.kt | 1 | 2798 | /*
* Copyright (C) 2021 Image Picker
* Author: Nguyen Hoang Lam <[email protected]>
*/
package com.nguyenhoanglam.imagepicker.ui.imagepicker
import android.content.Context
import android.content.Intent
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import com.nguyenhoanglam.imagepicker.helper.Constants
import com.nguyenhoanglam.imagepicker.model.Image
import com.nguyenhoanglam.imagepicker.model.ImagePickerConfig
import com.nguyenhoanglam.imagepicker.ui.camera.CameraActivity
typealias ImagePickerCallback = (ArrayList<Image>) -> Unit
class ImagePickerLauncher(
private val context: () -> Context,
private val resultLauncher: ActivityResultLauncher<Intent>
) {
fun launch(config: ImagePickerConfig = ImagePickerConfig()) {
val intent = createImagePickerIntent(context(), config)
resultLauncher.launch(intent)
}
companion object {
fun createIntent(
context: Context,
config: ImagePickerConfig = ImagePickerConfig()
): Intent {
return createImagePickerIntent(context, config)
}
}
}
private fun createImagePickerIntent(context: Context, config: ImagePickerConfig): Intent {
val intent: Intent
if (config.isCameraOnly) {
intent = Intent(context, CameraActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
} else {
intent = Intent(context, ImagePickerActivity::class.java)
}
intent.putExtra(Constants.EXTRA_CONFIG, config)
return intent
}
fun getImages(data: Intent?): ArrayList<Image> {
return if (data != null) data.getParcelableArrayListExtra(Constants.EXTRA_IMAGES)!!
else arrayListOf()
}
fun ComponentActivity.registerImagePicker(
context: () -> Context = { this },
callback: ImagePickerCallback
): ImagePickerLauncher {
return ImagePickerLauncher(context, createLauncher(callback))
}
fun Fragment.registerImagePicker(
context: () -> Context = { requireContext() },
callback: ImagePickerCallback
): ImagePickerLauncher {
return ImagePickerLauncher(context, createLauncher(callback))
}
private fun ComponentActivity.createLauncher(callback: ImagePickerCallback): ActivityResultLauncher<Intent> {
return registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
val images = getImages(it.data)
callback(images)
}
}
private fun Fragment.createLauncher(callback: ImagePickerCallback): ActivityResultLauncher<Intent> {
return registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
val images = getImages(it.data)
callback(images)
}
}
| apache-2.0 | b225010064c6c5078e64e63f104eb1e6 | 31.917647 | 109 | 0.748034 | 4.694631 | false | true | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/features/weapons/WeaponSelectionListFragment.kt | 1 | 3759 | package com.ghstudios.android.features.weapons
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.annotation.DrawableRes
import androidx.fragment.app.ListFragment
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.ghstudios.android.AssetLoader
import com.ghstudios.android.data.classes.Weapon
import com.ghstudios.android.features.weapons.list.WeaponListActivity
import com.ghstudios.android.mhgendatabase.R
class WeaponSelectionItem(
val type: String,
@DrawableRes val resource: Int
)
private val weaponListItems = listOf(
WeaponSelectionItem(Weapon.GREAT_SWORD, R.drawable.icon_great_sword),
WeaponSelectionItem(Weapon.LONG_SWORD, R.drawable.icon_long_sword),
WeaponSelectionItem(Weapon.SWORD_AND_SHIELD, R.drawable.icon_sword_and_shield),
WeaponSelectionItem(Weapon.DUAL_BLADES, R.drawable.icon_dual_blades),
WeaponSelectionItem(Weapon.HAMMER, R.drawable.icon_hammer),
WeaponSelectionItem(Weapon.HUNTING_HORN, R.drawable.icon_hunting_horn),
WeaponSelectionItem(Weapon.LANCE, R.drawable.icon_lance),
WeaponSelectionItem(Weapon.GUNLANCE, R.drawable.icon_gunlance),
WeaponSelectionItem(Weapon.SWITCH_AXE, R.drawable.icon_switch_axe),
WeaponSelectionItem(Weapon.CHARGE_BLADE, R.drawable.icon_charge_blade),
WeaponSelectionItem(Weapon.INSECT_GLAIVE, R.drawable.icon_insect_glaive),
WeaponSelectionItem(Weapon.LIGHT_BOWGUN, R.drawable.icon_light_bowgun),
WeaponSelectionItem(Weapon.HEAVY_BOWGUN, R.drawable.icon_heavy_bowgun),
WeaponSelectionItem(Weapon.BOW, R.drawable.icon_bow)
)
class WeaponSelectionListFragment : ListFragment() {
override fun onCreateView(inflater: LayoutInflater, parent: ViewGroup?,
savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_generic_list, parent, false)
val mAdapter = WeaponItemAdapter(weaponListItems)
listAdapter = mAdapter
return v
}
private inner class WeaponItemAdapter(items: List<WeaponSelectionItem>) : ArrayAdapter<WeaponSelectionItem>(requireContext(), 0, items) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
// If there's already an inflated view, reuse it
val view = when(convertView) {
null -> {
val inflater = LayoutInflater.from(context)
inflater.inflate(R.layout.fragment_list_item_large, parent, false)
}
else -> convertView
}
val item = checkNotNull(getItem(position))
val textView = view.findViewById<TextView>(R.id.item_label)
val imageView = view.findViewById<ImageView>(R.id.item_image)
val itemLayout = view.findViewById<RelativeLayout>(R.id.listitem)
textView.text = AssetLoader.localizeWeaponType(item.type)
imageView.setImageResource(item.resource)
itemLayout.setOnClickListener(WeaponListClickListener(view.context, item.type))
return view
}
}
private inner class WeaponListClickListener(private val c: Context, private val type: String) : OnClickListener {
override fun onClick(v: View) {
val intent = Intent(c, WeaponListActivity::class.java)
intent.putExtra(WeaponListActivity.EXTRA_WEAPON_TYPE, type)
c.startActivity(intent)
}
}
}
| mit | 3ba46fe5d641307f0161ae4b16c108cc | 40.307692 | 141 | 0.708699 | 4.291096 | false | false | false | false |
ruuvi/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/about/ui/AboutActivity.kt | 1 | 3382 | package com.ruuvi.station.about.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.ruuvi.station.BuildConfig
import com.ruuvi.station.R
import com.ruuvi.station.database.LocalDatabase
import com.ruuvi.station.database.tables.TagSensorReading
import kotlinx.android.synthetic.main.activity_about.toolbar
import kotlinx.android.synthetic.main.content_about.debugInfo
import kotlinx.android.synthetic.main.content_about.infoText
import kotlinx.android.synthetic.main.content_about.moreText
import kotlinx.android.synthetic.main.content_about.openText
import kotlinx.android.synthetic.main.content_about.operationsText
import kotlinx.android.synthetic.main.content_about.troubleshootingText
import com.ruuvi.station.util.extensions.viewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.closestKodein
import java.io.File
@ExperimentalCoroutinesApi
class AboutActivity : AppCompatActivity(), KodeinAware {
override val kodein: Kodein by closestKodein()
private val viewModel: AboutActivityViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = null
supportActionBar?.setIcon(R.drawable.logo_white)
infoText.movementMethod = LinkMovementMethod.getInstance()
operationsText.movementMethod = LinkMovementMethod.getInstance()
troubleshootingText.movementMethod = LinkMovementMethod.getInstance()
openText.movementMethod = LinkMovementMethod.getInstance()
moreText.movementMethod = LinkMovementMethod.getInstance()
lifecycleScope.launch {
viewModel.tagsSizesFlow.collect {
drawDebugInfo(it)
}
}
}
private fun drawDebugInfo(sizes: Pair<Int, Int>?) {
val readingCount = TagSensorReading.countAll()
var debugText = getString(R.string.version, BuildConfig.VERSION_NAME) + "\n"
sizes?.let {
val addedTags = it.first
debugText += getString(R.string.help_seen_tags, addedTags + it.second) + "\n"
debugText += getString(R.string.help_added_tags, addedTags) + "\n"
debugText += getString(R.string.help_db_data_points, readingCount) + "\n"
}
val dbPath = application.filesDir.path + "/../databases/" + LocalDatabase.NAME + ".db"
val dbFile = File(dbPath)
debugText += getString(R.string.help_db_size, dbFile.length() / 1024)
debugInfo.text = debugText
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
}
return true
}
companion object {
fun start(context: Context) {
val aboutIntent = Intent(context, AboutActivity::class.java)
context.startActivity(aboutIntent)
}
}
}
| mit | df68e74dab8c4354262804a02271807a | 37 | 94 | 0.72945 | 4.551817 | false | false | false | false |
Shynixn/PetBlocks | petblocks-bukkit-plugin/petblocks-bukkit-nms-108R3/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_8_R3/NMSPetVillager.kt | 1 | 4697 | package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_8_R3
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.business.proxy.PathfinderProxy
import com.github.shynixn.petblocks.api.business.service.ConcurrencyService
import com.github.shynixn.petblocks.api.persistence.entity.AIMovement
import net.minecraft.server.v1_8_R3.*
import org.bukkit.Location
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld
import org.bukkit.event.entity.CreatureSpawnEvent
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class NMSPetVillager(petDesign: NMSPetArmorstand, location: Location) : EntityPig((location.world as CraftWorld).handle) {
private var petDesign: NMSPetArmorstand? = null
private var pathfinderCounter = 0
init {
this.petDesign = petDesign
this.b(true)
clearAIGoals()
this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).value = 0.30000001192092896 * 0.75
this.S = 1.0F
val mcWorld = (location.world as CraftWorld).handle
this.setPosition(location.x, location.y - 200, location.z)
mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM)
val targetLocation = location.clone()
PetBlocksApi.resolve(ConcurrencyService::class.java).runTaskSync(20L) {
// Only fix location if it is not already fixed.
if (this.bukkitEntity.location.distance(targetLocation) > 20) {
this.setPosition(targetLocation.x, targetLocation.y + 1.0, targetLocation.z)
}
}
}
/**
* Applies pathfinders to the entity.
*/
fun applyPathfinders(pathfinders: List<Any>) {
clearAIGoals()
for (pathfinder in pathfinders) {
if (pathfinder is PathfinderProxy) {
this.goalSelector.a(pathfinderCounter++, Pathfinder(pathfinder))
val aiBase = pathfinder.aiBase
if (aiBase is AIMovement) {
this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).value = 0.30000001192092896 * aiBase.movementSpeed
this.S = aiBase.climbingHeight.toFloat()
}
} else {
this.goalSelector.a(pathfinderCounter++, pathfinder as PathfinderGoal)
}
}
}
/**
* Gets called on move to play sounds.
*/
override fun a(blockposition: BlockPosition, block: Block) {
if (petDesign == null) {
return
}
if (!this.inWater) {
petDesign!!.proxy.playMovementEffects()
}
}
/**
* Disable health.
*/
override fun setHealth(f: Float) {
}
/**
* Gets the bukkit entity.
*/
override fun getBukkitEntity(): CraftPet {
if (this.bukkitEntity == null) {
this.bukkitEntity = CraftPet(this.world.server, this)
}
return this.bukkitEntity as CraftPet
}
/**
* Clears all entity aiGoals.
*/
private fun clearAIGoals() {
val bField = PathfinderGoalSelector::class.java.getDeclaredField("b")
bField.isAccessible = true
(bField.get(this.goalSelector) as MutableList<*>).clear()
(bField.get(this.targetSelector) as MutableList<*>).clear()
val cField = PathfinderGoalSelector::class.java.getDeclaredField("c")
cField.isAccessible = true
(cField.get(this.goalSelector) as MutableList<*>).clear()
(cField.get(this.targetSelector) as MutableList<*>).clear()
}
} | apache-2.0 | 649802449e1870c4e0f2f8090e919386 | 35.138462 | 130 | 0.668725 | 4.309174 | false | false | false | false |
nlefler/Glucloser | Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/ui/HistoricalBolusDetailActivityFragment.kt | 1 | 8166 | package com.nlefler.glucloser.a.ui
import android.support.v4.app.Fragment
import android.os.Bundle
import android.os.Parcelable
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
//import com.github.mikephil.charting.charts.LineChart
//import com.github.mikephil.charting.data.ChartData
//import com.github.mikephil.charting.data.Entry
//import com.github.mikephil.charting.data.LineData
//import com.github.mikephil.charting.data.LineDataSet
//import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import com.nlefler.glucloser.a.GlucloserApplication
import com.nlefler.glucloser.a.R
import com.nlefler.glucloser.a.dataSource.FoodFactory
import com.nlefler.glucloser.a.dataSource.FoodListRecyclerAdapter
import com.nlefler.glucloser.a.dataSource.PumpDataFactory
import com.nlefler.glucloser.a.models.parcelable.BolusEventParcelable
import com.nlefler.glucloser.a.models.Food
import com.nlefler.glucloser.a.models.SensorReading
import rx.Observer
import rx.Scheduler
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.ArrayList
class HistoricalBolusDetailActivityFragment : Fragment() {
var foodFactory: FoodFactory? = null
var pumpDataFactory: PumpDataFactory? = null
private var placeName: String? = null
private var bolusEventParcelable: BolusEventParcelable? = null
private var placeNameField: TextView? = null
private var carbValueField: TextView? = null
private var insulinValueField: TextView? = null
private var beforeSugarValueField: TextView? = null
private var correctionValueBox: CheckBox? = null
// private var sensorChart: LineChart? = null
private var foodListView: RecyclerView? = null
private var foodListLayoutManager: RecyclerView.LayoutManager? = null
private var foodListAdapter: FoodListRecyclerAdapter? = null
private var foods: MutableList<Food> = ArrayList()
override fun onCreate(bundle: Bundle?) {
super.onCreate(bundle)
val dataFactory = GlucloserApplication.sharedApplication?.rootComponent
foodFactory = dataFactory?.foodFactory()
pumpDataFactory = dataFactory?.pumpDataFactory()
this.bolusEventParcelable = getBolusEventParcelableFromBundle(bundle, arguments, activity.intent.extras)
this.placeName = getPlaceNameFromBundle(bundle, arguments, activity.intent.extras)
for (foodPar in this.bolusEventParcelable?.foodParcelables ?: ArrayList()) {
// TODO(nl) make food
val food = foodFactory?.foodFromParcelable(foodPar)
if (food != null) {
this.foods.add(food)
this.foodListAdapter?.setFoods(this.foods)
this.foodListAdapter?.notifyDataSetChanged()
}
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
val rootView = inflater!!.inflate(R.layout.fragment_historical_bolus_detail, container, false)
linkViews(rootView)
setValuesInViews()
loadSensorValues()
return rootView
}
private fun linkViews(rootView: View) {
this.placeNameField = rootView.findViewById(R.id.historical_bolus_detail_place_name) as TextView
this.carbValueField = rootView.findViewById(R.id.historical_bolus_detail_total_carb_value) as TextView
this.insulinValueField = rootView.findViewById(R.id.historical_bolus_detail_total_insulin_value) as TextView
this.beforeSugarValueField = rootView.findViewById(R.id.historical_bolus_detail_blood_sugar_before_value) as TextView
this.correctionValueBox = rootView.findViewById(R.id.historical_bolus_detail_correction_value) as CheckBox
// sensorChart = rootView.findViewById(R.id.historical_bolus_detail_sensor_chart) as LineChart
this.foodListView = rootView.findViewById(R.id.historical_bolus_detail_food_list) as RecyclerView
this.foodListLayoutManager = LinearLayoutManager(activity)
this.foodListView?.layoutManager = this.foodListLayoutManager
this.foodListView?.addItemDecoration(DividerItemDecoration(activity))
}
private fun setValuesInViews() {
this.placeNameField?.text = this.placeName ?: ""
this.carbValueField?.text = "${this.bolusEventParcelable?.carbs}"
this.insulinValueField?.text = "${this.bolusEventParcelable?.insulin}"
this.beforeSugarValueField?.text = "${this.bolusEventParcelable?.bloodSugarParcelable?.value}"
this.correctionValueBox?.isChecked = this.bolusEventParcelable?.isCorrection ?: false
this.foodListAdapter = FoodListRecyclerAdapter(this.foods)
this.foodListView?.adapter = this.foodListAdapter
this.foodListAdapter?.setFoods(this.foods)
this.foodListAdapter?.notifyDataSetChanged()
}
private fun loadSensorValues() {
// val dataList = ArrayList<Entry>()
// var minReading = Float.MAX_VALUE
// var maxReading = Float.MIN_VALUE
//
// val date = bolusEventParcelable?.date ?: return
// pumpDataFactory?.sensorReadingsAfter(date)
// ?.subscribeOn(Schedulers.newThread())
// ?.observeOn(AndroidSchedulers.mainThread())
// ?.subscribe(object: Observer<SensorReading> {
// override fun onNext(reading: SensorReading) {
// val fReading = reading.reading.toFloat()
// dataList.add(Entry(fReading, dataList.count() + 1))
// minReading = if (fReading < minReading) fReading else minReading
// maxReading = if (fReading > maxReading) fReading else maxReading
// }
//
// override fun onCompleted() {
// val dataSet = LineDataSet(dataList, getString(R.string.sensor_readings_chart_label))
// dataSet.lineWidth = 2f
// dataSet.setDrawCircles(false)
// dataSet.color = R.color.bright_foreground_material_dark
//
// sensorChart?.data = LineData(ChartData.generateXVals(0, dataSet.entryCount), listOf(dataSet))
// sensorChart?.setDescription(getString(R.string.sensor_readings_chart_label))
//
// sensorChart?.axisLeft?.setAxisMinValue(minReading)
// sensorChart?.axisLeft?.setAxisMaxValue(maxReading)
// sensorChart?.axisRight?.isEnabled = false
// sensorChart?.invalidate()
// }
//
// override fun onError(t: Throwable) {
//
// }
// })
}
private fun getPlaceNameFromBundle(vararg bundles: Bundle?): String {
for (bundle in bundles) {
if (bundle?.containsKey(HistoricalBolusDetailActivityFragment.Companion.HistoricalBolusDetailPlaceNameBundleKey) ?: false) {
return bundle?.getString(HistoricalBolusDetailActivityFragment.Companion.HistoricalBolusDetailPlaceNameBundleKey) ?: ""
}
}
return ""
}
private fun getBolusEventParcelableFromBundle(vararg bundles: Bundle?): BolusEventParcelable? {
for (bundle in bundles) {
if (bundle?.containsKey(HistoricalBolusDetailActivityFragment.Companion.HistoricalBolusEventBolusDetailParcelableBundleKey) ?: false) {
return bundle?.getParcelable<Parcelable>(HistoricalBolusDetailActivityFragment.Companion.HistoricalBolusEventBolusDetailParcelableBundleKey) as BolusEventParcelable?
}
}
return null
}
companion object {
public val HistoricalBolusDetailPlaceNameBundleKey: String = "HistoricalBolusDetailPlaceNameBundleKey"
public val HistoricalBolusEventBolusDetailParcelableBundleKey: String = "HistoricalBolusDetailBolusEventParcelableBundleKey"
}
}
| gpl-2.0 | b87066cf7ddbe63d16e9e18056969a26 | 45.135593 | 181 | 0.70022 | 4.685026 | false | false | false | false |
lttng/lttng-scope | jabberwocky-ctf/src/main/kotlin/com/efficios/jabberwocky/ctf/trace/event/CtfTraceEventFieldParser.kt | 2 | 3709 | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.ctf.trace.event
import com.efficios.jabberwocky.trace.event.FieldValue
import com.efficios.jabberwocky.trace.event.FieldValue.*
import org.eclipse.tracecompass.ctf.core.event.types.*
object CtfTraceEventFieldParser {
fun parseField(fieldDef: IDefinition): FieldValue = when (fieldDef) {
is IntegerDefinition -> IntegerValue(fieldDef.value, fieldDef.declaration.base)
is FloatDefinition -> FloatValue(fieldDef.value)
is StringDefinition -> StringValue(fieldDef.value)
is AbstractArrayDefinition -> {
val decl = fieldDef.declaration as? CompoundDeclaration ?: throw IllegalArgumentException("Array definitions should only come from sequence or array declarations") //$NON-NLS-1$
val elemType = decl.elementType
if (elemType is IntegerDeclaration) {
/*
* Array of integers => either an array of integers values or a
* string.
*/
/* Are the integers characters and encoded? */
when {
elemType.isCharacter -> StringValue(fieldDef.toString()) /* it's a banal string */
fieldDef is ByteArrayDefinition -> {
/*
* Unsigned byte array, consider this field an array of integers
*/
val elements = (0 until fieldDef.length)
.map { idx -> java.lang.Byte.toUnsignedLong(fieldDef.getByte(idx)) }
.map { longVal -> IntegerValue(longVal, elemType.base) }
.toTypedArray()
ArrayValue(elements)
}
else -> {
/* Consider this a straight array of integers */
val elements = fieldDef.definitions
.filterNotNull()
.map { elem ->
val integerDef = elem as IntegerDefinition
val value = integerDef.value
val base = integerDef.declaration.base
IntegerValue(value, base)
}
.toTypedArray()
ArrayValue(elements)
}
}
} else {
/* Arrays of elements of any other type */
val elements = fieldDef.definitions
.map { parseField(it) }
.toTypedArray()
ArrayValue(elements)
}
}
is ICompositeDefinition -> {
/*
* Recursively parse the fields, and save the results in a struct value.
*/
val structElements = fieldDef.fieldNames.associateBy({ it }, { parseField(fieldDef.getDefinition(it)) })
StructValue(structElements)
}
is EnumDefinition -> EnumValue(fieldDef.value, fieldDef.integerValue)
is VariantDefinition -> parseField(fieldDef.currentField)
else -> throw IllegalArgumentException("Field type: " + fieldDef.javaClass.toString()
+ " is not supported.")
}
}
| epl-1.0 | c89ecd793bb8bb9f9314cb1afbedc7da | 42.635294 | 189 | 0.53815 | 5.786271 | false | false | false | false |
anthologist/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/adapters/MediaAdapter.kt | 1 | 11940 | package com.simplemobiletools.gallery.adapters
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
import com.simplemobiletools.commons.dialogs.PropertiesDialog
import com.simplemobiletools.commons.dialogs.RenameItemDialog
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.OTG_PATH
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.views.FastScroller
import com.simplemobiletools.commons.views.MyRecyclerView
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.dialogs.DeleteWithRememberDialog
import com.simplemobiletools.gallery.extensions.*
import com.simplemobiletools.gallery.helpers.VIEW_TYPE_LIST
import com.simplemobiletools.gallery.models.Medium
import kotlinx.android.synthetic.main.photo_video_item_grid.view.*
class MediaAdapter(activity: BaseSimpleActivity, var media: MutableList<Medium>, val listener: MediaOperationsListener?, val isAGetIntent: Boolean,
val allowMultiplePicks: Boolean, recyclerView: MyRecyclerView, fastScroller: FastScroller? = null,
itemClick: (Any) -> Unit) : MyRecyclerViewAdapter(activity, recyclerView, fastScroller, itemClick) {
private val INSTANT_LOAD_DURATION = 2000L
private val IMAGE_LOAD_DELAY = 100L
private val config = activity.config
private val isListViewType = config.viewTypeFiles == VIEW_TYPE_LIST
private var skipConfirmationDialog = false
private var visibleItemPaths = ArrayList<String>()
private var loadImageInstantly = false
private var delayHandler = Handler(Looper.getMainLooper())
private var currentMediaHash = media.hashCode()
private val hasOTGConnected = activity.hasOTGConnected()
private var scrollHorizontally = config.scrollHorizontally
private var animateGifs = config.animateGifs
private var cropThumbnails = config.cropThumbnails
private var displayFilenames = config.displayFileNames
init {
setupDragListener(true)
enableInstantLoad()
}
override fun getActionMenuId() = R.menu.cab_media
override fun prepareItemSelection(view: View) {
view.medium_check?.background?.applyColorFilter(primaryColor)
}
override fun markItemSelection(select: Boolean, view: View?) {
view?.medium_check?.beVisibleIf(select)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutType = if (isListViewType) R.layout.photo_video_item_list else R.layout.photo_video_item_grid
return createViewHolder(layoutType, parent)
}
override fun onBindViewHolder(holder: MyRecyclerViewAdapter.ViewHolder, position: Int) {
val medium = media[position]
visibleItemPaths.add(medium.path)
val view = holder.bindView(medium, !allowMultiplePicks) { itemView, layoutPosition ->
setupView(itemView, medium)
}
bindViewHolder(holder, position, view)
}
override fun getItemCount() = media.size
override fun prepareActionMode(menu: Menu) {
menu.apply {
findItem(R.id.cab_rename).isVisible = isOneItemSelected()
findItem(R.id.cab_open_with).isVisible = isOneItemSelected()
findItem(R.id.cab_confirm_selection).isVisible = isAGetIntent && allowMultiplePicks && selectedPositions.size > 0
checkHideBtnVisibility(this)
}
}
override fun actionItemPressed(id: Int) {
if (selectedPositions.isEmpty()) {
return
}
when (id) {
R.id.cab_confirm_selection -> confirmSelection()
R.id.cab_properties -> showProperties()
R.id.cab_rename -> renameFile()
R.id.cab_edit -> editFile()
R.id.cab_hide -> toggleFileVisibility(true)
R.id.cab_unhide -> toggleFileVisibility(false)
R.id.cab_share -> shareMedia()
R.id.cab_copy_to -> copyMoveTo(true)
R.id.cab_move_to -> copyMoveTo(false)
R.id.cab_select_all -> selectAll()
R.id.cab_open_with -> activity.openPath(getCurrentPath(), true)
R.id.cab_set_as -> activity.setAs(getCurrentPath())
R.id.cab_delete -> checkDeleteConfirmation()
}
}
override fun getSelectableItemCount() = media.size
override fun onViewRecycled(holder: ViewHolder) {
super.onViewRecycled(holder)
if (!activity.isActivityDestroyed()) {
val itemView = holder.itemView
visibleItemPaths.remove(itemView?.photo_name?.tag)
Glide.with(activity).clear(itemView?.medium_thumbnail!!)
}
}
private fun checkHideBtnVisibility(menu: Menu) {
var hiddenCnt = 0
var unhiddenCnt = 0
selectedPositions.mapNotNull { media.getOrNull(it) }.forEach {
if (it.name.startsWith('.')) {
hiddenCnt++
} else {
unhiddenCnt++
}
}
menu.findItem(R.id.cab_hide).isVisible = unhiddenCnt > 0
menu.findItem(R.id.cab_unhide).isVisible = hiddenCnt > 0
}
private fun confirmSelection() {
val paths = getSelectedMedia().map { it.path } as ArrayList<String>
listener?.selectedPaths(paths)
}
private fun showProperties() {
if (selectedPositions.size <= 1) {
PropertiesDialog(activity, media[selectedPositions.first()].path, config.shouldShowHidden)
} else {
val paths = ArrayList<String>()
selectedPositions.forEach { paths.add(media[it].path) }
PropertiesDialog(activity, paths, config.shouldShowHidden)
}
}
private fun renameFile() {
RenameItemDialog(activity, getCurrentPath()) {
activity.runOnUiThread {
listener?.refreshItems()
finishActMode()
}
}
}
private fun editFile() {
activity.openEditor(getCurrentPath())
}
private fun toggleFileVisibility(hide: Boolean) {
Thread {
getSelectedMedia().forEach {
activity.toggleFileVisibility(it.path, hide)
}
activity.runOnUiThread {
listener?.refreshItems()
finishActMode()
}
}.start()
}
private fun shareMedia() {
if (selectedPositions.size == 1 && selectedPositions.first() != -1) {
activity.shareMedium(getSelectedMedia()[0])
} else if (selectedPositions.size > 1) {
activity.shareMedia(getSelectedMedia())
}
}
private fun copyMoveTo(isCopyOperation: Boolean) {
val paths = ArrayList<String>()
selectedPositions.forEach { paths.add(media[it].path) }
val fileDirItems = paths.map { FileDirItem(it, it.getFilenameFromPath()) } as ArrayList
activity.tryCopyMoveFilesTo(fileDirItems, isCopyOperation) {
config.tempFolderPath = ""
activity.applicationContext.rescanFolderMedia(it)
activity.applicationContext.rescanFolderMedia(fileDirItems.first().getParentPath())
if (!isCopyOperation) {
listener?.refreshItems()
}
}
}
private fun checkDeleteConfirmation() {
if (skipConfirmationDialog || config.skipDeleteConfirmation) {
deleteFiles()
} else {
askConfirmDelete()
}
}
private fun askConfirmDelete() {
val items = resources.getQuantityString(R.plurals.delete_items, selectedPositions.size, selectedPositions.size)
val question = String.format(resources.getString(R.string.deletion_confirmation), items)
DeleteWithRememberDialog(activity, question) {
skipConfirmationDialog = it
deleteFiles()
}
}
private fun getCurrentPath() = media[selectedPositions.first()].path
private fun deleteFiles() {
if (selectedPositions.isEmpty()) {
return
}
val fileDirItems = ArrayList<FileDirItem>(selectedPositions.size)
val removeMedia = ArrayList<Medium>(selectedPositions.size)
if (media.size <= selectedPositions.first()) {
finishActMode()
return
}
val SAFPath = media[selectedPositions.first()].path
activity.handleSAFDialog(SAFPath) {
selectedPositions.sortedDescending().forEach {
val medium = media[it]
fileDirItems.add(FileDirItem(medium.path, medium.name))
removeMedia.add(medium)
}
media.removeAll(removeMedia)
listener?.deleteFiles(fileDirItems)
removeSelectedItems()
}
}
private fun getSelectedMedia(): List<Medium> {
val selectedMedia = ArrayList<Medium>(selectedPositions.size)
selectedPositions.forEach { selectedMedia.add(media[it]) }
return selectedMedia
}
fun updateMedia(newMedia: ArrayList<Medium>) {
if (newMedia.hashCode() != currentMediaHash) {
currentMediaHash = newMedia.hashCode()
Handler().postDelayed({
media = newMedia.clone() as ArrayList<Medium>
enableInstantLoad()
notifyDataSetChanged()
finishActMode()
}, 100L)
}
}
fun updateDisplayFilenames(displayFilenames: Boolean) {
this.displayFilenames = displayFilenames
enableInstantLoad()
notifyDataSetChanged()
}
fun updateAnimateGifs(animateGifs: Boolean) {
this.animateGifs = animateGifs
notifyDataSetChanged()
}
fun updateCropThumbnails(cropThumbnails: Boolean) {
this.cropThumbnails = cropThumbnails
notifyDataSetChanged()
}
fun updateScrollHorizontally(scrollHorizontally: Boolean) {
this.scrollHorizontally = scrollHorizontally
notifyDataSetChanged()
}
private fun enableInstantLoad() {
loadImageInstantly = true
delayHandler.postDelayed({
loadImageInstantly = false
}, INSTANT_LOAD_DURATION)
}
private fun setupView(view: View, medium: Medium) {
view.apply {
play_outline.beVisibleIf(medium.isVideo())
photo_name.beVisibleIf(displayFilenames || isListViewType)
photo_name.text = medium.name
photo_name.tag = medium.path
var thumbnailPath = medium.path
if (hasOTGConnected && thumbnailPath.startsWith(OTG_PATH)) {
thumbnailPath = thumbnailPath.getOTGPublicPath(context)
}
if (loadImageInstantly) {
activity.loadImage(medium.type, thumbnailPath, medium_thumbnail, scrollHorizontally, animateGifs, cropThumbnails)
} else {
medium_thumbnail.setImageDrawable(null)
medium_thumbnail.isHorizontalScrolling = scrollHorizontally
delayHandler.postDelayed({
val isVisible = visibleItemPaths.contains(medium.path)
if (isVisible) {
activity.loadImage(medium.type, thumbnailPath, medium_thumbnail, scrollHorizontally, animateGifs, cropThumbnails)
}
}, IMAGE_LOAD_DELAY)
}
if (isListViewType) {
photo_name.setTextColor(textColor)
play_outline.applyColorFilter(textColor)
}
}
}
interface MediaOperationsListener {
fun refreshItems()
fun deleteFiles(fileDirItems: ArrayList<FileDirItem>)
fun selectedPaths(paths: ArrayList<String>)
}
}
| apache-2.0 | 76854a5b2068228fea8a51448571d66f | 35.291793 | 147 | 0.646482 | 4.977074 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/completion/RsMacroDefinitionCompletionProvider.kt | 2 | 2749 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.psi.PsiElement
import com.intellij.util.ProcessingContext
import org.rust.lang.RsLanguage
import org.rust.lang.core.RsPsiPattern
import org.rust.lang.core.psi.RsElementTypes.IDENTIFIER
import org.rust.lang.core.psi.RsMacroCall
import org.rust.lang.core.psi.RsMacroDefinition
import org.rust.lang.core.psi.RsPath
import org.rust.lang.core.psi.RsPathExpr
import org.rust.lang.core.psi.ext.RsItemElement
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.lang.core.psi.ext.queryAttributes
import org.rust.lang.core.resolve.collectCompletionVariants
import org.rust.lang.core.resolve.processMacroCallVariants
import org.rust.lang.core.withPrevSiblingSkipping
object RsMacroDefinitionCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext?, result: CompletionResultSet) {
val mod = parameters.position.ancestorStrict<RsMod>()
result.addAllElements(collectCompletionVariants { variantsCollector ->
processMacroCallVariants(parameters.position) { entry ->
val macro = entry.element
val hide = mod != null && macro is RsMacroDefinition && isHidden(macro, mod)
if (!hide) variantsCollector(entry) else false
}
}.asList())
}
val elementPattern: ElementPattern<PsiElement>
get() {
val incompleteItem = psiElement<RsItemElement>().withLastChild(RsPsiPattern.error)
return psiElement(IDENTIFIER)
.andNot(psiElement().withPrevSiblingSkipping(RsPsiPattern.whitespace, incompleteItem))
.withParent(psiElement().with(object : PatternCondition<PsiElement?>("MacroParent") {
override fun accepts(t: PsiElement, context: ProcessingContext?): Boolean {
return t is RsMod || (t is RsPath && t.path == null && t.parent is RsPathExpr) || t is RsMacroCall
}
}))
.withLanguage(RsLanguage)
}
private fun isHidden(macro: RsMacroDefinition, mod: RsMod): Boolean =
macro.queryAttributes.isDocHidden && macro.containingMod != mod
}
| mit | b9ff71494291cad120c9653e8a346774 | 46.396552 | 125 | 0.733358 | 4.667233 | false | false | false | false |
android/trackr | app/src/main/java/com/example/android/trackr/ui/BindingAdapters.kt | 1 | 7674 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.trackr.ui
import android.content.res.ColorStateList
import android.graphics.Rect
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.TouchDelegate
import android.view.View
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.ViewCompat
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat
import androidx.core.widget.TextViewCompat
import androidx.databinding.BindingAdapter
import com.example.android.trackr.R
import com.example.android.trackr.data.Tag
import com.example.android.trackr.data.TaskStatus
import com.example.android.trackr.utils.DateTimeUtils
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import java.time.Clock
import java.time.Instant
import kotlin.math.ceil
/**
* Sets the visibility of this view to either [View.GONE] or [View.VISIBLE].
*/
@BindingAdapter("isGone")
fun View.setIsGone(
isGone: Boolean
) {
visibility = if (isGone) View.GONE else View.VISIBLE
}
/**
* Sets the visibility of this view to either [View.INVISIBLE] or [View.VISIBLE].
*/
@BindingAdapter("isInvisible")
fun View.setIsInvisible(
isInvisible: Boolean
) {
visibility = if (isInvisible) View.INVISIBLE else View.VISIBLE
}
/**
* Sets tags to be shown in this [ChipGroup].
*
* @param tags The list of tags to show.
* @param showAllTags Whether all the tags should be shown or they should be truncated to the number
* of available [Chip] in this [ChipGroup]. This should be `false` when the method should not
* inflate new views, .
*/
@BindingAdapter("tags", "showAllTags")
fun ChipGroup.tags(
tags: List<Tag>?,
showAllTags: Boolean
) {
bind(tags ?: emptyList(), showAllTags)
}
private fun ChipGroup.bind(tags: List<Tag>, showAllTags: Boolean) {
var index = 0
for (i in 0 until childCount) {
(getChildAt(i) as? Chip)?.let { chip ->
if (index >= tags.size) {
chip.visibility = View.GONE
} else {
chip.bind(tags[index])
chip.visibility = View.VISIBLE
}
index++
}
}
if (showAllTags) {
while (index < tags.size) {
val chip = LayoutInflater.from(context)
.inflate(R.layout.tag, this, false) as Chip
chip.bind(tags[index])
addView(chip, index)
index++
}
} else {
(getChildAt(childCount - 1) as? TextView)?.let { label ->
val extraCount = tags.size - index
if (extraCount > 0) {
label.visibility = View.VISIBLE
label.text = resources.getString(R.string.more_tags, extraCount)
} else {
label.visibility = View.GONE
}
}
}
}
private fun Chip.bind(tag: Tag) {
text = tag.label
val color = tag.color
val typedValue = TypedValue()
context.theme.resolveAttribute(color.textColor, typedValue, true)
setTextColor(typedValue.data)
context.theme.resolveAttribute(color.backgroundColor, typedValue, true)
chipBackgroundColor = ColorStateList.valueOf(typedValue.data)
}
@BindingAdapter("dueMessageOrDueDate", "clock")
fun showFormattedDueMessageOrDueDate(view: TextView, instant: Instant?, clock: Clock?) {
view.text = if (instant == null || clock == null) {
""
} else {
DateTimeUtils.durationMessageOrDueDate(view.resources, instant, clock)
}
}
/**
* Binding adapter to format due date of task to a human-readable format. If the due date is not
* close, the [view] is hidden. TODO: rephrase.
*/
@BindingAdapter("dueMessageOrHide", "clock")
fun showFormattedDueMessageOrHide(view: TextView, dueDate: Instant?, clock: Clock) {
val text = if (dueDate == null) {
""
} else {
DateTimeUtils.durationMessageOrDueDate(view.resources, dueDate, clock)
}
if (text.isEmpty()) {
view.visibility = View.GONE
}
}
@BindingAdapter("formattedDate", "clock")
fun formattedGenericDate(view: TextView, instant: Instant?, clock: Clock) {
instant?.let {
view.text = DateTimeUtils.formattedDate(view.resources, it, clock)
}
}
/**
* Replaces the label for the click action associated with [view]. The custom
* label is then passed on to the user of an accessibility service, which can use [label].
* For example, this replaces Talkback's generic "double tap to activate" announcement with the more
* descriptive "double tap to <label>" action label.
*/
@BindingAdapter("clickActionLabel")
fun addClickActionLabel(
view: View,
label: String
) {
ViewCompat.replaceAccessibilityAction(
view,
AccessibilityNodeInfoCompat.AccessibilityActionCompat.ACTION_CLICK,
label,
null
)
}
@BindingAdapter("android:text")
fun TextView.setText(status: TaskStatus?) {
if (status != null) {
setText(status.stringResId)
} else {
text = null
}
}
@BindingAdapter("drawableStartCompat")
fun TextView.setDrawableStartCompat(
@DrawableRes
drawableResId: Int
) {
if (drawableResId == 0) return
val drawable = ResourcesCompat.getDrawable(resources, drawableResId, context.theme) ?: return
val size = resources.getDimensionPixelSize(R.dimen.home_task_star_size)
drawable.setBounds(0, 0, size, size)
TextViewCompat.setCompoundDrawablesRelative(
this, drawable, null, null, null
)
}
/**
* Ensures that the touchable area of [view] equal [minTouchTarget] by expanding the touch area
* of a view beyond its actual view bounds. This adapter can be used expand the touchable area of a
* view when other options (adding padding, for example) may not be available.
*
* Usage:
* <ImageView
* ...
* app:ensureMinTouchArea="@{@dimen/min_touch_target}"
*
* @param view The view whose touch area may be expanded
* @param minTouchTarget The minimum touch area expressed dimen resource
*/
@BindingAdapter("ensureMinTouchArea")
fun addTouchDelegate(view: View, minTouchTarget: Float) {
val parent = view.parent as View
parent.post {
val delegate = Rect()
view.getHitRect(delegate)
val metrics = view.context.resources.displayMetrics
val height = ceil(delegate.height() / metrics.density)
val width = ceil(delegate.width() / metrics.density)
val minTarget = minTouchTarget / metrics.density
var extraSpace = 0
if (height < minTarget) {
extraSpace = (minTarget.toInt() - height.toInt()) / 2
delegate.apply {
top -= extraSpace
bottom += extraSpace
}
}
if (width < minTarget) {
extraSpace = (minTarget.toInt() - width.toInt()) / 2
delegate.apply {
left -= extraSpace
right += extraSpace
}
}
parent.touchDelegate = TouchDelegate(delegate, view)
}
}
| apache-2.0 | 1233ae0739e12423709c48887247b7d6 | 30.580247 | 100 | 0.673443 | 4.150352 | false | false | false | false |
xfournet/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/SetChangesGroupingAction.kt | 1 | 1316 | // 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.vcs.changes.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport
abstract class SetChangesGroupingAction : ToggleAction(), DumbAware {
init {
isEnabledInModalContext = true
}
abstract val groupingKey: String
override fun update(e: AnActionEvent) = super.update(e).also {
e.presentation.isEnabledAndVisible = getGroupingSupport(e)?.isAvailable(groupingKey) ?: false
}
override fun isSelected(e: AnActionEvent) = e.presentation.isEnabledAndVisible && getGroupingSupport(e)?.get(groupingKey) ?: false
override fun setSelected(e: AnActionEvent, state: Boolean) {
getGroupingSupport(e)!![groupingKey] = state
}
protected fun getGroupingSupport(e: AnActionEvent) = e.getData(ChangesGroupingSupport.KEY)
}
class SetDirectoryChangesGroupingAction : SetChangesGroupingAction() {
override val groupingKey get() = "directory"
}
class SetModuleChangesGroupingAction : SetChangesGroupingAction() {
override val groupingKey get() = "module"
} | apache-2.0 | e3109d1e4e2660cfd38dc3f1b8270800 | 37.735294 | 140 | 0.788754 | 4.506849 | false | false | false | false |
SamuelGjk/NHentai-android | app/src/main/kotlin/moe/feng/nhentai/ui/category/CategoryActivity.kt | 1 | 3650 | package moe.feng.nhentai.ui.category
import android.app.ActivityManager
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.databinding.Observable
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import moe.feng.nhentai.R
import moe.feng.nhentai.databinding.ActivityCategoryBinding
import moe.feng.nhentai.model.Tag
import moe.feng.nhentai.ui.common.NHBindingActivity
import moe.feng.nhentai.ui.widget.SwipeBackCoordinatorLayout
import moe.feng.nhentai.util.extension.jsonAsObject
import moe.feng.nhentai.util.extension.objectAsJson
class CategoryActivity: NHBindingActivity<ActivityCategoryBinding>(),
SwipeBackCoordinatorLayout.OnSwipeListener {
override val LAYOUT_RES_ID: Int = R.layout.activity_category
private val pagerAdapter by lazy { CategoryPagerAdapter(supportFragmentManager) }
private val viewModel: CategoryViewModel = CategoryViewModel()
override fun onViewCreated(savedInstanceState: Bundle?) {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityOptions.makeTaskLaunchBehind()
}
binding.vm = viewModel
viewModel.tag.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(p0: Observable?, p1: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setTaskDescription(ActivityManager.TaskDescription(
viewModel.tag.get().type + ":" + viewModel.tag.get().name
))
}
}
})
viewModel.tag.set(intent.getStringExtra(EXTRA_DATA).jsonAsObject())
binding.init()
}
private fun ActivityCategoryBinding.init() {
swipeBackLayout.setOnSwipeListener(this@CategoryActivity)
tabLayout.setupWithViewPager(pager)
pager.adapter = pagerAdapter
}
override fun canSwipeBack(dir: Int): Boolean =
(dir == SwipeBackCoordinatorLayout.UP_DIR
|| (dir == SwipeBackCoordinatorLayout.DOWN_DIR && binding.appBarLayout.y >= 0))
&& (pagerAdapter.getItem(binding.pager.currentItem) as CategoryListFragment)
.canSwipeBack(dir)
override fun onSwipeProcess(percent: Float) {
binding.root.setBackgroundColor(SwipeBackCoordinatorLayout.getBackgroundColor(percent))
}
override fun onSwipeFinish(dir: Int) {
finish()
}
inner class CategoryPagerAdapter(fm: FragmentManager): FragmentPagerAdapter(fm) {
private val latestListFragment by lazy {
CategoryListFragment.newInstance(viewModel.tag.get(), true)
}
private val popularListFragment by lazy {
CategoryListFragment.newInstance(viewModel.tag.get(), false)
}
override fun getItem(position: Int): Fragment = when (position) {
0 -> latestListFragment
1 -> popularListFragment
else -> throw IllegalArgumentException("No more pages")
}
override fun getPageTitle(position: Int): CharSequence? =
resources.getStringArray(R.array.category_tabs_title)[position]
override fun getCount(): Int = 2
}
companion object {
private val TAG = CategoryActivity::class.java.simpleName
private const val EXTRA_DATA = "extra_data"
@JvmStatic fun launch(context: Context, tag: Tag) {
val intent = Intent(context, CategoryActivity::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_NEW_TASK)
} else {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
intent.putExtra(EXTRA_DATA, tag.objectAsJson())
context.startActivity(intent)
}
}
} | gpl-3.0 | c9913c271a2f1095e5e4e7b2901f8e62 | 31.026316 | 94 | 0.772877 | 3.963084 | false | false | false | false |
googlecreativelab/digital-wellbeing-experiments-toolkit | liveWallpaper/data-livewallpaper/app/src/main/java/com/digitalwellbeingexperiments/toolkit/datalivewallpaper/PreferenceKeys.kt | 1 | 948 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.digitalwellbeingexperiments.toolkit.datalivewallpaper
const val DAY_END_MS_PREFERENCE = "DAY_END_MS_PREFERENCE"
const val COUNT_PREFERENCE = "COUNT_PREFERENCE"
const val COUNT_PREFERENCE_DEFAULT_VALUE = 0
const val PREVIEW_COUNT = 1
const val PREV_COUNT_PREFERENCE = "PREV_COUNT_PREFERENCE"
const val PREV_COUNT_PREFERENCE_DEFAULT_VALUE = 0 | apache-2.0 | 0d7d2c555278ae8b3182707fc3d9041d | 32.892857 | 75 | 0.763713 | 3.95 | false | false | false | false |
alashow/music-android | modules/ui-artist/src/main/java/tm/alashow/datmusic/ui/artist/ArtistDetail.kt | 1 | 8286 | /*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.ui.artist
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.hilt.navigation.compose.hiltViewModel
import com.google.accompanist.insets.ui.Scaffold
import kotlin.math.round
import tm.alashow.base.util.extensions.localizedMessage
import tm.alashow.base.util.extensions.localizedTitle
import tm.alashow.common.compose.LocalPlaybackConnection
import tm.alashow.common.compose.rememberFlowWithLifecycle
import tm.alashow.datmusic.domain.entities.Album
import tm.alashow.datmusic.domain.entities.Artist
import tm.alashow.datmusic.domain.entities.Audio
import tm.alashow.datmusic.ui.albums.AlbumColumn
import tm.alashow.datmusic.ui.audios.AudioRow
import tm.alashow.datmusic.ui.components.CoverHeaderDefaults
import tm.alashow.datmusic.ui.components.CoverHeaderRow
import tm.alashow.domain.models.Async
import tm.alashow.domain.models.Fail
import tm.alashow.domain.models.Incomplete
import tm.alashow.domain.models.Loading
import tm.alashow.domain.models.Success
import tm.alashow.navigation.LeafScreen
import tm.alashow.navigation.LocalNavigator
import tm.alashow.navigation.Navigator
import tm.alashow.ui.OffsetNotifyingBox
import tm.alashow.ui.components.CollapsingTopBar
import tm.alashow.ui.components.EmptyErrorBox
import tm.alashow.ui.components.ErrorBox
import tm.alashow.ui.components.fullScreenLoading
import tm.alashow.ui.theme.AppTheme
@Composable
fun ArtistDetail(navigator: Navigator = LocalNavigator.current) {
ArtistDetail(viewModel = hiltViewModel()) {
navigator.back()
}
}
@Composable
private fun ArtistDetail(viewModel: ArtistDetailViewModel, onBackClick: () -> Unit = {}) {
val viewState by rememberFlowWithLifecycle(viewModel.state).collectAsState(initial = ArtistDetailViewState.Empty)
val listState = rememberLazyListState()
val headerHeight = CoverHeaderDefaults.height
val headerOffsetProgress = remember { Animatable(0f) }
OffsetNotifyingBox(headerHeight = headerHeight) { _, progress ->
Scaffold(
topBar = {
LaunchedEffect(progress.value) {
headerOffsetProgress.animateTo(round(progress.value))
}
CollapsingTopBar(
title = stringResource(R.string.artists_detail_title),
collapsed = headerOffsetProgress.value == 0f,
onNavigationClick = onBackClick,
)
}
) { padding ->
ArtistDetailList(viewState, viewModel::refresh, padding, listState)
}
}
}
@Composable
private fun ArtistDetailList(
viewState: ArtistDetailViewState,
onRetry: () -> Unit,
padding: PaddingValues = PaddingValues(),
listState: LazyListState,
) {
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(bottom = padding.calculateTopPadding() + padding.calculateBottomPadding())
) {
val artist = viewState.artist
if (artist != null) {
var scrolledY = 0f
var previousOffset = 0
val parallax = 0.3f
item {
CoverHeaderRow(
title = artist.name,
imageRequest = artist.largePhoto(),
modifier = Modifier.graphicsLayer {
scrolledY += listState.firstVisibleItemScrollOffset - previousOffset
translationY = scrolledY * parallax
previousOffset = listState.firstVisibleItemScrollOffset
}
)
}
val details = viewState.artistDetails
val detailsLoading = details is Incomplete
val (artistAlbums, artistAudios) = artistDetails(details, detailsLoading)
artistDetailsFail(details, onRetry)
artistDetailsEmpty(details, artistAlbums.isEmpty() && artistAudios.isEmpty(), onRetry)
} else {
fullScreenLoading()
}
}
}
private fun LazyListScope.artistDetails(
details: Async<Artist>,
detailsLoading: Boolean
): Pair<List<Album>, List<Audio>> {
val artistAlbums = when (details) {
is Success -> details().albums
is Loading -> (1..5).map { Album() }
else -> emptyList()
}
val artistAudios = when (details) {
is Success -> details().audios
is Loading -> (1..5).map { Audio() }
else -> emptyList()
}
if (artistAlbums.isNotEmpty()) {
item {
Text(
stringResource(R.string.search_albums), style = MaterialTheme.typography.h6.copy(fontWeight = FontWeight.Bold),
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colors.background)
.padding(AppTheme.specs.inputPaddings)
)
}
item {
LazyRow(Modifier.fillMaxWidth()) {
items(artistAlbums) { album ->
val navigator = LocalNavigator.current
AlbumColumn(album, isPlaceholder = detailsLoading, modifier = Modifier.background(MaterialTheme.colors.background)) {
navigator.navigate(LeafScreen.AlbumDetails.buildRoute(it))
}
}
}
}
}
if (artistAudios.isNotEmpty()) {
item {
Text(
stringResource(R.string.search_audios), style = MaterialTheme.typography.h6.copy(fontWeight = FontWeight.Bold),
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colors.background)
.padding(AppTheme.specs.inputPaddings)
)
}
itemsIndexed(artistAudios) { index, audio ->
val playbackConnection = LocalPlaybackConnection.current
AudioRow(
audio = audio,
isPlaceholder = detailsLoading,
modifier = Modifier.background(MaterialTheme.colors.background),
onPlayAudio = {
if (details is Success)
playbackConnection.playArtist(details(), index)
}
)
}
}
return Pair(artistAlbums, artistAudios)
}
private fun LazyListScope.artistDetailsFail(
details: Async<Artist>,
onRetry: () -> Unit,
) {
if (details is Fail) {
item {
ErrorBox(
title = stringResource(details.error.localizedTitle()),
message = stringResource(details.error.localizedMessage()),
onRetryClick = onRetry,
modifier = Modifier.fillParentMaxHeight()
)
}
}
}
private fun LazyListScope.artistDetailsEmpty(
details: Async<Artist>,
detailsEmpty: Boolean,
onRetry: () -> Unit,
) {
if (details is Success && detailsEmpty) {
item {
EmptyErrorBox(
onRetryClick = onRetry,
modifier = Modifier.fillParentMaxHeight()
)
}
}
}
| apache-2.0 | 35210669110cecff284a917f0daa6f82 | 35.183406 | 137 | 0.658098 | 4.943914 | false | false | false | false |
mfietz/fyydlin | src/main/kotlin/FyydClient.kt | 1 | 1362 | package de.mfietz.fyydlin
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter
import io.reactivex.rxjava3.core.Single
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.Date
class FyydClient @JvmOverloads constructor(
client: OkHttpClient = defaultClient,
baseUrl: String = defaultBaseUrl
) {
companion object FyydClientDefaults {
private val defaultClient by lazy { OkHttpClient() }
private val defaultBaseUrl = "https://api.fyyd.de/0.2/"
}
constructor(baseUrl: String) : this(client = defaultClient, baseUrl = baseUrl)
val service: FyydService
init {
val moshi = Moshi.Builder()
.add(Date::class.java, Rfc3339DateJsonAdapter())
.build()
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
service = retrofit.create(FyydService::class.java)
}
fun searchPodcasts(term: String, limit: Int? = null): Single<FyydResponse> {
return service.searchPodcasts(term, limit)
}
}
| apache-2.0 | 0622682acd57208db0f2d0f31cd60ba6 | 30.674419 | 82 | 0.703377 | 4.283019 | false | false | false | false |
CodeIntelligenceTesting/jazzer | sanitizers/src/main/java/com/code_intelligence/jazzer/sanitizers/Deserialization.kt | 1 | 6561 | // Copyright 2021 Code Intelligence GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.code_intelligence.jazzer.sanitizers
import com.code_intelligence.jazzer.api.HookType
import com.code_intelligence.jazzer.api.MethodHook
import com.code_intelligence.jazzer.api.MethodHooks
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.ObjectStreamConstants
import java.lang.invoke.MethodHandle
import java.util.WeakHashMap
/**
* Detects unsafe deserialization that leads to attacker-controlled method calls, in particular to [Object.finalize].
*/
@Suppress("unused_parameter", "unused")
object Deserialization {
private val OBJECT_INPUT_STREAM_HEADER =
ObjectStreamConstants.STREAM_MAGIC.toBytes() + ObjectStreamConstants.STREAM_VERSION.toBytes()
/**
* Used to memoize the [InputStream] used to construct a given [ObjectInputStream].
* [ThreadLocal] is required because the map is not synchronized (and likely cheaper than
* synchronization).
* [WeakHashMap] ensures that we don't prevent the GC from cleaning up [ObjectInputStream] from
* previous fuzzing runs.
*
* Note: The [InputStream] values can all be assumed to be markable, i.e., their
* [InputStream.markSupported] returns true.
*/
private var inputStreamForObjectInputStream: ThreadLocal<WeakHashMap<ObjectInputStream, InputStream>> =
ThreadLocal.withInitial {
WeakHashMap<ObjectInputStream, InputStream>()
}
/**
* A serialized instance of our honeypot class.
*/
private val SERIALIZED_JAZ_ZER_INSTANCE: ByteArray by lazy {
// We can't instantiate jaz.Zer directly, so we instantiate and serialize jaz.Ter and then
// patch the class name.
val baos = ByteArrayOutputStream()
ObjectOutputStream(baos).writeObject(jaz.Ter())
val serializedJazTerInstance = baos.toByteArray()
val posToPatch = serializedJazTerInstance.indexOf("jaz.Ter".toByteArray())
serializedJazTerInstance[posToPatch + "jaz.".length] = 'Z'.code.toByte()
serializedJazTerInstance
}
/**
* Guides the fuzzer towards producing a valid header for an ObjectInputStream.
*/
@MethodHook(
type = HookType.BEFORE,
targetClassName = "java.io.ObjectInputStream",
targetMethod = "<init>",
targetMethodDescriptor = "(Ljava/io/InputStream;)V"
)
@JvmStatic
fun objectInputStreamInitBeforeHook(method: MethodHandle?, alwaysNull: Any?, args: Array<Any?>, hookId: Int) {
val originalInputStream = args[0] as? InputStream ?: return
val fixedInputStream = if (originalInputStream.markSupported())
originalInputStream
else
BufferedInputStream(originalInputStream)
args[0] = fixedInputStream
guideMarkableInputStreamTowardsEquality(fixedInputStream, OBJECT_INPUT_STREAM_HEADER, hookId)
}
/**
* Memoizes the input stream used for creating the [ObjectInputStream] instance.
*/
@MethodHook(
type = HookType.AFTER,
targetClassName = "java.io.ObjectInputStream",
targetMethod = "<init>",
targetMethodDescriptor = "(Ljava/io/InputStream;)V"
)
@JvmStatic
fun objectInputStreamInitAfterHook(
method: MethodHandle?,
objectInputStream: ObjectInputStream?,
args: Array<Any?>,
hookId: Int,
alwaysNull: Any?,
) {
val inputStream = args[0] as? InputStream
check(inputStream?.markSupported() == true) {
"ObjectInputStream#<init> AFTER hook reached with null or non-markable input stream"
}
inputStreamForObjectInputStream.get()[objectInputStream] = inputStream
}
/**
* Guides the fuzzer towards producing a valid serialized instance of our honeypot class.
*/
@MethodHooks(
MethodHook(
type = HookType.BEFORE,
targetClassName = "java.io.ObjectInputStream",
targetMethod = "readObject"
),
MethodHook(
type = HookType.BEFORE,
targetClassName = "java.io.ObjectInputStream",
targetMethod = "readObjectOverride"
),
MethodHook(
type = HookType.BEFORE,
targetClassName = "java.io.ObjectInputStream",
targetMethod = "readUnshared"
),
)
@JvmStatic
fun readObjectBeforeHook(
method: MethodHandle?,
objectInputStream: ObjectInputStream?,
args: Array<Any?>,
hookId: Int,
) {
val inputStream = inputStreamForObjectInputStream.get()[objectInputStream]
if (inputStream?.markSupported() != true) return
guideMarkableInputStreamTowardsEquality(inputStream, SERIALIZED_JAZ_ZER_INSTANCE, hookId)
}
/**
* Calls [Object.finalize] early if the returned object is [jaz.Zer]. A call to finalize is
* guaranteed to happen at some point, but calling it early means that we can accurately report
* the input that lead to its execution.
*/
@MethodHooks(
MethodHook(type = HookType.AFTER, targetClassName = "java.io.ObjectInputStream", targetMethod = "readObject"),
MethodHook(type = HookType.AFTER, targetClassName = "java.io.ObjectInputStream", targetMethod = "readObjectOverride"),
MethodHook(type = HookType.AFTER, targetClassName = "java.io.ObjectInputStream", targetMethod = "readUnshared"),
)
@JvmStatic
fun readObjectAfterHook(
method: MethodHandle?,
objectInputStream: ObjectInputStream?,
args: Array<Any?>,
hookId: Int,
deserializedObject: Any?,
) {
if (deserializedObject?.javaClass?.name == HONEYPOT_CLASS_NAME) {
deserializedObject.javaClass.getDeclaredMethod("finalize").run {
isAccessible = true
invoke(deserializedObject)
}
}
}
}
| apache-2.0 | 143e0213b5979bf98bf27d4efa149a69 | 38.053571 | 126 | 0.67947 | 4.703226 | false | false | false | false |
joan-domingo/Podcasts-RAC1-Android | app/src/main/java/cat/xojan/random1/feature/home/HomeActivity.kt | 1 | 5304 | package cat.xojan.random1.feature.home
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.viewpager.widget.PagerAdapter
import cat.xojan.random1.R
import cat.xojan.random1.domain.model.CrashReporter
import cat.xojan.random1.feature.MediaPlayerBaseActivity
import cat.xojan.random1.injection.HasComponent
import cat.xojan.random1.injection.component.DaggerHomeComponent
import cat.xojan.random1.injection.component.HomeComponent
import cat.xojan.random1.injection.module.HomeModule
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_home.*
import javax.inject.Inject
class HomeActivity : MediaPlayerBaseActivity(), HasComponent<HomeComponent> {
companion object {
private const val PERMISSION_WRITE_EXTERNAL_STORAGE = 20
}
@Inject
internal lateinit var viewModel: HomeViewModel
@Inject
internal lateinit var crashReporter: CrashReporter
private val compositeDisposable = CompositeDisposable()
private var programFragment: ProgramFragment? = null
private var downloadsFragment: DownloadsFragment? = null
override val component: HomeComponent by lazy {
DaggerHomeComponent.builder()
.appComponent(applicationComponent)
.baseActivityModule(activityModule)
.homeModule(HomeModule(this))
.build()
}
private val pageAdapter: HomePagerAdapter by lazy {
HomePagerAdapter(supportFragmentManager, this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
initView(savedInstanceState)
component.inject(this)
}
override fun onMediaControllerConnected() {
programFragment?.onMediaControllerConnected()
downloadsFragment?.onMediaControllerConnected()
}
private fun initView(savedInstanceState: Bundle?) {
setSupportActionBar(toolbar)
if (savedInstanceState == null) {
programFragment = ProgramFragment()
downloadsFragment = DownloadsFragment()
} else {
programFragment = supportFragmentManager.getFragment(savedInstanceState,
ProgramFragment.TAG) as ProgramFragment
downloadsFragment = supportFragmentManager.getFragment(savedInstanceState,
DownloadsFragment.TAG) as DownloadsFragment
}
pageAdapter.addFragment(programFragment!!)
pageAdapter.addFragment(downloadsFragment!!)
viewPager.adapter = pageAdapter as PagerAdapter
tabLayout.setupWithViewPager(viewPager)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.home, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_export_podcasts -> if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestWriteExternalStoragePermission()
} else {
exportPodcasts()
}
}
return super.onOptionsItemSelected(item)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
grantResults: IntArray) {
when (requestCode) {
PERMISSION_WRITE_EXTERNAL_STORAGE -> {
exportPodcasts()
}
}
}
private fun requestWriteExternalStoragePermission() {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
PERMISSION_WRITE_EXTERNAL_STORAGE)
}
override fun onStop() {
super.onStop()
compositeDisposable.clear()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (programFragment != null && programFragment!!.isAdded) {
supportFragmentManager.putFragment(outState, ProgramFragment.TAG, programFragment as
ProgramFragment)
}
if (downloadsFragment != null && downloadsFragment!!.isAdded) {
supportFragmentManager.putFragment(outState, DownloadsFragment.TAG, downloadsFragment
as DownloadsFragment)
}
}
private fun exportPodcasts() {
compositeDisposable.add(viewModel.exportPodcasts()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ notifyUser() },
{ e -> crashReporter.logException(e) }
))
}
private fun notifyUser() {
Toast.makeText(this, getString(R.string.podcasts_exported), Toast.LENGTH_LONG)
.show()
}
} | mit | 7a80ecdd83afeaba09ab09a393e5f403 | 35.335616 | 111 | 0.678356 | 5.496373 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/dialogs/ExportCompleteDialog.kt | 1 | 3286 | /****************************************************************************************
* Copyright (c) 2015 Timothy Rae <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.dialogs
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.core.os.bundleOf
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.listItems
import com.ichi2.anki.R
class ExportCompleteDialog(private val listener: ExportCompleteDialogListener) : AsyncDialogFragment() {
interface ExportCompleteDialogListener {
fun dismissAllDialogFragments()
fun shareFile(path: String) // path of the file to be shared
fun saveExportFile(exportPath: String)
}
private val exportPath
get() = requireArguments().getString("exportPath")!!
fun withArguments(exportPath: String): ExportCompleteDialog {
arguments = (arguments ?: bundleOf(Pair("exportPath", exportPath)))
return this
}
@SuppressLint("CheckResult")
override fun onCreateDialog(savedInstanceState: Bundle?): MaterialDialog {
super.onCreate(savedInstanceState)
val options = listOf(
getString(R.string.export_select_save_app),
getString(R.string.export_select_share_app),
)
return MaterialDialog(requireActivity()).show {
title(text = notificationTitle)
message(text = notificationMessage)
listItems(items = options, waitForPositiveButton = false) { _, index, _ ->
listener.dismissAllDialogFragments()
when (index) {
0 -> listener.saveExportFile(exportPath)
1 -> listener.shareFile(exportPath)
}
}
negativeButton(R.string.dialog_cancel) { listener.dismissAllDialogFragments() }
}
}
override val notificationTitle: String
get() = res().getString(R.string.export_success_title)
override val notificationMessage: String
get() = res().getString(R.string.export_success_message)
}
| gpl-3.0 | 2413f96d4e8c3add15e443d70f5b1858 | 48.787879 | 104 | 0.557821 | 5.626712 | false | false | false | false |
bertilxi/Chilly_Willy_Delivery | mobile/app/src/main/java/dam/isi/frsf/utn/edu/ar/delivery/adapter/ContainersAdapter.kt | 1 | 2041 | package dam.isi.frsf.utn.edu.ar.delivery.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import com.koushikdutta.ion.Ion
import dam.isi.frsf.utn.edu.ar.delivery.R
import dam.isi.frsf.utn.edu.ar.delivery.model.ContainerType
import java.text.NumberFormat
import java.util.*
class ContainersAdapter(context: Context, containers: List<ContainerType>) : ArrayAdapter<ContainerType>(context, R.layout.listview_containers_row, containers) {
var inflater: LayoutInflater = LayoutInflater.from(context)
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var row = convertView
if (row == null) {
row = inflater.inflate(R.layout.listview_containers_row, parent, false)
}
var holder: ContainerHolder? = row!!.tag as ContainerHolder?
if (holder == null) {
holder = ContainerHolder(row)
row.tag = holder
}
Ion.with(holder.containerPic!!)
.fitCenter()
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.load(this.getItem(position)!!.completeImgURL)
holder.containerName!!.text = this.getItem(position)!!.label
holder.containerPrice!!.text = NumberFormat.getCurrencyInstance(Locale.US).format(
this.getItem(position)!!.priceInCents * 0.01
)
return row
}
internal inner class ContainerHolder(row: View) {
var containerPic: ImageView? = null
var containerName: TextView? = null
var containerPrice: TextView? = null
init {
containerPic = row.findViewById(R.id.imageview_addin) as ImageView
containerName = row.findViewById(R.id.containerName) as TextView
containerPrice = row.findViewById(R.id.container_price) as TextView
}
}
} | mit | 58117b8e2f838d811c5ad30da06d708f | 35.464286 | 161 | 0.675649 | 4.278826 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/util/identicon/ColorTransforms.kt | 1 | 1892 | /*
* Copyright (c) 2017. Toshi Inc
*
* 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.toshi.util.identicon
import android.graphics.Color
fun hslToRgb(h: Double, s: Double, l: Double): Int {
val hue = (h % 360.0f) / 360f
val saturation = s / 100f
val lightness = l / 100f
val q = if (lightness < 0.5) lightness * (1 + saturation)
else lightness + saturation - saturation * lightness
val p = 2 * lightness - q
var r = Math.max(0.0, hueToRgb(p, q, hue + 1.0f / 3.0f))
var g = Math.max(0.0, hueToRgb(p, q, hue))
var b = Math.max(0.0, hueToRgb(p, q, hue - 1.0f / 3.0f))
r = Math.min(r, 1.0)
g = Math.min(g, 1.0)
b = Math.min(b, 1.0)
val red = (r * 255).toInt()
val green = (g * 255).toInt()
val blue = (b * 255).toInt()
return Color.rgb(red, green, blue)
}
fun hueToRgb(p: Double, q: Double, h: Double): Double {
var normalisedH = h
if (normalisedH < 0) normalisedH += 1f
if (normalisedH > 1) normalisedH -= 1f
if (6 * normalisedH < 1) {
return p + (q - p) * 6f * normalisedH
}
if (2 * normalisedH < 1) {
return q
}
if (3 * normalisedH < 2) {
return p + (q - p) * 6f * (2.0f / 3.0f - normalisedH)
}
return p
} | gpl-3.0 | 84d3bed31b4494bb65cb2db89e3f7f66 | 31.637931 | 76 | 0.610465 | 3.091503 | false | false | false | false |
ratabb/Hishoot2i | app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/common/widget/CropImageView.kt | 1 | 35654 | package org.illegaller.ratabb.hishoot2i.ui.common.widget
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.PointF
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.os.Parcel
import android.os.Parcelable
import android.os.Parcelable.ClassLoaderCreator
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.SoundEffectConstants
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.content.withStyledAttributes
import androidx.core.graphics.component1
import androidx.core.graphics.component2
import androidx.core.graphics.component3
import androidx.core.graphics.component4
import androidx.core.graphics.drawable.toBitmap
import androidx.core.graphics.minus
import androidx.customview.view.AbsSavedState
import common.ext.displayMetrics
import org.illegaller.ratabb.hishoot2i.R
class CropImageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = R.attr.cropImageViewStyle
) : AppCompatImageView(context, attrs, defStyle) {
private var mViewWidth = 0
private var mViewHeight = 0
private var mScale = 1.0F
private var mImgWidth = 0.0F
private var mImgHeight = 0.0F
private var mIsInitialized = false
private var mLastX = 0F
private var mLastY = 0F
private var mTouchArea = TouchArea.OUT_OF_BOUNDS
private val mMatrix = Matrix()
private val density = context.displayMetrics.density
private val mPaint = Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG)
private val mPaintBitmap = Paint(Paint.FILTER_BITMAP_FLAG)
private val mFrmRect = RectF()
private val mImgRect = RectF()
private val mCenter = PointF()
private var mCropMode: CropMode = CropMode.RATIO_1_1
private var mGuideShowMode: ShowMode = ShowMode.SHOW_ALWAYS
private var mHandleShowMode: ShowMode = ShowMode.SHOW_ALWAYS
private var mMinFrameSize = density * MIN_FRAME_SIZE_IN_DP
private var mHandleSize = density * HANDLE_SIZE_IN_DP
private var mTouchPadding = 0F
private var mShowGuide = true
private var mShowHandle = true
private var mCustomRatio = PointF(1.0F, 1.0F)
private var mFrameStrokeWeight = density * FRAME_STROKE_WEIGHT_IN_DP
private var mGuideStrokeWeight = density * GUIDE_STROKE_WEIGHT_IN_DP
private var mBackgroundColor = TRANSPARENT
private var mOverlayColor = TRANSLUCENT_BLACK
private var mFrameColor = WHITE
private var mHandleColor = WHITE
private var mGuideColor = TRANSLUCENT_WHITE
private var imageBitmap: Bitmap? = null
init {
context.withStyledAttributes(
set = attrs,
attrs = R.styleable.CropImageView,
defStyleAttr = defStyle,
defStyleRes = R.style.AppWidget_CropImageView
) {
setImageDrawable(getDrawable(R.styleable.CropImageView_imgSrc))
mCropMode = CropMode.values().getOrElse(
getInt(R.styleable.CropImageView_cropMode, CropMode.RATIO_1_1.id)
) { CropMode.RATIO_1_1 }
mBackgroundColor = getColor(R.styleable.CropImageView_backgroundColor, TRANSPARENT)
super.setBackgroundColor(mBackgroundColor) //
mOverlayColor = getColor(R.styleable.CropImageView_overlayColor, TRANSLUCENT_BLACK)
mFrameColor = getColor(R.styleable.CropImageView_frameColor, WHITE)
mHandleColor = getColor(R.styleable.CropImageView_handleColor, WHITE)
mGuideColor = getColor(R.styleable.CropImageView_guideColor, TRANSLUCENT_WHITE)
mGuideShowMode = ShowMode.values().getOrElse(
getInt(R.styleable.CropImageView_guideShowMode, ShowMode.SHOW_ALWAYS.id)
) { ShowMode.SHOW_ALWAYS }
setGuideShowMode(mGuideShowMode)
mHandleShowMode = ShowMode.values().getOrElse(
getInt(R.styleable.CropImageView_handleShowMode, ShowMode.SHOW_ALWAYS.id)
) { ShowMode.SHOW_ALWAYS }
setHandleShowMode(mHandleShowMode)
mHandleSize = getDimensionPixelSize(
R.styleable.CropImageView_handleSize,
(HANDLE_SIZE_IN_DP * density).toInt()
).toFloat()
mTouchPadding = getDimensionPixelSize(R.styleable.CropImageView_touchPadding, 0)
.toFloat()
mMinFrameSize = getDimensionPixelSize(
R.styleable.CropImageView_minFrameSize,
(MIN_FRAME_SIZE_IN_DP * density).toInt()
).toFloat()
mFrameStrokeWeight = getDimensionPixelSize(
R.styleable.CropImageView_frameStrokeWeight,
(FRAME_STROKE_WEIGHT_IN_DP * density).toInt()
).toFloat()
mGuideStrokeWeight = getDimensionPixelSize(
R.styleable.CropImageView_guideStrokeWeight,
(GUIDE_STROKE_WEIGHT_IN_DP * density).toInt()
).toFloat()
}
}
public override fun onSaveInstanceState(): Parcelable? =
when (val superState = super.onSaveInstanceState()) {
null -> null // superState
else -> SavedState(superState).apply {
image = imageBitmap
mode = mCropMode
backgroundColor = mBackgroundColor
overlayColor = mOverlayColor
frameColor = mFrameColor
guideShowMode = mGuideShowMode
handleShowMode = mHandleShowMode
showGuide = mShowGuide
showHandle = mShowHandle
handleSize = mHandleSize
touchPadding = mTouchPadding
minFrameSize = mMinFrameSize
customRatio = mCustomRatio
frameStrokeWeight = mFrameStrokeWeight
guideStrokeWeight = mGuideStrokeWeight
handleColor = mHandleColor
guideColor = mGuideColor
}
}
public override fun onRestoreInstanceState(state: Parcelable) {
when (state) {
is SavedState -> {
super.onRestoreInstanceState(state.superState)
mCropMode = state.mode
mBackgroundColor = state.backgroundColor
mOverlayColor = state.overlayColor
mFrameColor = state.frameColor
mGuideShowMode = state.guideShowMode
mHandleShowMode = state.handleShowMode
mShowGuide = state.showGuide
mShowHandle = state.showHandle
mHandleSize = state.handleSize
mTouchPadding = state.touchPadding
mMinFrameSize = state.minFrameSize
mCustomRatio = state.customRatio
mFrameStrokeWeight = state.frameStrokeWeight
mGuideStrokeWeight = state.guideStrokeWeight
mHandleColor = state.handleColor
mGuideColor = state.guideColor
setImageBitmap(state.image)
requestLayout()
}
else -> super.onRestoreInstanceState(state)
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val viewWidth = MeasureSpec.getSize(widthMeasureSpec)
val viewHeight = MeasureSpec.getSize(heightMeasureSpec)
setMeasuredDimension(viewWidth, viewHeight)
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
super.onLayout(changed, l, t, r, b)
mViewWidth = r - l - paddingLeft - paddingRight
mViewHeight = b - t - paddingTop - paddingBottom
if (imageBitmap != null) initLayout(mViewWidth, mViewHeight)
}
public override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (mIsInitialized) {
setMatrix()
imageBitmap?.let { canvas.drawBitmap(it, mMatrix, mPaintBitmap) }
drawEditFrame(canvas)
}
}
private fun drawEditFrame(canvas: Canvas) {
// region Draw Overlay
mPaint.apply {
color = mOverlayColor
style = Paint.Style.FILL
}
canvas.drawRect(mImgRect.left, mImgRect.top, mImgRect.right, mFrmRect.top, mPaint)
canvas.drawRect(mImgRect.left, mFrmRect.bottom, mImgRect.right, mImgRect.bottom, mPaint)
canvas.drawRect(mImgRect.left, mFrmRect.top, mFrmRect.left, mFrmRect.bottom, mPaint)
canvas.drawRect(mFrmRect.right, mFrmRect.top, mImgRect.right, mFrmRect.bottom, mPaint)
// endregion
// region Draw Frame
mPaint.apply {
style = Paint.Style.STROKE
color = mFrameColor
strokeWidth = mFrameStrokeWeight
}
canvas.drawRect(mFrmRect.left, mFrmRect.top, mFrmRect.right, mFrmRect.bottom, mPaint)
// endregion
// region Draw Guide
if (mShowGuide) {
mPaint.apply {
color = mGuideColor
strokeWidth = mGuideStrokeWeight
}
val h1 = mFrmRect.left + (mFrmRect.right - mFrmRect.left) / 3.0f
val h2 = mFrmRect.right - (mFrmRect.right - mFrmRect.left) / 3.0f
val v1 = mFrmRect.top + (mFrmRect.bottom - mFrmRect.top) / 3.0f
val v2 = mFrmRect.bottom - (mFrmRect.bottom - mFrmRect.top) / 3.0f
canvas.drawLine(h1, mFrmRect.top, h1, mFrmRect.bottom, mPaint)
canvas.drawLine(h2, mFrmRect.top, h2, mFrmRect.bottom, mPaint)
canvas.drawLine(mFrmRect.left, v1, mFrmRect.right, v1, mPaint)
canvas.drawLine(mFrmRect.left, v2, mFrmRect.right, v2, mPaint)
}
// endregion
// region Draw Handle
if (mShowHandle) {
mPaint.apply {
style = Paint.Style.FILL
color = mHandleColor
}
canvas.drawCircle(mFrmRect.left, mFrmRect.top, mHandleSize, mPaint)
canvas.drawCircle(mFrmRect.right, mFrmRect.top, mHandleSize, mPaint)
canvas.drawCircle(mFrmRect.left, mFrmRect.bottom, mHandleSize, mPaint)
canvas.drawCircle(mFrmRect.right, mFrmRect.bottom, mHandleSize, mPaint)
}
//endregion
}
private fun setMatrix() {
mMatrix.reset()
mMatrix.setTranslate(mCenter.x - mImgWidth * 0.5F, mCenter.y - mImgHeight * 0.5F)
mMatrix.postScale(mScale, mScale, mCenter.x, mCenter.y)
}
private fun initLayout(viewW: Int, viewH: Int) {
val imgW = imageBitmap!!.width.toFloat()
val imgH = imageBitmap!!.height.toFloat()
mImgWidth = imgW
mImgHeight = imgH
val w = viewW.toFloat()
val h = viewH.toFloat()
val viewRatio = w / h
val imgRatio = imgW / imgH
val scale = when {
imgRatio >= viewRatio -> w / imgW
imgRatio < viewRatio -> h / imgH
else -> 1.0F
}
mCenter.set(paddingLeft + w * 0.5F, paddingTop + h * 0.5F)
mScale = scale
initCropFrame()
adjustRatio()
mIsInitialized = true
}
private fun initCropFrame() {
setMatrix()
val pts = floatArrayOf(0.0F, 0.0F, 0.0F, mImgHeight, mImgWidth, 0.0F, mImgWidth, mImgHeight)
mMatrix.mapPoints(pts)
val l = pts[0]
val t = pts[1]
val r = pts[6]
val b = pts[7]
mFrmRect.set(l, t, r, b)
mImgRect.set(l, t, r, b)
}
override fun performClick(): Boolean {
val handle = super.performClick()
if (!handle) playSoundEffect(SoundEffectConstants.CLICK)
return handle
}
override fun onTouchEvent(event: MotionEvent): Boolean {
performClick()
if (!mIsInitialized) return false
val (eX, eY) = event.run { x to y }
return when (event.action) {
MotionEvent.ACTION_DOWN -> {
onDown(eX, eY)
true
}
MotionEvent.ACTION_MOVE -> {
onMove(eX, eY)
if (mTouchArea != TouchArea.OUT_OF_BOUNDS) {
parent.requestDisallowInterceptTouchEvent(true)
}
true
}
MotionEvent.ACTION_CANCEL -> {
parent.requestDisallowInterceptTouchEvent(false)
onCancel()
true
}
MotionEvent.ACTION_UP -> {
parent.requestDisallowInterceptTouchEvent(false)
onUp()
true
}
else -> false
}
}
private fun onDown(eX: Float, eY: Float) {
invalidate()
mLastX = eX
mLastY = eY
checkTouchArea(eX, eY)
}
private fun onMove(eX: Float, eY: Float) {
val diff = PointF(eX - mLastX, eY - mLastY)
when (mTouchArea) {
TouchArea.CENTER -> moveFrame(diff)
TouchArea.LEFT_TOP -> moveHandleLT(diff)
TouchArea.RIGHT_TOP -> moveHandleRT(diff)
TouchArea.LEFT_BOTTOM -> moveHandleLB(diff)
TouchArea.RIGHT_BOTTOM -> moveHandleRB(diff)
TouchArea.OUT_OF_BOUNDS -> {
}
}
invalidate()
mLastX = eX
mLastY = eY
}
private fun onUp() {
if (mGuideShowMode == ShowMode.SHOW_ON_TOUCH) mShowGuide = false
if (mHandleShowMode == ShowMode.SHOW_ON_TOUCH) mShowHandle = false
mTouchArea = TouchArea.OUT_OF_BOUNDS
invalidate()
}
private fun onCancel() {
mTouchArea = TouchArea.OUT_OF_BOUNDS
invalidate()
}
private fun checkTouchArea(x: Float, y: Float) {
mTouchArea = when {
isInsideCornerLeftTop(x, y) -> TouchArea.LEFT_TOP
isInsideCornerRightTop(x, y) -> TouchArea.RIGHT_TOP
isInsideCornerLeftBottom(x, y) -> TouchArea.LEFT_BOTTOM
isInsideCornerRightBottom(x, y) -> TouchArea.RIGHT_BOTTOM
isInsideFrame(x, y) -> TouchArea.CENTER
else -> TouchArea.OUT_OF_BOUNDS
}
when (mTouchArea) {
TouchArea.LEFT_TOP,
TouchArea.RIGHT_TOP,
TouchArea.LEFT_BOTTOM,
TouchArea.RIGHT_BOTTOM -> {
if (mHandleShowMode == ShowMode.SHOW_ON_TOUCH) mShowHandle = true
if (mGuideShowMode == ShowMode.SHOW_ON_TOUCH) mShowGuide = true
}
TouchArea.CENTER -> {
if (mGuideShowMode == ShowMode.SHOW_ON_TOUCH) mShowGuide = true
}
TouchArea.OUT_OF_BOUNDS -> {
}
}
}
private fun isInsideFrame(x: Float, y: Float): Boolean = mFrmRect.contains(x, y)
private fun isInsideCornerLeftTop(x: Float, y: Float): Boolean {
val dx = x - mFrmRect.left
val dy = y - mFrmRect.top
val d = dx * dx + dy * dy
return sq(mHandleSize + mTouchPadding) >= d
}
private fun isInsideCornerRightTop(x: Float, y: Float): Boolean {
val dx = x - mFrmRect.right
val dy = y - mFrmRect.top
val d = dx * dx + dy * dy
return sq(mHandleSize + mTouchPadding) >= d
}
private fun isInsideCornerLeftBottom(x: Float, y: Float): Boolean {
val dx = x - mFrmRect.left
val dy = y - mFrmRect.bottom
val d = dx * dx + dy * dy
return sq(mHandleSize + mTouchPadding) >= d
}
private fun isInsideCornerRightBottom(x: Float, y: Float): Boolean {
val dx = x - mFrmRect.right
val dy = y - mFrmRect.bottom
val d = dx * dx + dy * dy
return sq(mHandleSize + mTouchPadding) >= d
}
private fun moveFrame(diff: PointF) {
mFrmRect.offset(diff.x, diff.y)
checkMoveBounds()
}
private fun moveHandleLT(diff: PointF) {
if (mCropMode.isRatioFree) {
mFrmRect.left += diff.x
mFrmRect.top += diff.y
if (isWidthTooSmall) {
val offsetX = mMinFrameSize - frameW
mFrmRect.left -= offsetX
}
if (isHeightTooSmall) {
val offsetY = mMinFrameSize - frameH
mFrmRect.top -= offsetY
}
checkScaleBounds()
} else {
val (ratioX, ratioY) = ratio
val dy = diff.x * ratioY / ratioX
mFrmRect.left += diff.x
mFrmRect.top += dy
if (isWidthTooSmall) {
val offsetX = mMinFrameSize - frameW
mFrmRect.left -= offsetX
val offsetY = offsetX * ratioY / ratioX
mFrmRect.top -= offsetY
}
if (isHeightTooSmall) {
val offsetY = mMinFrameSize - frameH
mFrmRect.top -= offsetY
val offsetX = offsetY * ratioX / ratioY
mFrmRect.left -= offsetX
}
var ox: Float
var oy: Float
if (!isInsideHorizontal(mFrmRect.left)) {
ox = mImgRect.left - mFrmRect.left
mFrmRect.left += ox
oy = ox * ratioY / ratioX
mFrmRect.top += oy
}
if (!isInsideVertical(mFrmRect.top)) {
oy = mImgRect.top - mFrmRect.top
mFrmRect.top += oy
ox = oy * ratioX / ratioY
mFrmRect.left += ox
}
}
}
private fun moveHandleRT(diff: PointF) {
if (mCropMode.isRatioFree) {
mFrmRect.right += diff.x
mFrmRect.top += diff.y
if (isWidthTooSmall) {
val offsetX = mMinFrameSize - frameW
mFrmRect.right += offsetX
}
if (isHeightTooSmall) {
val offsetY = mMinFrameSize - frameH
mFrmRect.top -= offsetY
}
checkScaleBounds()
} else {
val (ratioX, ratioY) = ratio
val dy = diff.x * ratioY / ratioX
mFrmRect.right += diff.x
mFrmRect.top -= dy
if (isWidthTooSmall) {
val offsetX = mMinFrameSize - frameW
mFrmRect.right += offsetX
val offsetY = offsetX * ratioY / ratioX
mFrmRect.top -= offsetY
}
if (isHeightTooSmall) {
val offsetY = mMinFrameSize - frameH
mFrmRect.top -= offsetY
val offsetX = offsetY * ratioX / ratioY
mFrmRect.right += offsetX
}
var ox: Float
var oy: Float
if (!isInsideHorizontal(mFrmRect.right)) {
ox = mFrmRect.right - mImgRect.right
mFrmRect.right -= ox
oy = ox * ratioY / ratioX
mFrmRect.top += oy
}
if (!isInsideVertical(mFrmRect.top)) {
oy = mImgRect.top - mFrmRect.top
mFrmRect.top += oy
ox = oy * ratioX / ratioY
mFrmRect.right -= ox
}
}
}
private fun moveHandleLB(diff: PointF) {
if (mCropMode.isRatioFree) {
mFrmRect.left += diff.x
mFrmRect.bottom += diff.y
if (isWidthTooSmall) {
val offsetX = mMinFrameSize - frameW
mFrmRect.left -= offsetX
}
if (isHeightTooSmall) {
val offsetY = mMinFrameSize - frameH
mFrmRect.bottom += offsetY
}
checkScaleBounds()
} else {
val (ratioX, ratioY) = ratio
val dy = diff.x * ratioY / ratioX
mFrmRect.left += diff.x
mFrmRect.bottom -= dy
if (isWidthTooSmall) {
val offsetX = mMinFrameSize - frameW
mFrmRect.left -= offsetX
val offsetY = offsetX * ratioY / ratioX
mFrmRect.bottom += offsetY
}
if (isHeightTooSmall) {
val offsetY = mMinFrameSize - frameH
mFrmRect.bottom += offsetY
val offsetX = offsetY * ratioX / ratioY
mFrmRect.left -= offsetX
}
var ox: Float
var oy: Float
if (!isInsideHorizontal(mFrmRect.left)) {
ox = mImgRect.left - mFrmRect.left
mFrmRect.left += ox
oy = ox * ratioY / ratioX
mFrmRect.bottom -= oy
}
if (!isInsideVertical(mFrmRect.bottom)) {
oy = mFrmRect.bottom - mImgRect.bottom
mFrmRect.bottom -= oy
ox = oy * ratioX / ratioY
mFrmRect.left += ox
}
}
}
private fun moveHandleRB(diff: PointF) {
if (mCropMode.isRatioFree) {
mFrmRect.right += diff.x
mFrmRect.bottom += diff.y
if (isWidthTooSmall) {
val offsetX = mMinFrameSize - frameW
mFrmRect.right += offsetX
}
if (isHeightTooSmall) {
val offsetY = mMinFrameSize - frameH
mFrmRect.bottom += offsetY
}
checkScaleBounds()
} else {
val (ratioX, ratioY) = ratio
val dy = diff.x * ratioY / ratioX
mFrmRect.right += diff.x
mFrmRect.bottom += dy
if (isWidthTooSmall) {
val offsetX = mMinFrameSize - frameW
mFrmRect.right += offsetX
val offsetY = offsetX * ratioY / ratioX
mFrmRect.bottom += offsetY
}
if (isHeightTooSmall) {
val offsetY = mMinFrameSize - frameH
mFrmRect.bottom += offsetY
val offsetX = offsetY * ratioX / ratioY
mFrmRect.right += offsetX
}
var ox: Float
var oy: Float
if (!isInsideHorizontal(mFrmRect.right)) {
ox = mFrmRect.right - mImgRect.right
mFrmRect.right -= ox
oy = ox * ratioY / ratioX
mFrmRect.bottom -= oy
}
if (!isInsideVertical(mFrmRect.bottom)) {
oy = mFrmRect.bottom - mImgRect.bottom
mFrmRect.bottom -= oy
ox = oy * ratioX / ratioY
mFrmRect.right -= ox
}
}
}
private fun checkScaleBounds() {
val diff = (mFrmRect - mImgRect).bounds
if (diff.left < 0) mFrmRect.left -= diff.left
if (diff.right > 0) mFrmRect.right -= diff.right
if (diff.top < 0) mFrmRect.top -= diff.top
if (diff.bottom > 0) mFrmRect.bottom -= diff.bottom
}
private fun checkMoveBounds() {
var diff = mFrmRect.left - mImgRect.left
if (diff < 0) {
mFrmRect.left -= diff
mFrmRect.right -= diff
}
diff = mFrmRect.right - mImgRect.right
if (diff > 0) {
mFrmRect.left -= diff
mFrmRect.right -= diff
}
diff = mFrmRect.top - mImgRect.top
if (diff < 0) {
mFrmRect.top -= diff
mFrmRect.bottom -= diff
}
diff = mFrmRect.bottom - mImgRect.bottom
if (diff > 0) {
mFrmRect.top -= diff
mFrmRect.bottom -= diff
}
}
private fun isInsideHorizontal(x: Float): Boolean = mImgRect.run { x in left..right }
private fun isInsideVertical(y: Float): Boolean = mImgRect.run { y in top..bottom }
private val isWidthTooSmall: Boolean
get() = frameW < mMinFrameSize
private val isHeightTooSmall: Boolean
get() = frameH < mMinFrameSize
private fun adjustRatio() {
val imgW = mImgRect.right - mImgRect.left
val imgH = mImgRect.bottom - mImgRect.top
val frameW = if (mCropMode.isRatioFree) imgW else ratio.x
val frameH = if (mCropMode.isRatioFree) imgH else ratio.y
val imgRatio = imgW / imgH
val frameRatio = frameW / frameH
var (l, t, r, b) = mImgRect
if (frameRatio >= imgRatio) {
val hy = (mImgRect.top + mImgRect.bottom) * 0.5F
val hh = imgW / frameRatio * 0.5F
t = hy - hh
b = hy + hh
} else if (frameRatio < imgRatio) {
val hx = (mImgRect.left + mImgRect.right) * 0.5F
val hw = imgH * frameRatio * 0.5F
l = hx - hw
r = hx + hw
}
val w = r - l
val h = b - t
mFrmRect.set(l + w / 8, t + h / 8, r - w / 8, b - h / 8)
invalidate()
}
private val ratio: PointF
get() = when (mCropMode) {
CropMode.RATIO_FIT_IMAGE -> PointF(mImgWidth, mImgHeight)
CropMode.RATIO_4_3 -> PointF(4.0F, 3.0F)
CropMode.RATIO_3_4 -> PointF(3.0f, 4.0F)
CropMode.RATIO_16_9 -> PointF(16.0F, 9.0F)
CropMode.RATIO_9_16 -> PointF(9.0F, 16.0F)
CropMode.RATIO_FREE, CropMode.RATIO_1_1 -> PointF(1.0F, 1.0F)
CropMode.RATIO_CUSTOM -> mCustomRatio
}
private fun sq(value: Float): Float = value * value
/* NOTE: Coil use this */
override fun setImageDrawable(drawable: Drawable?) {
if (drawable != null) setImageBitmap(drawable.toBitmap())
}
/**
* Set source image bitmap
*
* @param bitmap src image bitmap
*/
override fun setImageBitmap(bitmap: Bitmap?) {
if (bitmap == null) return
mIsInitialized = false
if (imageBitmap != null && imageBitmap != bitmap) {
imageBitmap = null
}
imageBitmap = bitmap
if (imageBitmap != null) {
mImgWidth = imageBitmap!!.width.toFloat()
mImgHeight = imageBitmap!!.height.toFloat()
initLayout(mViewWidth, mViewHeight)
}
}
/**
* Set source image resource id
*
* @param resId source image resource id
*/
override fun setImageResource(resId: Int) {
if (resId != 0) {
val bitmap = BitmapFactory.decodeResource(resources, resId)
setImageBitmap(bitmap)
}
}
/**
* Get cropped image bitmap
*
* @return cropped image bitmap
* @throws [IllegalStateException] if [imageBitmap] is ```null```
*/
val croppedBitmap: Bitmap
get() {
val l = (mFrmRect.left / mScale).toInt()
val t = (mFrmRect.top / mScale).toInt()
val r = (mFrmRect.right / mScale).toInt()
val b = (mFrmRect.bottom / mScale).toInt()
val x = l - (mImgRect.left / mScale).toInt()
val y = t - (mImgRect.top / mScale).toInt()
imageBitmap?.let {
return Bitmap.createBitmap(it, x, y, r - l, b - t, null, false)
}
throw IllegalStateException("imageBitmap == null, did you forget to setImage?")
}
/**
* Set crop mode
*
* @param mode crop mode
*/
@Suppress("unused")
fun setCropMode(mode: CropMode) {
if (mode == CropMode.RATIO_CUSTOM) {
setCustomRatio(1, 1)
} else {
mCropMode = mode
adjustRatio()
}
}
/**
* Set custom aspect ratio to crop frame
*
* @param ratioX aspect ratio X
* @param ratioY aspect ratio Y
*/
fun setCustomRatio(ratioX: Int, ratioY: Int) {
if (ratioX == 0 || ratioY == 0) return
mCropMode = CropMode.RATIO_CUSTOM
mCustomRatio = PointF(ratioX.toFloat(), ratioY.toFloat())
adjustRatio()
}
/**
* Set image overlay color
*
* @param overlayColor color resId or color int(ex. 0xFFFFFFFF)
*/
@Suppress("unused")
fun setOverlayColor(overlayColor: Int) {
mOverlayColor = overlayColor
invalidate()
}
/**
* Set crop frame color
*
* @param frameColor color resId or color int(ex. 0xFFFFFFFF)
*/
@Suppress("unused")
fun setFrameColor(frameColor: Int) {
mFrameColor = frameColor
invalidate()
}
/**
* Set handle color
*
* @param handleColor color resId or color int(ex. 0xFFFFFFFF)
*/
@Suppress("unused")
fun setHandleColor(handleColor: Int) {
mHandleColor = handleColor
invalidate()
}
/**
* Set guide color
*
* @param guideColor color resId or color int(ex. 0xFFFFFFFF)
*/
@Suppress("unused")
fun setGuideColor(guideColor: Int) {
mGuideColor = guideColor
invalidate()
}
/**
* Set view background color
*
* @param bgColor color resId or color int(ex. 0xFFFFFFFF)
*/
override fun setBackgroundColor(bgColor: Int) {
mBackgroundColor = bgColor
super.setBackgroundColor(mBackgroundColor)
invalidate()
}
/**
* Set crop frame minimum size in density-independent pixels.
*
* @param minDp crop frame minimum size in density-independent pixels
*/
@Suppress("unused")
fun setMinFrameSizeInDp(minDp: Int) {
mMinFrameSize = minDp * density
}
/**
* Set handle radius in density-independent pixels.
*
* @param handleDp handle radius in density-independent pixels
*/
@Suppress("unused")
fun setHandleSizeInDp(handleDp: Int) {
mHandleSize = (handleDp * density)
}
/**
* Set crop frame handle touch padding(touch area) in density-independent pixels.
*
*
* handle touch area : a circle of radius R.(R = handle size + touch padding)
*
* @param paddingDp crop frame handle touch padding(touch area) in density-independent pixels
*/
@Suppress("unused")
fun setTouchPaddingInDp(paddingDp: Int) {
mTouchPadding = (paddingDp * density)
}
/**
* Set guideline show mode.
* (SHOW_ALWAYS/NOT_SHOW/SHOW_ON_TOUCH)
*
* @param mode guideline show mode
*/
@Suppress("MemberVisibilityCanBePrivate")
fun setGuideShowMode(mode: ShowMode) {
mGuideShowMode = mode
mShowGuide = mode == ShowMode.SHOW_ALWAYS
invalidate()
}
/**
* Set handle show mode.
* (SHOW_ALWAYS/NOT_SHOW/SHOW_ON_TOUCH)
*
* @param mode handle show mode
*/
@Suppress("MemberVisibilityCanBePrivate")
fun setHandleShowMode(mode: ShowMode) {
mHandleShowMode = mode
mShowHandle = mode == ShowMode.SHOW_ALWAYS
invalidate()
}
/**
* Set frame stroke weight in density-independent pixels.
*
* @param weightDp frame stroke weight in density-independent pixels.
*/
@Suppress("unused")
fun setFrameStrokeWeightInDp(weightDp: Int) {
mFrameStrokeWeight = weightDp * density
invalidate()
}
/**
* Set guideline stroke weight in density-independent pixels.
*
* @param weightDp guideline stroke weight in density-independent pixels.
*/
@Suppress("unused")
fun setGuideStrokeWeightInDp(weightDp: Int) {
mGuideStrokeWeight = weightDp * density
invalidate()
}
private val frameW: Float
get() = mFrmRect.right - mFrmRect.left
private val frameH: Float
get() = mFrmRect.bottom - mFrmRect.top
private enum class TouchArea {
OUT_OF_BOUNDS, CENTER, LEFT_TOP, RIGHT_TOP, LEFT_BOTTOM, RIGHT_BOTTOM
}
enum class CropMode(val id: Int) {
RATIO_FIT_IMAGE(0),
RATIO_4_3(1),
RATIO_3_4(2),
RATIO_1_1(3),
RATIO_16_9(4),
RATIO_9_16(5),
RATIO_FREE(6),
RATIO_CUSTOM(7);
val isRatioFree: Boolean
get() = this == RATIO_FREE
}
enum class ShowMode(val id: Int) { SHOW_ALWAYS(1), SHOW_ON_TOUCH(2), NOT_SHOW(3); }
// Save/Restore support ////////////////////////////////////////////////////////////////////////
internal class SavedState : AbsSavedState {
var image: Bitmap? = null
var mode: CropMode = CropMode.RATIO_1_1
var backgroundColor = 0
var overlayColor = 0
var frameColor = 0
var guideShowMode: ShowMode = ShowMode.SHOW_ALWAYS
var handleShowMode: ShowMode = ShowMode.SHOW_ALWAYS
var showGuide = false
var showHandle = false
var handleSize = 0F
var touchPadding = 0F
var minFrameSize = 0F
var customRatio = PointF(1.0F, 1.0F)
var frameStrokeWeight = 0F
var guideStrokeWeight = 0F
var handleColor = 0
var guideColor = 0
constructor(superState: Parcelable) : super(superState)
constructor(source: Parcel, loader: ClassLoader?) : super(source, loader) {
image = source.readParcelable(Bitmap::class.java.classLoader)
mode = source.readSerializable() as CropMode
backgroundColor = source.readInt()
overlayColor = source.readInt()
frameColor = source.readInt()
guideShowMode = source.readSerializable() as ShowMode
handleShowMode = source.readSerializable() as ShowMode
showGuide = source.readInt() != 0
showHandle = source.readInt() != 0
handleSize = source.readFloat()
touchPadding = source.readFloat()
minFrameSize = source.readFloat()
source.readParcelable<PointF>(PointF::class.java.classLoader)?.let { customRatio = it }
frameStrokeWeight = source.readFloat()
guideStrokeWeight = source.readFloat()
handleColor = source.readInt()
guideColor = source.readInt()
}
override fun writeToParcel(out: Parcel, flag: Int) {
super.writeToParcel(out, flag)
out.writeParcelable(image, flag)
out.writeSerializable(mode)
out.writeInt(backgroundColor)
out.writeInt(overlayColor)
out.writeInt(frameColor)
out.writeSerializable(guideShowMode)
out.writeSerializable(handleShowMode)
out.writeInt(if (showGuide) 1 else 0)
out.writeInt(if (showHandle) 1 else 0)
out.writeFloat(handleSize)
out.writeFloat(touchPadding)
out.writeFloat(minFrameSize)
out.writeParcelable(customRatio, flag)
out.writeFloat(frameStrokeWeight)
out.writeFloat(guideStrokeWeight)
out.writeInt(handleColor)
out.writeInt(guideColor)
}
companion object {
@Suppress("unused")
@JvmField
val CREATOR = object : ClassLoaderCreator<SavedState> {
override fun createFromParcel(source: Parcel, loader: ClassLoader?): SavedState =
SavedState(source, loader)
override fun createFromParcel(parcel: Parcel): SavedState = SavedState(parcel, null)
override fun newArray(size: Int): Array<SavedState> = newArray(size)
}
}
}
companion object {
private const val HANDLE_SIZE_IN_DP = 16
private const val MIN_FRAME_SIZE_IN_DP = 50
private const val FRAME_STROKE_WEIGHT_IN_DP = 1
private const val GUIDE_STROKE_WEIGHT_IN_DP = 1
private const val TRANSPARENT = Color.TRANSPARENT
private const val TRANSLUCENT_WHITE = -0x44000001
private const val WHITE = -0x1
private const val TRANSLUCENT_BLACK = -0x45000000
}
}
| apache-2.0 | d2df18765a764dd04b3d32c90bb95fd5 | 34.30099 | 100 | 0.571493 | 4.171034 | false | false | false | false |
davidwhitman/changelogs | app/src/main/java/com/thunderclouddev/changelogs/auth/GsfId.kt | 1 | 1714 | /*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.changelogs.auth
import android.content.Context
import android.net.Uri
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
/**
* Gets the device's ID for Google Services Framework.
* REQUIRES com.google.android.providers.gsf.permission.READ_GSERVICES
* Credit to http://stackoverflow.com/questions/22743087/gsf-id-key-google-service-framework-id-as-android-device-unique-identifier
*/
@Singleton
class GsfId @Inject constructor(private val context: Context) {
val get: String? by lazy {
val uri = Uri.parse("content://com.google.android.gsf.gservices")
val params = arrayOf("android_id")
val c = context.contentResolver.query(uri, null, null, params, null)
if (c != null) {
if (c.moveToFirst() && c.columnCount >= 2) {
try {
val androidId = java.lang.Long.toHexString(c.getString(1).toLong())
Timber.v("AndroidId=$androidId")
androidId
} catch (e: Exception) {
Timber.e(e, "Failed to get androidId!")
null
} finally {
c.close()
}
} else {
Timber.e(RuntimeException(), "Failed to get androidId, cursor was null!")
null
}
} else {
Timber.w(RuntimeException(), "Failed to get androidId!")
null
}
}
} | gpl-3.0 | 7abb4149fdff25c96132dcd3eeea6968 | 33.3 | 131 | 0.595099 | 4.090692 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/test/kotlin/org/wfanet/measurement/duchy/service/internal/computations/ComputationsServiceTest.kt | 1 | 18257 | // Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.duchy.service.internal.computations
import com.google.common.truth.extensions.proto.ProtoTruth.assertThat
import com.google.protobuf.kotlin.toByteStringUtf8
import java.time.Clock
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.wfanet.measurement.common.grpc.testing.GrpcTestServerRule
import org.wfanet.measurement.common.grpc.testing.mockService
import org.wfanet.measurement.common.testing.verifyProtoArgument
import org.wfanet.measurement.duchy.db.computation.testing.FakeComputationsDatabase
import org.wfanet.measurement.duchy.toProtocolStage
import org.wfanet.measurement.internal.duchy.AdvanceComputationStageRequest
import org.wfanet.measurement.internal.duchy.ClaimWorkRequest
import org.wfanet.measurement.internal.duchy.ComputationDetails
import org.wfanet.measurement.internal.duchy.ComputationTypeEnum.ComputationType
import org.wfanet.measurement.internal.duchy.FinishComputationRequest
import org.wfanet.measurement.internal.duchy.GetComputationIdsRequest
import org.wfanet.measurement.internal.duchy.GetComputationIdsResponse
import org.wfanet.measurement.internal.duchy.RecordOutputBlobPathRequest
import org.wfanet.measurement.internal.duchy.RecordRequisitionBlobPathRequest
import org.wfanet.measurement.internal.duchy.RequisitionDetails
import org.wfanet.measurement.internal.duchy.UpdateComputationDetailsRequest
import org.wfanet.measurement.internal.duchy.computationStage
import org.wfanet.measurement.internal.duchy.computationToken
import org.wfanet.measurement.internal.duchy.config.LiquidLegionsV2SetupConfig.RoleInComputation
import org.wfanet.measurement.internal.duchy.copy
import org.wfanet.measurement.internal.duchy.externalRequisitionKey
import org.wfanet.measurement.internal.duchy.protocol.LiquidLegionsSketchAggregationV2
import org.wfanet.measurement.internal.duchy.requisitionEntry
import org.wfanet.measurement.internal.duchy.requisitionMetadata
import org.wfanet.measurement.internal.duchy.updateComputationDetailsRequest
import org.wfanet.measurement.system.v1alpha.ComputationLogEntriesGrpcKt.ComputationLogEntriesCoroutineImplBase
import org.wfanet.measurement.system.v1alpha.ComputationLogEntriesGrpcKt.ComputationLogEntriesCoroutineStub
import org.wfanet.measurement.system.v1alpha.CreateComputationLogEntryRequest
private val AGGREGATOR_COMPUTATION_DETAILS =
ComputationDetails.newBuilder()
.apply { liquidLegionsV2Builder.apply { role = RoleInComputation.AGGREGATOR } }
.build()
private val NON_AGGREGATOR_COMPUTATION_DETAILS =
ComputationDetails.newBuilder()
.apply { liquidLegionsV2Builder.apply { role = RoleInComputation.NON_AGGREGATOR } }
.build()
private const val DUCHY_NAME = "BOHEMIA"
@RunWith(JUnit4::class)
@ExperimentalCoroutinesApi
class ComputationsServiceTest {
private val fakeDatabase = FakeComputationsDatabase()
private val mockComputationLogEntriesService: ComputationLogEntriesCoroutineImplBase =
mockService()
@get:Rule
val grpcTestServerRule = GrpcTestServerRule { addService(mockComputationLogEntriesService) }
private val fakeService: ComputationsService by lazy {
ComputationsService(
fakeDatabase,
ComputationLogEntriesCoroutineStub(grpcTestServerRule.channel),
DUCHY_NAME,
Clock.systemUTC()
)
}
@Test
fun `get computation token`() = runBlocking {
val id = "1234"
val requisitionMetadata = requisitionMetadata {
externalKey = externalRequisitionKey {
externalRequisitionId = "1234"
requisitionFingerprint = "A requisition fingerprint".toByteStringUtf8()
}
}
fakeDatabase.addComputation(
globalId = id,
stage = LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.toProtocolStage(),
computationDetails = AGGREGATOR_COMPUTATION_DETAILS,
requisitions = listOf(requisitionMetadata)
)
val expectedToken = computationToken {
localComputationId = 1234
globalComputationId = "1234"
computationStage = computationStage {
liquidLegionsSketchAggregationV2 =
LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE
}
computationDetails = AGGREGATOR_COMPUTATION_DETAILS
requisitions += requisitionMetadata
}
assertThat(fakeService.getComputationToken(id.toGetTokenRequest()))
.isEqualTo(expectedToken.toGetComputationTokenResponse())
assertThat(fakeService.getComputationToken(id.toGetTokenRequest()))
.isEqualTo(expectedToken.toGetComputationTokenResponse())
}
@Test
fun `update computationDetails successfully`() = runBlocking {
val id = "1234"
fakeDatabase.addComputation(
globalId = id,
stage = LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.toProtocolStage(),
computationDetails = AGGREGATOR_COMPUTATION_DETAILS
)
val tokenAtStart = fakeService.getComputationToken(id.toGetTokenRequest()).token
val newComputationDetails =
AGGREGATOR_COMPUTATION_DETAILS.toBuilder()
.apply { liquidLegionsV2Builder.reachEstimateBuilder.reach = 123 }
.build()
val request =
UpdateComputationDetailsRequest.newBuilder()
.apply {
token = tokenAtStart
details = newComputationDetails
}
.build()
assertThat(fakeService.updateComputationDetails(request))
.isEqualTo(
tokenAtStart
.toBuilder()
.apply {
version = 1
computationDetails = newComputationDetails
}
.build()
.toUpdateComputationDetailsResponse()
)
}
@Test
fun `update computations details and requisition details`() = runBlocking {
val id = "1234"
val requisition1Key = externalRequisitionKey {
externalRequisitionId = "1234"
requisitionFingerprint = "A requisition fingerprint".toByteStringUtf8()
}
val requisition2Key = externalRequisitionKey {
externalRequisitionId = "5678"
requisitionFingerprint = "Another requisition fingerprint".toByteStringUtf8()
}
fakeDatabase.addComputation(
globalId = id,
stage = LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.toProtocolStage(),
computationDetails = AGGREGATOR_COMPUTATION_DETAILS,
requisitions =
listOf(
requisitionMetadata { externalKey = requisition1Key },
requisitionMetadata { externalKey = requisition2Key }
)
)
val tokenAtStart = fakeService.getComputationToken(id.toGetTokenRequest()).token
val newComputationDetails =
AGGREGATOR_COMPUTATION_DETAILS.toBuilder()
.apply { liquidLegionsV2Builder.reachEstimateBuilder.reach = 123 }
.build()
val requisitionDetails1 =
RequisitionDetails.newBuilder().apply { externalFulfillingDuchyId = "duchy-1" }.build()
val requisitionDetails2 =
RequisitionDetails.newBuilder().apply { externalFulfillingDuchyId = "duchy-2" }.build()
val request = updateComputationDetailsRequest {
token = tokenAtStart
details = newComputationDetails
requisitions += requisitionEntry {
key = requisition1Key
value = requisitionDetails1
}
requisitions += requisitionEntry {
key = requisition2Key
value = requisitionDetails2
}
}
assertThat(fakeService.updateComputationDetails(request))
.isEqualTo(
tokenAtStart
.copy {
version = 1
computationDetails = newComputationDetails
requisitions.clear()
requisitions += requisitionMetadata {
externalKey = requisition1Key
details = requisitionDetails1
}
requisitions += requisitionMetadata {
externalKey = requisition2Key
details = requisitionDetails2
}
}
.toUpdateComputationDetailsResponse()
)
}
@Test
fun `end failed computation`() = runBlocking {
val id = "1234"
fakeDatabase.addComputation(
globalId = id,
stage = LiquidLegionsSketchAggregationV2.Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage(),
computationDetails = AGGREGATOR_COMPUTATION_DETAILS
)
val tokenAtStart = fakeService.getComputationToken(id.toGetTokenRequest()).token
val request =
FinishComputationRequest.newBuilder()
.apply {
token = tokenAtStart
endingComputationStage = LiquidLegionsSketchAggregationV2.Stage.COMPLETE.toProtocolStage()
reason = ComputationDetails.CompletedReason.FAILED
}
.build()
assertThat(fakeService.finishComputation(request))
.isEqualTo(
tokenAtStart
.toBuilder()
.clearStageSpecificDetails()
.apply {
version = 1
computationStage = LiquidLegionsSketchAggregationV2.Stage.COMPLETE.toProtocolStage()
computationDetailsBuilder.endingState = ComputationDetails.CompletedReason.FAILED
}
.build()
.toFinishComputationResponse()
)
verifyProtoArgument(
mockComputationLogEntriesService,
ComputationLogEntriesCoroutineImplBase::createComputationLogEntry
)
.comparingExpectedFieldsOnly()
.isEqualTo(
CreateComputationLogEntryRequest.newBuilder()
.apply {
parent = "computations/$id/participants/$DUCHY_NAME"
computationLogEntryBuilder.apply {
logMessage = "Computation $id at stage COMPLETE, attempt 0"
stageAttemptBuilder.apply {
stage = LiquidLegionsSketchAggregationV2.Stage.COMPLETE.number
stageName = LiquidLegionsSketchAggregationV2.Stage.COMPLETE.name
attemptNumber = 0
}
}
}
.build()
)
}
@Test
fun `write reference to output blob and advance stage`() = runBlocking {
val id = "67890"
fakeDatabase.addComputation(
globalId = id,
stage = LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.toProtocolStage(),
computationDetails = NON_AGGREGATOR_COMPUTATION_DETAILS,
blobs =
listOf(
newInputBlobMetadata(id = 0L, key = "an_input_blob"),
newEmptyOutputBlobMetadata(id = 1L)
)
)
val tokenAtStart = fakeService.getComputationToken(id.toGetTokenRequest()).token
val tokenAfterRecordingBlob =
fakeService
.recordOutputBlobPath(
RecordOutputBlobPathRequest.newBuilder()
.apply {
token = tokenAtStart
outputBlobId = 1L
blobPath = "the_writen_output_blob"
}
.build()
)
.token
val request =
AdvanceComputationStageRequest.newBuilder()
.apply {
token = tokenAfterRecordingBlob
nextComputationStage =
LiquidLegionsSketchAggregationV2.Stage.WAIT_EXECUTION_PHASE_TWO_INPUTS.toProtocolStage()
addAllInputBlobs(listOf("inputs_to_new_stage"))
outputBlobs = 1
afterTransition = AdvanceComputationStageRequest.AfterTransition.DO_NOT_ADD_TO_QUEUE
}
.build()
assertThat(fakeService.advanceComputationStage(request))
.isEqualTo(
tokenAtStart
.toBuilder()
.clearBlobs()
.clearStageSpecificDetails()
.apply {
version = 2
attempt = 1
computationStage =
LiquidLegionsSketchAggregationV2.Stage.WAIT_EXECUTION_PHASE_TWO_INPUTS
.toProtocolStage()
addBlobs(newInputBlobMetadata(id = 0L, key = "inputs_to_new_stage"))
addBlobs(newEmptyOutputBlobMetadata(id = 1L))
}
.build()
.toAdvanceComputationStageResponse()
)
verifyProtoArgument(
mockComputationLogEntriesService,
ComputationLogEntriesCoroutineImplBase::createComputationLogEntry
)
.comparingExpectedFieldsOnly()
.isEqualTo(
CreateComputationLogEntryRequest.newBuilder()
.apply {
parent = "computations/$id/participants/$DUCHY_NAME"
computationLogEntryBuilder.apply {
logMessage = "Computation $id at stage WAIT_EXECUTION_PHASE_TWO_INPUTS, attempt 0"
stageAttemptBuilder.apply {
stage =
LiquidLegionsSketchAggregationV2.Stage.WAIT_EXECUTION_PHASE_TWO_INPUTS.number
stageName =
LiquidLegionsSketchAggregationV2.Stage.WAIT_EXECUTION_PHASE_TWO_INPUTS.name
attemptNumber = 0
}
}
}
.build()
)
}
@Test
fun `get computation ids`() = runBlocking {
val blindId = "67890"
val completedId = "12341"
val decryptId = "4342242"
fakeDatabase.addComputation(
globalId = blindId,
stage = LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.toProtocolStage(),
computationDetails = NON_AGGREGATOR_COMPUTATION_DETAILS
)
fakeDatabase.addComputation(
completedId,
LiquidLegionsSketchAggregationV2.Stage.COMPLETE.toProtocolStage(),
NON_AGGREGATOR_COMPUTATION_DETAILS,
listOf()
)
fakeDatabase.addComputation(
decryptId,
LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_THREE.toProtocolStage(),
NON_AGGREGATOR_COMPUTATION_DETAILS,
listOf()
)
val getIdsInMillStagesRequest =
GetComputationIdsRequest.newBuilder()
.apply {
addAllStages(
setOf(
LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.toProtocolStage(),
LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_THREE.toProtocolStage()
)
)
}
.build()
assertThat(fakeService.getComputationIds(getIdsInMillStagesRequest))
.isEqualTo(
GetComputationIdsResponse.newBuilder()
.apply { addAllGlobalIds(setOf(blindId, decryptId)) }
.build()
)
}
@Test
fun `claim task`() = runBlocking {
val unclaimed = "12345678"
val claimed = "23456789"
fakeDatabase.addComputation(
globalId = unclaimed,
stage = LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.toProtocolStage(),
computationDetails = NON_AGGREGATOR_COMPUTATION_DETAILS
)
val unclaimedAtStart = fakeService.getComputationToken(unclaimed.toGetTokenRequest()).token
fakeDatabase.addComputation(
claimed,
LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.toProtocolStage(),
NON_AGGREGATOR_COMPUTATION_DETAILS,
listOf()
)
fakeDatabase.claimedComputationIds.add(claimed)
val claimedAtStart = fakeService.getComputationToken(claimed.toGetTokenRequest()).token
val owner = "TheOwner"
val request =
ClaimWorkRequest.newBuilder()
.setComputationType(ComputationType.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2)
.setOwner(owner)
.build()
assertThat(fakeService.claimWork(request))
.isEqualTo(
unclaimedAtStart.toBuilder().setVersion(1).setAttempt(1).build().toClaimWorkResponse()
)
assertThat(fakeService.claimWork(request)).isEqualToDefaultInstance()
assertThat(fakeService.getComputationToken(claimed.toGetTokenRequest()))
.isEqualTo(claimedAtStart.toGetComputationTokenResponse())
verifyProtoArgument(
mockComputationLogEntriesService,
ComputationLogEntriesCoroutineImplBase::createComputationLogEntry
)
.comparingExpectedFieldsOnly()
.isEqualTo(
CreateComputationLogEntryRequest.newBuilder()
.apply {
parent = "computations/$unclaimed/participants/$DUCHY_NAME"
computationLogEntryBuilder.apply {
logMessage = "Computation $unclaimed at stage EXECUTION_PHASE_ONE, attempt 1"
stageAttemptBuilder.apply {
stage = LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.number
stageName = LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.name
attemptNumber = 1
}
}
}
.build()
)
}
@Test
fun `record requisition blob path`() = runBlocking {
val id = "1234"
val requisitionKey = externalRequisitionKey {
externalRequisitionId = "1234"
requisitionFingerprint = "A requisition fingerprint".toByteStringUtf8()
}
fakeDatabase.addComputation(
globalId = id,
stage = LiquidLegionsSketchAggregationV2.Stage.EXECUTION_PHASE_ONE.toProtocolStage(),
computationDetails = AGGREGATOR_COMPUTATION_DETAILS,
requisitions = listOf(requisitionMetadata { externalKey = requisitionKey })
)
val tokenAtStart = fakeService.getComputationToken(id.toGetTokenRequest()).token
val request =
RecordRequisitionBlobPathRequest.newBuilder()
.apply {
token = tokenAtStart
key = requisitionKey
blobPath = "this is a new path"
}
.build()
assertThat(fakeService.recordRequisitionBlobPath(request))
.isEqualTo(
tokenAtStart
.toBuilder()
.clearRequisitions()
.apply {
version = 1
addRequisitionsBuilder().apply {
externalKey = requisitionKey
path = "this is a new path"
}
}
.build()
.toRecordRequisitionBlobPathResponse()
)
}
}
| apache-2.0 | 5be9ba28f2c897200a26ef32bbc50408 | 36.259184 | 111 | 0.697869 | 4.932991 | false | false | false | false |
tajobe/innovate2017 | savingmyinfo-bot/src/main/kotlin/info/savingmy/innovate/hackbot/commands/Command.kt | 1 | 2940 | package info.savingmy.innovate.hackbot.commands
import info.savingmy.innovate.hackbot.SavingInfoBot
import info.savingmy.innovate.hackbot.build
import org.symphonyoss.symphony.clients.model.SymMessage
import org.symphonyoss.symphony.clients.model.SymStream
enum class Command(val description: String, val requireDirect: Boolean, vararg val command: String)
{
BOOKMARK("Bookmark messages", false, "bookmark", "bm", "save")
{
override fun onCommand(from: Long, stream: SymStream, bot: SavingInfoBot, vararg args: String)
{
if (args.size == 1)
bot.client.messagesClient.sendMessage(stream, SymMessage().build(
SymMessage.Format.MESSAGEML,
"<div data-format=\"PresentationML\" data-version=\"2.0\">" + (bot.messagesPerStream[stream.streamId]
?.joinToString("<br />") { it.message }
?: "No messages found in stream") + "</div>"))
}
},
LIST("List your bookmarks", true, "list", "listbookmarks", "ls", "bookmarks")
{
override fun onCommand(from: Long, stream: SymStream, bot: SavingInfoBot, vararg args: String)
{
}
},
TAG("Manage tags applied to a bookmark", true, "tag", "update")
{
override fun onCommand(from: Long, stream: SymStream, bot: SavingInfoBot, vararg args: String)
{
}
},
DELETE("Delete a saved bookmark", true, "delete", "rm", "remove")
{
override fun onCommand(from: Long, stream: SymStream, bot: SavingInfoBot, vararg args: String)
{
}
},
HELP("Help information about the bot", true, "help", "h", "commands")
{
override fun onCommand(from: Long, stream: SymStream, bot: SavingInfoBot, vararg args: String)
{
val messageToSend = SymMessage().build(
SymMessage.Format.MESSAGEML,
"<div data-format=\"PresentationML\" data-version=\"2.0\"><b>Available Commands</b>:<br /><ul>${Command.values()
.joinToString(separator = "") { "<li><b>${it.command.first()}${if (it.requireDirect) " (Direct only)" else ""}</b>: ${it.description}</li>" }}</ul></div>")
bot.client.messagesClient.sendMessage(stream, messageToSend)
}
};
abstract fun onCommand(from: Long, stream: SymStream, bot: SavingInfoBot, vararg args: String)
companion object
{
fun getCommand(command: String): Command
{
return values().singleOrNull { it.command.contains(command) } ?: HELP
}
fun runCommand(message: SymMessage, bot: SavingInfoBot)
{
val commandParms = message.messageText.substring(1).split(" ", ignoreCase = true).toTypedArray()
commandParms.firstOrNull()?.let { getCommand(it).onCommand(message.fromUserId, message.stream, bot, *commandParms) }
}
}
}
| apache-2.0 | 39d452666dc6e13cd5ccd2c0f3dc6801 | 42.235294 | 183 | 0.608163 | 3.98374 | false | false | false | false |
debop/debop4k | debop4k-data-exposed/src/test/kotlin/debop4k/data/exposed/examples/shared/DDLTests.kt | 1 | 9995 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package debop4k.data.exposed.examples.shared
import com.fasterxml.uuid.Generators
import debop4k.core.utils.toUtf8String
import debop4k.data.exposed.dao.UUIDIdTable
import debop4k.data.exposed.examples.DatabaseTestBase
import debop4k.data.exposed.examples.TestDB.*
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.exposed.dao.*
import org.jetbrains.exposed.sql.*
import org.junit.Test
import javax.sql.rowset.serial.SerialBlob
class DDLTests : DatabaseTestBase() {
@Test
fun tableExists01() {
val TestTable = object : Table() {
val id = integer("id").primaryKey().autoIncrement()
val name = varchar("name", length = 42)
}
withTables {
assertThat(TestTable.exists()).isFalse()
}
}
@Test
fun tableExists02() {
val TestTable = object : Table() {
val id = integer("id").primaryKey().autoIncrement()
val name = varchar("name", length = 42)
}
withTables(TestTable) {
assertThat(TestTable.exists()).isTrue()
}
}
@Test
fun testCreateMissingTablesAndColumns01() {
val TestTable = object : Table("test") {
val id = integer("id").primaryKey().autoIncrement()
val name = varchar("name", length = 42)
}
withDb {
SchemaUtils.createMissingTablesAndColumns(TestTable)
try {
assertThat(TestTable.exists()).isTrue()
} finally {
SchemaUtils.drop(TestTable)
}
}
}
@Test fun testCreateMissingTablesAndColumns02() {
val TestTable = object : UUIDIdTable("Users2") {
val name = varchar("name", 255)
val email = varchar("email", 255).uniqueIndex()
}
withDb(H2) {
SchemaUtils.createMissingTablesAndColumns(TestTable)
try {
assertEquals(true, TestTable.exists())
SchemaUtils.createMissingTablesAndColumns(TestTable)
} finally {
SchemaUtils.drop(TestTable)
}
}
}
@Test
fun unnamedTableWithQuotesSQL() {
val TestTable = object : Table() {
val id = integer("id").primaryKey()
val name = varchar("name", length = 42)
}
withTables(TestTable) {
val q = db.identityQuoteString
assertThat(TestTable.ddl.single())
.isEqualToIgnoringCase("CREATE TABLE IF NOT EXISTS ${q}unnamedTableWithQuotesSQL\$TestTable$1$q (id INT PRIMARY KEY, name VARCHAR(42) NOT NULL)")
}
}
@Test
fun namedEmptyTableWithoutQuotesSQL() {
val TestTable = object : Table("test_named_table") {
}
// MySQL, PostgreSQL, SQLITE ๋ ํ๋ ์ด์์ ์ปฌ๋ผ์ด ์์ด์ผ ํฉ๋๋ค.
withTables(excludeSettings = listOf(MYSQL, POSTGRESQL), tables = TestTable) {
assertThat(TestTable.ddl.single()).isEqualToIgnoringCase("CREATE TABLE IF NOT EXISTS test_named_table")
}
}
@Test
fun tableWithDifferentColumnTypesSQL01() {
val TestTable = object : Table("test_table_with_different_column_types") {
val id = integer("id").autoIncrement()
val name = varchar("name", 42).primaryKey()
val age = integer("age").nullable()
// not applicable in H2 database
// val testCollate = varchar("testCollate", 2, "ascii_general_ci")
}
withTables(excludeSettings = listOf(MYSQL), tables = TestTable) {
assertThat(TestTable.ddl.single())
.containsIgnoringCase("CREATE TABLE IF NOT EXISTS test_table_with_different_column_types (id ")
.containsIgnoringCase("name VARCHAR(42) PRIMARY KEY, age INT NULL")
}
}
@Test fun tableWithDifferentColumnTypesSQL02() {
val TestTable = object : Table("test_table_with_different_column_types") {
val id = integer("id").primaryKey()
val name = varchar("name", 42).primaryKey()
val age = integer("age").nullable()
}
withTables(excludeSettings = listOf(MYSQL), tables = TestTable) {
assertThat(TestTable.ddl.single())
.isEqualToIgnoringCase("CREATE TABLE IF NOT EXISTS test_table_with_different_column_types (id INT, name VARCHAR(42), age INT NULL, CONSTRAINT pk_test_table_with_different_column_types PRIMARY KEY (id, name))")
}
}
@Test
fun testDefaults01() {
val TestTable = object : Table("t") {
val s = varchar("s", 100).default("test")
val l = long("l").default(42L)
}
withTables(TestTable) {
assertThat(TestTable.ddl.single())
.isEqualToIgnoringCase("CREATE TABLE IF NOT EXISTS t (s VARCHAR(100) NOT NULL DEFAULT 'test', l BIGINT NOT NULL DEFAULT 42)")
}
}
@Test fun testIndices01() {
val t = object : Table("t1") {
val id = integer("id").primaryKey()
val name = varchar("name", 255).index()
}
withTables(t) {
val alter = SchemaUtils.createIndex(t.indices[0].first, t.indices[0].second)
assertThat(alter.single().toUpperCase()).startsWith("CREATE INDEX t1_name ON t1 (name)".toUpperCase())
}
}
@Test fun testIndices02() {
val t = object : Table("t2") {
val id = integer("id").primaryKey()
val lvalue = integer("lvalue")
val rvalue = integer("rvalue")
val name = varchar("name", 255).index()
init {
index(false, lvalue, rvalue)
}
}
withTables(t) {
val a1 = SchemaUtils.createIndex(t.indices[0].first, t.indices[0].second)
assertEquals("CREATE INDEX t2_name ON t2 (name)".toUpperCase(),
a1.single().toUpperCase())
val a2 = SchemaUtils.createIndex(t.indices[1].first, t.indices[1].second)
assertEquals("CREATE INDEX t2_lvalue_rvalue ON t2 (lvalue, rvalue)".toUpperCase(),
a2.single().toUpperCase())
}
}
@Test fun testIndices03() {
val t = object : Table("t1") {
val id = integer("id").primaryKey()
val name = varchar("name", 255).uniqueIndex()
}
withTables(t) {
val alter = SchemaUtils.createIndex(t.indices[0].first, t.indices[0].second)
assertEquals("CREATE UNIQUE INDEX t1_name_unique ON t1 (name)".toUpperCase(),
alter.single().toUpperCase())
}
}
@Test fun testBlob() {
val t = object : Table("t1") {
val id = integer("id").autoIncrement().primaryKey()
val b = blob("blob")
}
withTables(t) {
val bytes = "Hello there!".toByteArray()
// val blob = if (currentDialect.dataTypeProvider.blobAsStream) {
// SerialBlob(bytes)
// } else jdbcUrl.createBlob().apply {
// setBytes(1, bytes)
// }
val blob = try {
SerialBlob(bytes)
} catch(e: Throwable) {
connection.createBlob().apply { setBytes(1, bytes) }
}
val id = t.insert {
it[t.b] = blob
} get (t.id)
val readOn = t.select { t.id eq id }.first()[t.b]
val text = readOn.binaryStream.reader().readText()
assertEquals("Hello there!", text)
}
}
@Test fun testBinary() {
val t = object : Table() {
val binary = binary("bytes", 10)
}
withTables(t) {
t.insert { it[t.binary] = "Hello!".toByteArray() }
val bytes = t.selectAll().single()[t.binary]
assertThat(bytes.toUtf8String()).isEqualTo("Hello!")
}
}
@Test fun addAutoPrimaryKey() {
val tableName = "Foo"
val initialTable = object : Table(tableName) {
val bar = text("bar")
}
val t = IntIdTable(tableName)
withDb(H2) {
SchemaUtils.createMissingTablesAndColumns(initialTable)
assertThat(t.id.ddl.first().toUpperCase()).startsWith("ALTER TABLE ${tableName.toUpperCase()}")
// assertEquals("ALTER TABLE $tableName ADD COLUMN id ${t.id.columnType.sqlType()}", t.id.ddl.first())
// assertEquals("ALTER TABLE $tableName ADD CONSTRAINT pk_$tableName PRIMARY KEY (id)", t.id.ddl[1])
//assertEquals(1, currentDialect.tableColumns(t)[t]!!.size)
SchemaUtils.createMissingTablesAndColumns(t)
//assertEquals(2, currentDialect.tableColumns(t)[t]!!.size)
}
}
private abstract class EntityTable(name: String = "") : IdTable<String>(name) {
override val id: Column<EntityID<String>> = varchar("id", 64)
.clientDefault { Generators.timeBasedGenerator().generate().toString() }
.primaryKey()
.entityId()
}
@Test fun complexTest01() {
val User = object : UUIDIdTable() {
val name = varchar("name", 255)
val email = varchar("email", 255)
}
val Repository = object : UUIDIdTable() {
val name = varchar("name", 255)
}
val UserToRepo = object : UUIDIdTable() {
val user = reference("user", User)
val repo = reference("repo", Repository)
}
withTables(User, Repository, UserToRepo) {
User.insert {
it[User.name] = "foo"
it[User.email] = "bar"
}
val userID = User.selectAll().single()[User.id]
Repository.insert {
it[Repository.name] = "foo"
}
val repo = Repository.selectAll().single()[Repository.id]
UserToRepo.insert {
it[UserToRepo.user] = userID
it[UserToRepo.repo] = repo
}
assertEquals(1, UserToRepo.selectAll().count())
UserToRepo.insert {
it[UserToRepo.user] = userID
it[UserToRepo.repo] = repo
}
assertEquals(2, UserToRepo.selectAll().count())
}
}
}
//private fun String.inProperCase(): String = TransactionManager.currentOrNull()?.let { tm ->
// (currentDialect as? VendorDialect)?.run {
// [email protected]
// }
//} ?: this | apache-2.0 | 6d088efa121d98dd5efc68dfc5ddf14a | 29.759259 | 219 | 0.634822 | 3.843039 | false | true | false | false |
Mauin/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/LateinitUsage.kt | 1 | 2886 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.api.AnnotationExcluder
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.SplitPattern
import io.gitlab.arturbosch.detekt.api.LazyRegex
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.containingClass
/**
* Turn on this rule to flag usages of the lateinit modifier.
*
* Using lateinit for property initialization can be error prone and the actual initialization is not
* guaranteed. Try using constructor injection or delegation to initialize properties.
*
* <noncompliant>
* class Foo {
* @JvmField lateinit var i1: Int
* @JvmField @SinceKotlin("1.0.0") lateinit var i2: Int
* }
* </noncompliant>
*
* @configuration excludeAnnotatedProperties - Allows you to provide a list of annotations that disable
* this check. (default: "")
* @configuration ignoreOnClassesPattern - Allows you to disable the rule for a list of classes (default: "")
*
* @author Marvin Ramin
* @author Niklas Baudy
* @author schalkms
*/
class LateinitUsage(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(javaClass.simpleName,
Severity.Defect,
"Usage of lateinit detected. Using lateinit for property initialization " +
"is error prone, try using constructor injection or delegation.",
Debt.TWENTY_MINS)
private val excludeAnnotatedProperties = SplitPattern(valueOrDefault(EXCLUDE_ANNOTATED_PROPERTIES, ""))
private val ignoreOnClassesPattern by LazyRegex(key = IGNORE_ON_CLASSES_PATTERN, default = "")
private var properties = mutableListOf<KtProperty>()
override fun visitProperty(property: KtProperty) {
if (isLateinitProperty(property)) {
properties.add(property)
}
}
override fun visit(root: KtFile) {
properties = mutableListOf()
super.visit(root)
val annotationExcluder = AnnotationExcluder(root, excludeAnnotatedProperties)
properties.filterNot { annotationExcluder.shouldExclude(it.annotationEntries) }
.filterNot { it.containingClass()?.name?.matches(ignoreOnClassesPattern) == true }
.forEach {
report(CodeSmell(issue, Entity.from(it), "Usages of latinit should be avoided."))
}
}
private fun isLateinitProperty(property: KtProperty) =
property.modifierList?.hasModifier(KtTokens.LATEINIT_KEYWORD) == true
companion object {
const val EXCLUDE_ANNOTATED_PROPERTIES = "excludeAnnotatedProperties"
const val IGNORE_ON_CLASSES_PATTERN = "ignoreOnClassesPattern"
}
}
| apache-2.0 | 3050f763352ed20f589c819e28e977df | 35.075 | 109 | 0.773042 | 3.991701 | false | true | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/cropfarm/VanillaReedsSeed.kt | 1 | 1356 | package net.ndrei.teslapoweredthingies.machines.cropfarm
import net.minecraft.block.state.IBlockState
import net.minecraft.init.Blocks
import net.minecraft.init.Items
import net.minecraft.item.ItemStack
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* Created by CF on 2017-07-07.
*/
class VanillaReedsSeed(override val seeds: ItemStack)
: ISeedWrapper {
override fun canPlantHere(world: World, pos: BlockPos): Boolean {
if (!world.isAirBlock(pos)) return false
val under = world.getBlockState(pos.down()).block
return (under === Blocks.SAND || under === Blocks.DIRT || under === Blocks.GRASS) &&
(world.getBlockState(pos.north().down()).block === Blocks.WATER
|| world.getBlockState(pos.east().down()).block === Blocks.WATER
|| world.getBlockState(pos.south().down()).block === Blocks.WATER
|| world.getBlockState(pos.west().down()).block === Blocks.WATER)
}
override fun plant(world: World, pos: BlockPos): IBlockState {
return if (this.canPlantHere(world, pos)) {
Blocks.REEDS.getPlant(world, pos)
}
else
Blocks.AIR.defaultState
}
companion object {
fun isSeed(stack: ItemStack)
= !stack.isEmpty && (stack.item === Items.REEDS)
}
} | mit | 5a1bc74ae9448fd3c2f29084702b6b30 | 33.794872 | 92 | 0.643068 | 4.072072 | false | false | false | false |
jingcai-wei/android-news | app/src/main/java/com/sky/android/news/ui/main/news/NetNewsViewModel.kt | 1 | 3753 | /*
* Copyright (c) 2021 The sky Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sky.android.news.ui.main.news
import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.sky.android.news.data.model.LineItemModel
import com.sky.android.news.data.source.INewsSource
import com.sky.android.news.ext.doFailure
import com.sky.android.news.ext.doSuccess
import com.sky.android.news.ui.base.NewsViewModel
import com.sky.android.news.ui.helper.PageHelper
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import javax.inject.Inject
/**
* Created by sky on 2021-01-25.
*/
@HiltViewModel
class NetNewsViewModel @Inject constructor(
application: Application,
private val source: INewsSource
) : NewsViewModel(application) {
private val mLoading = MutableLiveData<Boolean>()
val loading: LiveData<Boolean> = mLoading
private val mFailure = MutableLiveData<String>()
val failure: LiveData<String> = mFailure
private val mLineItem = MutableLiveData<List<LineItemModel>>()
val lineItem: LiveData<List<LineItemModel>> = mLineItem
private val mPageHelper = PageHelper<LineItemModel>()
var tid: String = ""
fun loadHeadLine() {
// ๅ ่ฝฝ
loadHeadLine(0, false)
}
fun loadMoreHeadLine() {
if (!mPageHelper.isNextPage()) {
mLoading.value = false
return
}
// ๅ ่ฝฝๆดๅคๆฐๆฎ
loadHeadLine(mPageHelper.getCurPage() + 1, true)
}
private fun loadHeadLine(curPage: Int, loadMore: Boolean) {
launchOnUI {
val start = curPage * PageHelper.PAGE_SIZE
source.getHeadLine(tid, start, start + PageHelper.PAGE_SIZE)
.map {
it.doSuccess {
// ๅ ้คไธ่ฟ่ก็ๆฐ้ป
var tempList = ArrayList<LineItemModel>()
it.lineItems.forEach {
// ๆทปๅ ๆๆ็ๆฐ้ป
if (TextUtils.isEmpty(it.template)) tempList.add(it)
}
it.lineItems = tempList
}
}
.onStart { mLoading.value = true }
.onCompletion { mLoading.value = false }
.collect {
it.doFailure {
mFailure.value = "ๅ ่ฝฝๅ่กจไฟกๆฏๅคฑ่ดฅ"
}.doSuccess {
if (loadMore) {
// ่ฟฝๅ ๆฐๆฎ
mPageHelper.appendData(it.lineItems)
} else {
// ่ฎพ็ฝฎๆฐๆฎ
mPageHelper.setData(100, it.lineItems)
}
mLineItem.value = mPageHelper.getData()
}
}
}
}
} | apache-2.0 | d1ff0a4bc336953c11f0b919ff1520c1 | 31.245614 | 84 | 0.579864 | 4.657795 | false | false | false | false |
Devexperts/usages | server/src/main/kotlin/com/devexperts/usages/server/indexer/MavenIndexer.kt | 1 | 2968 | /**
* Copyright (C) 2017 Devexperts LLC
*
* 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/gpl-3.0.html>.
*/
package com.devexperts.usages.server.indexer
import com.devexperts.logging.Logging
import com.devexperts.usages.api.Artifact
import com.devexperts.usages.server.artifacts.ArtifactManager
import com.devexperts.usages.server.config.RepositorySetting
import com.devexperts.usages.server.config.RepositoryType
import com.devexperts.usages.server.config.Settings
import com.devexperts.util.TimePeriod
import java.io.File
abstract class MavenIndexer(
repositorySetting: RepositorySetting, // delay between repository indexing runs.
val supportedArtifactTypes: List<String>,
val id: String = repositorySetting.id,
val url: String = repositorySetting.url,
val user: String? = repositorySetting.user,
val password: String? = repositorySetting.password,
val scanDelay: TimePeriod = repositorySetting.scanTimePeriod
) {
protected abstract val log: Logging
/**
* Scans maven repository structure,
* stores information about artifacts and their transitive dependencies.
*/
abstract fun scan()
/**
* Downloads the specified artifact from the repository.
* Returns null if the artifact has not been downloaded.
*/
abstract fun downloadArtifact(artifact: Artifact): File?
/**
* Store information about the artifact into the [ArtifactManager]
*/
protected fun storeArtifactInfo(artifact: Artifact, dependencies: List<Artifact>, packages: Collection<String>) {
ArtifactManager.storeArtifactInfo(id, artifact, dependencies, packages)
log.trace("Store information for $artifact, dependencies=$dependencies, packages=$packages")
}
}
/**
* Creates [MavenIndexer] according to this settings
*/
fun RepositorySetting.createIndexer(supportedArtifactTypes: List<String>): MavenIndexer {
when (type) {
RepositoryType.NEXUS -> return NexusMavenIndexer(
repositorySetting = this,
supportedArtifacts = supportedArtifactTypes
)
else -> throw IllegalStateException("Unsupported repository type: $type")
}
}
/**
* Creates a list of [MavenIndexer]s according to this settings
*/
fun Settings.createIndexers() = repositorySettings.map {
it.createIndexer(artifactTypes)
} | gpl-3.0 | 6babf378fd4db1a7deb0b7259fd33bef | 36.1125 | 117 | 0.731806 | 4.615863 | false | false | false | false |
anninpavel/PhitoLed-Android | app/src/main/kotlin/ru/annin/phitoled/presentation/ui/decoration/SectionAdapter.kt | 1 | 2999 | package ru.annin.phitoled.presentation.ui.decoration
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import java.util.*
/**
* https://gist.github.com/jpshelley/4e0d4aa16c20e91a6c01e48d278b4282
*
* @author Pavel Annin.
*/
/**
* A section to use in Recycler Adapter's.
* It holds a sectioned position for use in determining the offset of the adapter items.
*/
data class AdapterSection(var firstPosition: Int, var title: String, var sectionedPosition: Int = 0)
/**
* An adapter that allows a RecyclerView to contain sections or subheaders
* much like the material docs describe.
* https://material.google.com/components/subheaders.html
*/
interface SectionedAdapter {
/** A list of sections to display in adapter. */
var sections: SparseArray<AdapterSection>
/** Returns true if the given position contains a section */
fun isSectionHeaderPosition(position: Int) = sections[position] != null
/** Determines the correct position based off of the number of currently displayed sections. */
fun sectionedPositionToPosition(sectionedPosition: Int): Int {
if (isSectionHeaderPosition(sectionedPosition)) {
return RecyclerView.NO_POSITION
}
var offset = 0
for (i in 0..sections.size() - 1) {
if (sections.valueAt(i).sectionedPosition > sectionedPosition) {
break
}
--offset
}
return sectionedPosition + offset
}
fun positionToSectionedPosition(position: Int): Int {
var offset = 0
for (i in 0..sections.size() - 1) {
if (sections.valueAt(i).firstPosition > position) {
break
}
++offset
}
return position + offset
}
/**
* Clears the current set of selections and sets a new list.
* In order for the new sections to be displayed, one must first call
* notifyDatasetChanged()
*
* @param newSections The new sections to be set
*/
fun setSections(newSections: Array<AdapterSection>) {
sections.clear()
val sortedSections = newSections.clone()
Arrays.sort<AdapterSection>(sortedSections) { o, o1 ->
when {
o.firstPosition == o1.firstPosition -> 0
o.firstPosition < o1.firstPosition -> -1
else -> 1
}
}
var offset = 0 // offset positions for the headers we're adding
sortedSections.forEach {
it.sectionedPosition = it.firstPosition + offset
sections.append(it.sectionedPosition, it)
++offset
}
}
/** Returns the nearest section header if one exists */
tailrec fun getNearestSectionHeader(sectionedPosition: Int): Int {
if (isSectionHeaderPosition(sectionedPosition)) {
return sectionedPosition
} else {
return getNearestSectionHeader(sectionedPosition - 1)
}
}
} | apache-2.0 | 0a06e70fa8b34f597582212e113268ff | 30.914894 | 100 | 0.633878 | 4.423304 | false | false | false | false |
dafi/photoshelf | tag-navigator/src/main/java/com/ternaryop/photoshelf/tagnavigator/adapter/TagNavigatorViewHolder.kt | 1 | 1100 | package com.ternaryop.photoshelf.tagnavigator.adapter
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.ternaryop.photoshelf.api.post.TagInfo
import com.ternaryop.photoshelf.tagnavigator.R
import com.ternaryop.utils.text.fromHtml
import com.ternaryop.utils.text.htmlHighlightPattern
import java.util.Locale
class TagNavigatorViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val tagView: TextView = itemView.findViewById(R.id.tag)
private val countView: TextView = itemView.findViewById(R.id.count)
fun bindModel(tagInfo: TagInfo, pattern: CharSequence?) {
tagView.text = if (pattern == null || pattern.isBlank()) {
tagInfo.tag
} else {
tagInfo.tag.htmlHighlightPattern(pattern.toString()).fromHtml()
}
countView.text = String.format(Locale.US, "%3d", tagInfo.postCount)
}
fun setOnClickListeners(listener: View.OnClickListener) {
itemView.setOnClickListener(listener)
itemView.tag = bindingAdapterPosition
}
}
| mit | bd8f62e4c31d74136a00016e1de0fff8 | 36.931034 | 82 | 0.742727 | 4.166667 | false | false | false | false |
gpolitis/jitsi-videobridge | jvb/src/test/kotlin/org/jitsi/videobridge/stats/config/StatsManagerConfigTest.kt | 1 | 5377 | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge.stats.config
import io.kotest.inspectors.forOne
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.shouldBe
import org.jitsi.ConfigTest
import java.time.Duration
internal class StatsManagerConfigTest : ConfigTest() {
init {
context("When only new config contains stats transport config") {
context("a stats transport config") {
context("with multiple, valid stats transports configured") {
withNewConfig(newConfigAllStatsTransports()) {
val cfg = StatsManagerConfig()
cfg.transportConfigs shouldHaveSize 2
cfg.transportConfigs.forOne {
it as StatsTransportConfig.MucStatsTransportConfig
it.interval shouldBe Duration.ofSeconds(5)
}
cfg.transportConfigs.forOne {
it as StatsTransportConfig.CallStatsIoStatsTransportConfig
it.interval shouldBe Duration.ofSeconds(5)
}
}
}
context("with an invalid stats transport configured") {
withNewConfig(newConfigInvalidStatsTransports()) {
should("ignore the invalid config and parse the valid transport correctly") {
val cfg = StatsManagerConfig()
cfg.transportConfigs shouldHaveSize 1
cfg.transportConfigs.forOne { it as StatsTransportConfig.MucStatsTransportConfig }
}
}
}
context("which has a custom interval") {
withNewConfig(newConfigOneStatsTransportCustomInterval()) {
should("reflect the custom interval") {
val cfg = StatsManagerConfig()
cfg.transportConfigs.forOne {
it as StatsTransportConfig.MucStatsTransportConfig
it.interval shouldBe Duration.ofSeconds(10)
}
}
}
}
}
}
context("When old and new config contain stats transport configs") {
withLegacyConfig(legacyConfigAllStatsTransports()) {
withNewConfig(newConfigOneStatsTransport()) {
should("use the values from the old config") {
val cfg = StatsManagerConfig()
cfg.transportConfigs shouldHaveSize 2
cfg.transportConfigs.forOne { it as StatsTransportConfig.MucStatsTransportConfig }
cfg.transportConfigs.forOne { it as StatsTransportConfig.CallStatsIoStatsTransportConfig }
}
}
}
}
}
}
private fun newConfigAllStatsTransports(enabled: Boolean = true) = """
videobridge {
stats {
interval=5 seconds
enabled=$enabled
transports = [
{
type="muc"
},
{
type="callstatsio"
},
]
}
}
""".trimIndent()
private fun newConfigOneStatsTransport(enabled: Boolean = true) = """
videobridge {
stats {
enabled=$enabled
interval=5 seconds
transports = [
{
type="muc"
}
]
}
}
""".trimIndent()
private fun newConfigOneStatsTransportCustomInterval(enabled: Boolean = true) = """
videobridge {
stats {
enabled=$enabled
interval=5 seconds
transports = [
{
type="muc"
interval=10 seconds
}
]
}
}
""".trimIndent()
private fun newConfigInvalidStatsTransports(enabled: Boolean = true) = """
videobridge {
stats {
interval=5 seconds
enabled=$enabled
transports = [
{
type="invalid"
},
{
type="muc"
},
]
}
}
""".trimIndent()
private fun legacyConfigStatsEnabled(enabled: Boolean = true) = "org.jitsi.videobridge.ENABLE_STATISTICS=$enabled"
private fun legacyConfigAllStatsTransports(enabled: Boolean = true) = """
org.jitsi.videobridge.ENABLE_STATISTICS=$enabled
org.jitsi.videobridge.STATISTICS_TRANSPORT=muc,callstats.io
""".trimIndent()
| apache-2.0 | 15d60d774fc98948a905ba8fe7507b6e | 34.375 | 114 | 0.533383 | 5.987751 | false | true | false | false |
jonalmeida/focus-android | app/src/main/java/org/mozilla/focus/autocomplete/AutocompleteRemoveFragment.kt | 2 | 2420 | /* 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 org.mozilla.focus.autocomplete
import android.content.Context
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import kotlinx.android.synthetic.main.fragment_autocomplete_customdomains.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import mozilla.components.browser.domains.CustomDomains
import org.mozilla.focus.R
import org.mozilla.focus.settings.BaseSettingsFragment
import org.mozilla.focus.telemetry.TelemetryWrapper
import kotlin.coroutines.CoroutineContext
class AutocompleteRemoveFragment : AutocompleteListFragment(), CoroutineScope {
private var job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.menu_autocomplete_remove, menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) {
R.id.remove -> {
removeSelectedDomains(activity!!.applicationContext)
true
}
else -> super.onOptionsItemSelected(item)
}
private fun removeSelectedDomains(context: Context) {
val domains = (domainList.adapter as DomainListAdapter).selection()
if (domains.isNotEmpty()) {
launch(Main) {
async {
CustomDomains.remove(context, domains)
TelemetryWrapper.removeAutocompleteDomainsEvent(domains.size)
}.await()
fragmentManager!!.popBackStack()
}
}
}
override fun isSelectionMode() = true
override fun onResume() {
super.onResume()
if (job.isCancelled) {
job = Job()
}
val updater = activity as BaseSettingsFragment.ActionBarUpdater
updater.updateTitle(R.string.preference_autocomplete_title_remove)
updater.updateIcon(R.drawable.ic_back)
}
override fun onPause() {
job.cancel()
super.onPause()
}
}
| mpl-2.0 | 53628776d50b035be2d741a4e5f1bf35 | 31.702703 | 88 | 0.694628 | 4.820717 | false | false | false | false |
yh-kim/gachi-android | Gachi/app/src/main/kotlin/com/pickth/gachi/view/custom/AddInfoViewPager.kt | 1 | 4489 | /*
* Copyright 2017 Yonghoon Kim
*
* 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.pickth.gachi.view.custom
import android.content.Context
import android.support.v4.app.FragmentManager
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import com.pickth.gachi.R
import com.pickth.gachi.base.BaseAddInfoFragment
import com.pickth.gachi.extensions.convertDpToPixel
import kotlinx.android.synthetic.main.view_pager_add_info.view.*
class AddInfoViewPager : LinearLayout {
private var mFrameLayout: FrameLayout? = null
private var mFragmentManager: FragmentManager? = null
private val mIndexButtons = ArrayList<ImageView>()
private val mViews = ArrayList<BaseAddInfoFragment>()
var currentIndex = 0
companion object {
private val ITEM_COUNT = 5
}
constructor(context: Context): super(context) {
initializeView()
}
constructor(context: Context, attrs: AttributeSet): super(context, attrs) {
initializeView()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): super(context, attrs, defStyleAttr) {
initializeView()
}
fun setFragmentManager(fragmentManager: FragmentManager) {
mFragmentManager = fragmentManager
}
fun addItemView(fragment: BaseAddInfoFragment) {
fragment.setChangeFragmentListener(object: ChangeFragmentListener {
override fun onChange() {
changeNextFragment()
}
})
mViews.add(fragment)
}
fun getFragments(position: Int) = mViews[position]
private fun initializeView() {
var mLayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val rootView = mLayoutInflater.inflate(R.layout.view_pager_add_info, this, false)
mFrameLayout = rootView.fl_view_pager
val size = rootView.context.convertDpToPixel(5)
var params = LinearLayout.LayoutParams(size, size)
params.leftMargin = rootView.context.convertDpToPixel(4)
params.rightMargin = rootView.context.convertDpToPixel(4)
// params.topMargin = rootView.context.convertDpToPixel(39)
params.bottomMargin = rootView.context.convertDpToPixel(40)
for(i in 0..ITEM_COUNT-1) {
mIndexButtons.add(ImageView(context))
mIndexButtons[i].run {
setImageResource(R.drawable.selector_reliability_circle)
isSelected = (i == currentIndex)
// setPadding(10, 10, 10, 10)
}
rootView.ll_view_pager_buttons.addView(mIndexButtons[i], params)
}
addView(rootView)
}
fun changeNextFragment() {
currentIndex++
if(mFragmentManager != null) {
mFragmentManager?.beginTransaction()?.run {
setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
replace(mFrameLayout!!.id, mViews[currentIndex])?.commit()
}
}
updateIndexes()
}
fun changePreFragment() {
if(currentIndex == 0) return
currentIndex--
if(mFragmentManager != null) {
mFragmentManager?.beginTransaction()?.run {
setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right)
replace(mFrameLayout!!.id, mViews[currentIndex])?.commit()
}
}
updateIndexes()
}
fun updateIndexes() {
for(i in 0..ITEM_COUNT-1) {
mIndexButtons[i].isSelected = (i == currentIndex)
}
}
fun notifyDataSetChanged() {
if(mFragmentManager != null) {
mFragmentManager?.beginTransaction()?.replace(R.id.fl_view_pager, mViews[currentIndex])?.commit()
}
updateIndexes()
}
interface ChangeFragmentListener {
fun onChange()
}
}
| apache-2.0 | 08271c82bd669c08f1f115306a63c8ff | 29.958621 | 112 | 0.663399 | 4.493493 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/utils/extensions/ConnectivityExtensions.kt | 1 | 1918 | @file:JvmName("NetworkUtil")
package de.xikolo.utils.extensions
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities.*
import android.os.Build
enum class ConnectivityType {
WIFI, CELLULAR, NONE
}
val <T : Context?> T.isOnline: Boolean
get() {
val manager = this?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
?: return false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val info = manager.getNetworkCapabilities(manager.activeNetwork)
?: return false
return info.hasCapability(NET_CAPABILITY_INTERNET)
} else {
val info = manager.activeNetworkInfo ?: return false
return info.isConnected
}
}
val <T : Context?> T.connectivityType: ConnectivityType
get() {
val manager = this?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
?: return ConnectivityType.NONE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val info = manager.getNetworkCapabilities(manager.activeNetwork)
?: return ConnectivityType.NONE
if (info.hasTransport(TRANSPORT_WIFI)) {
return ConnectivityType.WIFI
}
if (info.hasTransport(TRANSPORT_CELLULAR)) {
return ConnectivityType.CELLULAR
}
} else {
val info = manager.activeNetworkInfo ?: return ConnectivityType.NONE
@Suppress("DEPRECATION")
if (info.type == ConnectivityManager.TYPE_WIFI) {
return ConnectivityType.WIFI
}
@Suppress("DEPRECATION")
if (info.type == ConnectivityManager.TYPE_MOBILE) {
return ConnectivityType.CELLULAR
}
}
return ConnectivityType.NONE
}
| bsd-3-clause | 7902f853650639e84f8c9b4cb603a8b0 | 30.442623 | 98 | 0.622002 | 4.956072 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/scene/SceneContainer.kt | 1 | 10545 | package com.soywiz.korge.scene
import com.soywiz.kds.iterators.*
import com.soywiz.klock.*
import com.soywiz.korge.tween.*
import com.soywiz.korge.view.*
import com.soywiz.korinject.*
import com.soywiz.korio.async.*
import com.soywiz.korio.async.async
import com.soywiz.korio.resources.*
import com.soywiz.korma.interpolation.*
import com.soywiz.korui.*
import kotlinx.coroutines.*
import kotlin.reflect.*
/**
* Creates a new [SceneContainer], allowing to configure with [callback], and attaches the newly created container to the receiver this [Container]
* It requires to specify the [Views] singleton instance, and allows to specify a [defaultTransition] [Transition].
**/
inline fun Container.sceneContainer(
views: Views,
defaultTransition: Transition = AlphaTransition.withEasing(Easing.EASE_IN_OUT_QUAD),
name: String = "sceneContainer",
callback: SceneContainer.() -> Unit = {}
): SceneContainer = SceneContainer(views, defaultTransition, name).addTo(this, callback)
suspend inline fun Container.sceneContainer(
defaultTransition: Transition = AlphaTransition.withEasing(Easing.EASE_IN_OUT_QUAD),
name: String = "sceneContainer",
callback: SceneContainer.() -> Unit = {}
): SceneContainer = SceneContainer(views(), defaultTransition, name).addTo(this, callback)
/**
* A [Container] [View] that can hold [Scene]s controllers and contains a history.
* It changes between scene objects by using the [AsyncInjector] and allow to use [Transition]s for the change.
* You can apply a easing to the [Transition] by calling [Transition.withEasing].
*/
class SceneContainer(
val views: Views,
/** Default [Transition] that will be used when no transition is specified */
val defaultTransition: Transition = AlphaTransition.withEasing(Easing.EASE_IN_OUT_QUAD),
name: String = "sceneContainer"
) : Container(), CoroutineScope by views {
init {
this.name = name
}
/** The [TransitionView] that will be in charge of rendering the old and new scenes during the transition using a specified [Transition] object */
val transitionView = TransitionView().also { this += it }
/** The [Scene] that is currently set or null */
var currentScene: Scene? = null
// Async versions
/** Async variant returning a [Deferred] for [changeTo] */
inline fun <reified T : Scene> changeToAsync(vararg injects: Any, time: TimeSpan = 0.seconds, transition: Transition = defaultTransition): Deferred<T>
= CoroutineScope(coroutineContext).async { changeTo<T>(*injects, time = time, transition = transition) }
/** Async variant returning a [Deferred] for [changeTo] */
fun <T : Scene> changeToAsync(clazz: KClass<T>, vararg injects: Any, time: TimeSpan = 0.seconds, transition: Transition = defaultTransition): Deferred<T>
= CoroutineScope(coroutineContext).async { changeTo(clazz, *injects, time = time, transition = transition) }
/** Async variant returning a [Deferred] for [pushTo] */
inline fun <reified T : Scene> pushToAsync(vararg injects: Any, time: TimeSpan = 0.seconds, transition: Transition = defaultTransition): Deferred<T>
= CoroutineScope(coroutineContext).async { pushTo<T>(*injects, time = time, transition = transition) }
/** Async variant returning a [Deferred] for [pushTo] */
fun <T : Scene> pushToAsync(clazz: KClass<T>, vararg injects: Any, time: TimeSpan = 0.seconds, transition: Transition = defaultTransition): Deferred<T>
= CoroutineScope(coroutineContext).async { pushTo(clazz, *injects, time = time, transition = transition) }
/** Async variant returning a [Deferred] for [back] */
suspend fun backAsync(time: TimeSpan = 0.seconds, transition: Transition = defaultTransition): Deferred<Scene> = CoroutineScope(coroutineContext).async { back(time, transition) }
/** Async variant returning a [Deferred] for [forward] */
suspend fun forwardAsync(time: TimeSpan = 0.seconds, transition: Transition = defaultTransition): Deferred<Scene> = CoroutineScope(coroutineContext).async { forward(time, transition) }
/**
* Changes to the [T] [Scene], with a set of optional [injects] instances during [time] time, and with [transition].
* This method waits until the [transition] has been completed, and returns the [T] created instance.
*/
suspend inline fun <reified T : Scene> changeTo(
vararg injects: Any,
time: TimeSpan = 0.seconds,
transition: Transition = defaultTransition
): T = changeTo(T::class, *injects, time = time, transition = transition)
/**
* Pushes the [T] [Scene], with a set of optional [injects] instances during [time] time, and with [transition].
* It removes the old [currentScene] if any.
* This method waits until the [transition] has been completed, and returns the [T] created instance.
*/
suspend inline fun <reified T : Scene> pushTo(
vararg injects: Any,
time: TimeSpan = 0.seconds,
transition: Transition = defaultTransition
) = pushTo(T::class, *injects, time = time, transition = transition)
/**
* Returns to the previous pushed Scene with [pushTo] in [time] time, and with [transition].
* This method waits until the [transition] has been completed, and returns the old [Scene] instance.
*/
suspend fun back(time: TimeSpan = 0.seconds, transition: Transition = defaultTransition): Scene {
visitPos--
return _changeTo(visitStack.getOrNull(visitPos) ?: EMPTY_VISIT_ENTRY, time = time, transition = transition)
}
/**
* Returns to the next pushed Scene with [pushTo] in [time] time, and with [transition].
* This method waits until the [transition] has been completed, and returns the old [Scene] instance.
*/
suspend fun forward(time: TimeSpan = 0.seconds, transition: Transition = defaultTransition): Scene {
visitPos++
return _changeTo(visitStack.getOrNull(visitPos) ?: EMPTY_VISIT_ENTRY, time = time, transition = transition)
}
/**
* Pushes the [T] [clazz] [Scene], with a set of optional [injects] instances during [time] time, and with [transition].
* It removes the old [currentScene] if any.
* This method waits until the [transition] has been completed, and returns the [T] created instance.
*/
suspend fun <T : Scene> pushTo(
clazz: KClass<T>,
vararg injects: Any,
time: TimeSpan = 0.seconds,
transition: Transition = defaultTransition
): T {
visitPos++
setCurrent(VisitEntry(clazz, injects.toList()))
return _changeTo(clazz, *injects, time = time, transition = transition)
}
/**
* Changes to the [T] [clazz] [Scene], with a set of optional [injects] instances during [time] time, and with [transition].
* This method waits until the [transition] has been completed, and returns the [T] created instance.
*/
suspend fun <T : Scene> changeTo(
clazz: KClass<T>,
vararg injects: Any,
time: TimeSpan = 0.seconds,
transition: Transition = defaultTransition
): T {
setCurrent(VisitEntry(clazz, injects.toList()))
return _changeTo(clazz, *injects, time = time, transition = transition)
}
private suspend fun _changeTo(
entry: VisitEntry,
time: TimeSpan = 0.seconds,
transition: Transition = defaultTransition
): Scene = _changeTo(entry.clazz, *entry.injects.toTypedArray(), time = time, transition = transition) as Scene
/** Check [Scene] for details of the lifecycle. */
private suspend fun <T : Scene> _changeTo(
clazz: KClass<T>,
vararg injects: Any,
time: TimeSpan = 0.seconds,
transition: Transition = defaultTransition
): T {
val oldScene = currentScene
val sceneInjector: AsyncInjector =
views.injector.child()
.mapInstance(SceneContainer::class, this@SceneContainer)
.mapInstance(Resources::class, Resources(coroutineContext, views.globalResources.root, views.globalResources))
injects.fastForEach { inject ->
sceneInjector.mapInstance(inject::class as KClass<Any>, inject)
}
val newScene = sceneInjector.get(clazz)
currentScene = newScene
transitionView.startNewTransition(newScene._sceneViewContainer, transition)
//println("SCENE PREINIT")
try {
newScene.coroutineContext.launchUnscopedAndWait {
//println("coroutineContext=$coroutineContext")
newScene.sceneView.apply { newScene.apply { sceneInit() } }
//println("...")
}
} catch (e: Throwable) {
//println("WOOOPS!")
e.printStackTrace()
}
//println("SCENE POSTINIT")
newScene.launchUnscoped {
newScene.sceneView.apply { newScene.apply { sceneMain() } }
}
if (oldScene != null) {
oldScene.coroutineContext.launchUnscopedAndWait {
oldScene.sceneBeforeLeaving()
}
}
if (time > 0.seconds) {
transitionView.tween(transitionView::ratio[0.0, 1.0], time = time)
} else {
transitionView.ratio = 1.0
}
transitionView.endTransition()
if (oldScene != null) {
oldScene.coroutineContext.launchUnscopedAndWait {
//println("sceneDestroy.coroutineContext=$coroutineContext")
oldScene.sceneDestroy()
oldScene.sceneDestroyInternal()
}
oldScene.launchUnscoped {
//println("sceneAfterDestroyInternal.coroutineContext=$coroutineContext")
oldScene.sceneAfterDestroyInternal()
}
}
newScene.coroutineContext.launchUnscoped {
newScene.sceneAfterInit()
}
return newScene
}
private data class VisitEntry(val clazz: KClass<out Scene>, val injects: List<Any>)
companion object {
private val EMPTY_VISIT_ENTRY = VisitEntry(EmptyScene::class, listOf())
}
private val visitStack = arrayListOf<VisitEntry>(EMPTY_VISIT_ENTRY)
private var visitPos = 0
// https://developer.mozilla.org/en/docs/Web/API/History
private fun setCurrent(entry: VisitEntry) {
while (visitStack.size <= visitPos) visitStack.add(EMPTY_VISIT_ENTRY)
visitStack[visitPos] = entry
}
override fun buildDebugComponent(views: Views, container: UiContainer) {
currentScene?.buildDebugComponent(views, container)
super.buildDebugComponent(views, container)
}
}
| apache-2.0 | 6e6501334e742f3eceda311ade392e9e | 42.217213 | 185 | 0.675676 | 4.250302 | false | false | false | false |
AngrySoundTech/CouponCodes3 | mods/bukkit/src/main/kotlin/tech/feldman/couponcodes/bukkit/database/SQLDatabaseHandler.kt | 2 | 9196 | /**
* The MIT License
* Copyright (c) 2015 Nicholas Feldman (AngrySoundTech)
* <p/>
* 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:
* <p/>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p/>
* 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 tech.feldman.couponcodes.bukkit.database
import tech.feldman.couponcodes.api.coupon.*
import tech.feldman.couponcodes.api.exceptions.UnknownMaterialException
import tech.feldman.couponcodes.bukkit.BukkitPlugin
import tech.feldman.couponcodes.bukkit.database.options.MySQLOptions
import tech.feldman.couponcodes.core.coupon.*
import tech.feldman.couponcodes.core.database.SimpleDatabaseHandler
import java.sql.PreparedStatement
import java.sql.SQLException
import java.util.*
class SQLDatabaseHandler(val plugin: BukkitPlugin, val database: SQLDatabase) : SimpleDatabaseHandler() {
override fun addCouponToDatabase(coupon: Coupon): Boolean {
if (couponExists(coupon))
return false
try {
val con = database.connection
var p: PreparedStatement? = null
if (coupon is ItemCoupon) {
p = con!!.prepareStatement("INSERT INTO couponcodes (name, ctype, usetimes, usedplayers, ids, timeuse) " + "VALUES (?, ?, ?, ?, ?, ?)")
p!!.setString(1, coupon.name)
p.setString(2, coupon.type)
p.setInt(3, coupon.useTimes)
p.setString(4, playerHashToString(coupon.usedPlayers))
p.setString(5, itemHashToString(coupon.items))
p.setInt(6, coupon.time)
} else if (coupon is EconomyCoupon) {
p = con!!.prepareStatement("INSERT INTO couponcodes (name, ctype, usetimes, usedplayers, money, timeuse) " + "VALUES (?, ?, ?, ?, ?, ?)")
p!!.setString(1, coupon.name)
p.setString(2, coupon.type)
p.setInt(3, coupon.useTimes)
p.setString(4, playerHashToString(coupon.usedPlayers))
p.setInt(5, coupon.money)
p.setInt(6, coupon.time)
} else if (coupon is RankCoupon) {
p = con!!.prepareStatement("INSERT INTO couponcodes (name, ctype, usetimes, usedplayers, groupname, timeuse) " + "VALUES (?, ?, ?, ?, ?, ?)")
p!!.setString(1, coupon.name)
p.setString(2, coupon.type)
p.setInt(3, coupon.useTimes)
p.setString(4, playerHashToString(coupon.usedPlayers))
p.setString(5, coupon.group)
p.setInt(6, coupon.time)
} else if (coupon is XpCoupon) {
p = con!!.prepareStatement("INSERT INTO couponcodes (name, ctype, usetimes, usedplayers, timeuse, xp) " + "VALUES (?, ?, ?, ?, ?, ?)")
p!!.setString(1, coupon.name)
p.setString(2, coupon.type)
p.setInt(3, coupon.useTimes)
p.setString(4, playerHashToString(coupon.usedPlayers))
p.setInt(5, coupon.time)
p.setInt(6, coupon.xp)
} else if (coupon is CommandCoupon) {
p = con!!.prepareStatement("INSERT INTO couponcodes (name, ctype, usetimes, usedplayers, timeuse, command) " + "VALUES (?, ?, ?, ?, ?, ?)")
p!!.setString(1, coupon.name)
p.setString(2, coupon.type)
p.setInt(3, coupon.useTimes)
p.setString(4, playerHashToString(coupon.usedPlayers))
p.setInt(5, coupon.time)
p.setString(6, coupon.cmd)
}
p!!.addBatch()
con!!.autoCommit = false
p.executeBatch()
con.autoCommit = true
return true
} catch (e: SQLException) {
return false
}
}
override fun removeCouponFromDatabase(coupon: Coupon): Boolean {
if (!couponExists(coupon))
return false
try {
database.query("DELETE FROM couponcodes WHERE name='" + coupon.name + "'")
return true
} catch (e: SQLException) {
return false
}
}
override fun removeCouponFromDatabase(coupon: String): Boolean {
if (!couponExists(coupon))
return false
try {
database.query("DELETE FROM couponcodes WHERE name='$coupon'")
return true
} catch (e: SQLException) {
return false
}
}
override fun getCoupons(): List<String> {
val c = ArrayList<String>()
try {
val rs = database.query("SELECT name FROM couponcodes")
while (rs.next())
c.add(rs.getString(1))
} catch (e: NullPointerException) {
e.printStackTrace()
} catch (e: SQLException) {
e.printStackTrace()
}
return c
}
override fun updateCoupon(coupon: Coupon) {
try {
database.query("UPDATE couponcodes SET usetimes='" + coupon.useTimes + "' WHERE name='" + coupon.name + "'")
database.query("UPDATE couponcodes SET usedplayers='" + playerHashToString(coupon.usedPlayers) + "' WHERE name='" + coupon.name + "'")
database.query("UPDATE couponcodes SET timeuse='" + coupon.time + "' WHERE name='" + coupon.name + "'")
if (coupon is ItemCoupon)
database.query("UPDATE couponcodes SET ids='" + itemHashToString(coupon.items) + "' WHERE name='" + coupon.getName() + "'")
else if (coupon is EconomyCoupon)
database.query("UPDATE couponcodes SET money='" + coupon.money + "' WHERE name='" + coupon.getName() + "'")
else if (coupon is RankCoupon)
database.query("UPDATE couponcodes SET groupname='" + coupon.group + "' WHERE name='" + coupon.getName() + "'")
else if (coupon is XpCoupon)
database.query("UPDATE couponcodes SET xp='" + coupon.xp + "' WHERE name='" + coupon.getName() + "'")
else if (coupon is CommandCoupon)
database.query("UPDATE couponcodes SET command='" + coupon.cmd + "' WHERE name='" + coupon.getName() + "'")
} catch (e: SQLException) {
e.printStackTrace()
}
}
override fun updateCouponTime(coupon: Coupon) {
try {
database.query("UPDATE couponcodes SET timeuse='" + coupon.time + "' WHERE name='" + coupon.name + "'")
} catch (e: SQLException) {
e.printStackTrace()
}
}
override fun getCoupon(coupon: String): Coupon? {
if (!couponExists(coupon))
return null
try {
val rs = database.query("SELECT * FROM couponcodes WHERE name='$coupon'")
if (database.databaseOptions is MySQLOptions)
rs.first()
val usetimes = rs.getInt("usetimes")
val time = rs.getInt("timeuse")
val usedplayers = playerStringToHash(rs.getString("usedplayers"))
if (rs.getString("ctype").equals("Item", ignoreCase = true))
try {
return SimpleItemCoupon(coupon, usetimes, time, usedplayers, itemStringToHash(rs.getString("ids")))
} catch (e: UnknownMaterialException) {
// This should never happen, unless the database was modified by something not this plugin
return null
}
else if (rs.getString("ctype").equals("Economy", ignoreCase = true))
return SimpleEconomyCoupon(coupon, usetimes, time, usedplayers, rs.getInt("money"))
else if (rs.getString("ctype").equals("Rank", ignoreCase = true))
return SimpleRankCoupon(coupon, usetimes, time, usedplayers, rs.getString("groupname"))
else if (rs.getString("ctype").equals("Xp", ignoreCase = true))
return SimpleXpCoupon(coupon, usetimes, time, usedplayers, rs.getInt("xp"))
else if (rs.getString("ctype").equals("Command", ignoreCase = true))
return SimpleCommandCoupon(coupon, usetimes, time, usedplayers, rs.getString("command"))
else
return null
} catch (e: SQLException) {
e.printStackTrace()
return null
}
}
}
| mit | 8284b968f77615a33e3245ac15a5d5ab | 44.524752 | 157 | 0.594389 | 4.261353 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Coroutines/src/main/kotlin/core/context_dispatchers/08_Naming.kt | 2 | 1073 | package core.context_dispatchers
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
private fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
/*
ๅ็จๆฅๅฟไผ้ข็น่ฎฐๅฝ็ๆถๅไปฅๅๅฝไฝ ๅชๆฏ้่ฆๆฅ่ช็ธๅๅ็จ็ๅ
ณ่ๆฅๅฟ่ฎฐๅฝ๏ผ ่ชๅจๅ้
id ๆฏ้ๅธธๆฃ็ใ
็ถ่๏ผๅฝๅ็จไธๆง่กไธไธชๆ็กฎ็่ฏทๆฑๆไธๆง่กไธไบๆพๅผ็ๅๅฐไปปๅกๆๅ
ณ็ๆถๅ๏ผๅบไบ่ฐ่ฏ็็ฎ็็ปๅฎๆ็กฎ็ๅฝๅๆฏๆดๅฅฝ็ๅๆณใ
ไปฅ -Dkotlinx.coroutines.debug ๅฏๅจ่ฏฅ็จๅบ
*/
fun main() = runBlocking(CoroutineName("main")) {
//sampleStart
log("Started main coroutine")
// run two background value computations
val v1 = async(CoroutineName("v1coroutine")) {
delay(500)
log("Computing v1")
252
}
val v2 = async(CoroutineName("v2coroutine")) {
delay(1000)
log("Computing v2")
6
}
log("The answer for v1 / v2 = ${v1.await() / v2.await()}")
//sampleEnd
} | apache-2.0 | 2200d90c5128d3dde758e7e0e203b8a1 | 26.806452 | 79 | 0.69338 | 3.142336 | false | false | false | false |
freundTech/OneSlotServer | src/main/kotlin/com/freundtech/minecraft/oneslotserver/handler/command/TimeCommandsExecutors.kt | 1 | 2443 | package com.freundtech.minecraft.oneslotserver.handler.command
import com.freundtech.minecraft.oneslotserver.OneSlotServer
import com.freundtech.minecraft.oneslotserver.extension.PlayerInfo
import com.freundtech.minecraft.oneslotserver.extension.oneSlotServer
import com.kizitonwose.time.seconds
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
class SetPlayTimeCommand(private val plugin: OneSlotServer) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (args.size != 1) {
return false
}
val time = args[0].toLongOrNull()?.seconds ?: return false
plugin.playTime = time
sender.sendMessage("Set play time to $time")
return true
}
}
class SetWaitTimeCommand(private val plugin: OneSlotServer) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (args.size != 1) {
return false
}
val time = args[0].toLongOrNull()?.seconds ?: return false
plugin.waitTime = time
sender.sendMessage("Set wait time to $time")
return true
}
}
class SetTimeLeftCommand(private val plugin: OneSlotServer) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (args.size !in 1..2) {
return false
}
val time = args[0].toLongOrNull()?.seconds ?: return false
if (args.size == 1) {
val player = plugin.activePlayer ?: run {
sender.sendMessage("Nobody is currently playing")
return false
}
player.oneSlotServer.timeLeft = time
sender.sendMessage("Set time left to $time for active player")
} else {
val playerName = args[1]
val player = sender.server.offlinePlayers.firstOrNull { it.name.equals(playerName, ignoreCase = true) } ?: run {
sender.sendMessage("Player $playerName is isn't known to this server")
return false
}
player.oneSlotServer.also { it.timeLeft = time }.save()
sender.sendMessage("Set time left to $time for $playerName")
}
return true
}
}
| mit | 4958f1df0431d99715889f5bc1fcde57 | 39.716667 | 124 | 0.653704 | 4.425725 | false | false | false | false |
matejdro/WearMusicCenter | mobile/src/main/java/com/matejdro/wearmusiccenter/music/MusicService.kt | 1 | 19174 | package com.matejdro.wearmusiccenter.music
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.database.ContentObserver
import android.graphics.Bitmap
import android.media.MediaMetadata
import android.media.session.MediaController
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.preference.PreferenceManager
import android.provider.Settings
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.wearable.Asset
import com.google.android.gms.wearable.DataClient
import com.google.android.gms.wearable.MessageClient
import com.google.android.gms.wearable.MessageEvent
import com.google.android.gms.wearable.PutDataRequest
import com.google.android.gms.wearable.Wearable
import com.matejdro.wearmusiccenter.R
import com.matejdro.wearmusiccenter.actions.ActionHandler
import com.matejdro.wearmusiccenter.actions.OpenPlaylistAction
import com.matejdro.wearmusiccenter.actions.PhoneAction
import com.matejdro.wearmusiccenter.common.CommPaths
import com.matejdro.wearmusiccenter.common.CustomLists
import com.matejdro.wearmusiccenter.common.MiscPreferences
import com.matejdro.wearmusiccenter.common.buttonconfig.ButtonInfo
import com.matejdro.wearmusiccenter.common.util.FloatPacker
import com.matejdro.wearmusiccenter.config.ActionConfig
import com.matejdro.wearmusiccenter.config.WatchInfoProvider
import com.matejdro.wearmusiccenter.config.WatchInfoWithIcons
import com.matejdro.wearmusiccenter.di.GlobalConfig
import com.matejdro.wearmusiccenter.di.MusicServiceSubComponent
import com.matejdro.wearmusiccenter.notifications.NotificationProvider
import com.matejdro.wearmusiccenter.proto.CustomListItemAction
import com.matejdro.wearmusiccenter.proto.MusicState
import com.matejdro.wearmusiccenter.proto.WatchActions
import com.matejdro.wearmusiccenter.util.launchWithPlayServicesErrorHandling
import com.matejdro.wearutils.coroutines.await
import com.matejdro.wearutils.lifecycle.EmptyObserver
import com.matejdro.wearutils.lifecycle.Resource
import com.matejdro.wearutils.miscutils.BitmapUtils
import com.matejdro.wearutils.preferences.definition.Preferences
import com.matejdro.wearvibrationcenter.notificationprovider.ReceivedNotification
import dagger.android.AndroidInjection
import timber.log.Timber
import java.lang.ref.WeakReference
import java.nio.ByteBuffer
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class MusicService : LifecycleService(), MessageClient.OnMessageReceivedListener {
companion object {
const val ACTION_START_FROM_WATCH = "START_FROM_WATCH"
const val ACTION_NOTIFICATION_SERVICE_ACTIVATED = "NOTIFICATION_SERVICE_ACTIVATED"
private const val MESSAGE_STOP_SELF = 0
private val ACK_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(3)
private const val STOP_SELF_PENDING_INTENT_REQUEST_CODE = 333
private const val ACTION_STOP_SELF = "STOP_SELF"
private const val KEY_NOTIFICATION_CHANNEL = "Service_Channel"
private const val KEY_NOTIFICATION_CHANNEL_ERRORS = "Error notifications"
private const val NOTIFICATION_ID_PERSISTENT = 1
private const val NOTIFICATION_ID_SERVICE_ERROR = 2
var active = false
private set
}
private lateinit var messageClient: MessageClient
private lateinit var dataClient: DataClient
private lateinit var preferences: SharedPreferences
@Inject
lateinit var mediaSessionProvider: ActiveMediaSessionProvider
@Inject
@GlobalConfig
lateinit var config: ActionConfig
@Inject
lateinit var watchInfoProvider: WatchInfoProvider
@Inject
lateinit var notificationProvider: NotificationProvider
@Inject
lateinit var musicServiceComponentFactory: MusicServiceSubComponent.Factory
private lateinit var actionHandlers: Map<Class<*>, ActionHandler<*>>
private var ackTimeoutHandler = AckTimeoutHandler(WeakReference(this))
private var previousMusicState: MusicState? = null
var currentMediaController: MediaController? = null
private var startedFromWatch = false
private var currentVolume = 0
@SuppressLint("LaunchActivityFromNotification")
override fun onCreate() {
super.onCreate()
AndroidInjection.inject(this)
actionHandlers = musicServiceComponentFactory.build(this).getActionHandlers()
messageClient = Wearable.getMessageClient(applicationContext)
dataClient = Wearable.getDataClient(applicationContext)
preferences = PreferenceManager.getDefaultSharedPreferences(this)
messageClient.addListener(this, Uri.parse(CommPaths.MESSAGES_PREFIX), MessageClient.FILTER_PREFIX)
mediaSessionProvider = ActiveMediaSessionProvider(this)
mediaSessionProvider.observe(this, mediaCallback)
watchInfoProvider.observe(this, EmptyObserver<WatchInfoWithIcons>())
if (Preferences.getBoolean(preferences, MiscPreferences.ENABLE_NOTIFICATION_POPUP)) {
notificationProvider.observe(this, notificationCallback)
}
val stopSelfIntent = Intent(this, MusicService::class.java)
stopSelfIntent.action = ACTION_STOP_SELF
val stopSelfPendingIntent = PendingIntent.getService(this,
STOP_SELF_PENDING_INTENT_REQUEST_CODE,
stopSelfIntent,
PendingIntent.FLAG_UPDATE_CURRENT)
createNotificationChannel()
val notificationBuilder = NotificationCompat.Builder(this, KEY_NOTIFICATION_CHANNEL)
.setContentTitle(getString(R.string.music_control_active))
.setContentText(getString(R.string.tap_to_force_stop))
.setContentIntent(stopSelfPendingIntent)
.setSmallIcon(R.drawable.ic_notification)
contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, volumeContentObserver)
// This is still needed for Pre-O versions, so it must be used, even if it is deprecated.
@Suppress("DEPRECATION")
notificationBuilder.priority = Notification.PRIORITY_MIN
startForeground(NOTIFICATION_ID_PERSISTENT, notificationBuilder.build())
active = true
Timber.d("Service started")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val action = intent?.action
if (action == ACTION_START_FROM_WATCH) {
startedFromWatch = true
} else if (action == ACTION_STOP_SELF || !startedFromWatch) {
stopSelf()
return Service.START_NOT_STICKY
} else if (action == ACTION_NOTIFICATION_SERVICE_ACTIVATED) {
mediaSessionProvider.activate()
NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID_SERVICE_ERROR)
}
super.onStartCommand(intent, flags, startId)
return Service.START_STICKY
}
override fun onDestroy() {
Timber.d("Service stopped")
messageClient.removeListener(this)
ackTimeoutHandler.removeCallbacksAndMessages(null)
contentResolver.unregisterContentObserver(volumeContentObserver)
active = false
super.onDestroy()
}
private val mediaCallback = Observer<Resource<MediaController>?> {
when {
it == null -> {
buildMusicStateAndTransmit(null)
}
it.status == Resource.Status.ERROR -> {
transmitError(it.message ?: "")
if (it.message == getString(R.string.error_notification_access)) {
showNotificationServiceErrorNotification()
}
}
else -> {
currentMediaController = it.data
buildMusicStateAndTransmit(currentMediaController)
}
}
}
private val notificationCallback = Observer<ReceivedNotification> {
if (it == null) {
return@Observer
}
val putDataRequest = PutDataRequest.create(CommPaths.DATA_NOTIFICATION)
val protoNotification = com.matejdro.wearmusiccenter.proto.Notification.newBuilder()
.setTitle(it.title.trim())
.setDescription(it.description.trim())
.setTime(System.currentTimeMillis().toInt())
.build()
it.imageDataPng?.let { imageData ->
val albumArtAsset = Asset.createFromBytes(imageData)
putDataRequest.putAsset(CommPaths.ASSET_NOTIFICATION_BACKGROUND, albumArtAsset)
}
putDataRequest.data = protoNotification.toByteArray()
putDataRequest.setUrgent()
lifecycleScope.launchWithPlayServicesErrorHandling(this) {
dataClient.putDataItem(putDataRequest).await()
}
startTimeout()
}
private fun updateVolume(newVolume: Float) {
val previousMediaController = currentMediaController ?: return
val maxVolume = previousMediaController.playbackInfo?.maxVolume ?: 0
val newAbsoluteVolume = (maxVolume * newVolume).toInt()
currentVolume = newAbsoluteVolume
previousMediaController.setVolumeTo(newAbsoluteVolume, 0)
}
private fun executeAction(buttonInfo: ButtonInfo) {
val playing = currentMediaController?.isPlaying() == true
val config = if (playing)
config.getPlayingConfig()
else
config.getStoppedConfig()
val buttonAction = config.getScreenAction(buttonInfo) ?: return
executeAction(buttonAction)
}
private fun executeMenuAction(index: Int) {
val config = config.getActionList()
val list = config.actions
if (index < 0 || index >= list.size) {
Timber.e("Action out of bounds: %d", index)
return
}
executeAction(list[index])
}
private fun executeAction(action: PhoneAction) {
lifecycleScope.launchWithPlayServicesErrorHandling(this) {
@Suppress("UNCHECKED_CAST")
val handler = actionHandlers[action.javaClass] as ActionHandler<PhoneAction>?
?: throw IllegalStateException("Action handler for $action missing")
handler.handleAction(action)
}
}
private fun buildMusicStateAndTransmit(mediaController: MediaController?) {
val musicStateBuilder = MusicState.newBuilder()
var albumArt: Bitmap? = null
musicStateBuilder.time = System.currentTimeMillis().toInt()
if (mediaController == null) {
musicStateBuilder.playing = false
} else {
musicStateBuilder.playing = mediaController.playbackState?.isPlaying() == true
val meta = mediaController.metadata
if (meta != null) {
meta.getString(MediaMetadata.METADATA_KEY_ARTIST)?.let {
musicStateBuilder.artist = it
}
meta.getString(MediaMetadata.METADATA_KEY_TITLE)?.let {
musicStateBuilder.title = it
}
albumArt = meta.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART)
}
currentVolume = mediaController.playbackInfo?.currentVolume ?: 0
val volume = currentVolume.toFloat() / (mediaController.playbackInfo?.maxVolume?.toFloat() ?: 0f)
musicStateBuilder.volume = volume
}
val musicState = musicStateBuilder.build()
// Do not waste BT bandwitch and re-transmit equal music state
if (musicState.equalsIgnoringTime(previousMusicState)) {
return
}
Timber.d("TransmittingToWear %s", musicState)
transmitToWear(musicState, albumArt)
}
private fun transmitToWear(musicState: MusicState, originalAlbumArt: Bitmap?) {
lifecycleScope.launchWithPlayServicesErrorHandling(this) {
val putDataRequest = PutDataRequest.create(CommPaths.DATA_MUSIC_STATE)
var albumArt = originalAlbumArt
val watchInfo = watchInfoProvider.value?.watchInfo
if (watchInfo != null && albumArt != null) {
albumArt = BitmapUtils.resizeAndCrop(albumArt,
watchInfo.displayWidth,
watchInfo.displayHeight,
true)
}
if (albumArt != null) {
val albumArtAsset = Asset.createFromBytes(BitmapUtils.serialize(albumArt)!!)
putDataRequest.putAsset(CommPaths.ASSET_ALBUM_ART, albumArtAsset)
}
putDataRequest.data = musicState.toByteArray()
putDataRequest.setUrgent()
dataClient.putDataItem(putDataRequest).await()
startTimeout()
}
}
private fun transmitError(error: String) = lifecycleScope.launchWithPlayServicesErrorHandling(this) {
val musicStateBuilder = MusicState.newBuilder()
// Add time to the first message to make sure it gets transmitted even if it is
// identical to the previous one
musicStateBuilder.time = System.currentTimeMillis().toInt()
musicStateBuilder.error = true
musicStateBuilder.title = error
musicStateBuilder.playing = false
val musicState = musicStateBuilder.build()
val putDataRequest = PutDataRequest.create(CommPaths.DATA_MUSIC_STATE)
putDataRequest.data = musicState.toByteArray()
putDataRequest.setUrgent()
dataClient.putDataItem(putDataRequest).await()
}
private fun showNotificationServiceErrorNotification() {
val notificationManagerIntent = Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
val notificationManagerPendingIntent = PendingIntent.getActivity(this,
STOP_SELF_PENDING_INTENT_REQUEST_CODE,
notificationManagerIntent,
PendingIntent.FLAG_UPDATE_CURRENT)
createNotificationChannel()
val notificationBuilder = NotificationCompat.Builder(this, KEY_NOTIFICATION_CHANNEL_ERRORS)
.setContentTitle(getString(R.string.notification_access_notification_title))
.setContentText(getString(R.string.notification_access_notification_title_description))
.setContentIntent(notificationManagerPendingIntent)
.setSmallIcon(R.drawable.ic_notification)
NotificationManagerCompat.from(this).notify(NOTIFICATION_ID_SERVICE_ERROR,
notificationBuilder.build())
}
private fun onWatchSwipeExited() {
if (!Preferences.getBoolean(preferences, MiscPreferences.PAUSE_ON_SWIPE_EXIT)) {
return
}
if (currentMediaController?.isPlaying() == true) {
currentMediaController?.transportControls?.pause()
}
}
private fun onCustomMenuItemPresed(customListItemAction: CustomListItemAction) {
if (customListItemAction.entryId == CustomLists.SPECIAL_ITEM_ERROR) {
return
}
when (customListItemAction.listId) {
CustomLists.PLAYLIST -> {
currentMediaController?.transportControls?.skipToQueueItem(
customListItemAction.entryId.toLong()
)
}
}
}
private fun openPlaybackQueueOnWatch() {
executeAction(OpenPlaylistAction(this))
}
override fun onMessageReceived(event: MessageEvent?) {
if (event == null) {
return
}
Timber.d("Message %s", event.path)
when (event.path) {
CommPaths.MESSAGE_WATCH_CLOSED -> {
stopSelf()
}
CommPaths.MESSAGE_ACK -> {
ackTimeoutHandler.removeMessages(MESSAGE_STOP_SELF)
}
CommPaths.MESSAGE_CHANGE_VOLUME -> {
updateVolume(FloatPacker.unpackFloat(event.data))
}
CommPaths.MESSAGE_EXECUTE_ACTION -> {
executeAction(ButtonInfo(WatchActions.ProtoButtonInfo.parseFrom(event.data)))
}
CommPaths.MESSAGE_EXECUTE_MENU_ACTION -> {
executeMenuAction(ByteBuffer.wrap(event.data).int)
}
CommPaths.MESSAGE_WATCH_OPENED -> {
ackTimeoutHandler.removeMessages(MESSAGE_STOP_SELF)
buildMusicStateAndTransmit(currentMediaController)
}
CommPaths.MESSAGE_WATCH_CLOSED_MANUALLY -> {
onWatchSwipeExited()
}
CommPaths.MESSAGE_CUSTOM_LIST_ITEM_SELECTED -> {
onCustomMenuItemPresed(CustomListItemAction.parseFrom(event.data))
}
CommPaths.MESSAGE_OPEN_PLAYBACK_QUEUE -> {
openPlaybackQueueOnWatch()
}
}
}
@TargetApi(Build.VERSION_CODES.O)
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val persistentChannel = NotificationChannel(KEY_NOTIFICATION_CHANNEL,
getString(R.string.music_control),
NotificationManager.IMPORTANCE_MIN)
notificationManager.createNotificationChannel(persistentChannel)
val errorChannel = NotificationChannel(KEY_NOTIFICATION_CHANNEL_ERRORS,
getString(R.string.error_notifications),
NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(errorChannel)
}
private fun startTimeout() {
ackTimeoutHandler.removeMessages(MESSAGE_STOP_SELF)
}
private class AckTimeoutHandler(val service: WeakReference<MusicService>) : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
if (msg.what == MESSAGE_STOP_SELF) {
Timber.d("TIMEOUT!")
service.get()?.stopSelf()
}
}
}
private fun MusicState.equalsIgnoringTime(other: MusicState?): Boolean {
return other != null &&
other.playing == playing &&
other.artist == artist &&
other.title == title &&
other.volume == volume &&
other.error == error
}
private val volumeContentObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
override fun onChange(selfChange: Boolean) {
val newVolume = currentMediaController?.playbackInfo?.currentVolume
if (newVolume != currentVolume) {
buildMusicStateAndTransmit(currentMediaController)
}
}
}
}
| gpl-3.0 | 70f99c2a236aa8b2c5a7c48425d920cf | 36.158915 | 113 | 0.680035 | 5.191985 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.