content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.habitrpg.android.habitica.data.implementation
import com.habitrpg.android.habitica.BuildConfig
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.data.local.SocialLocalRepository
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.models.Achievement
import com.habitrpg.android.habitica.models.inventory.Quest
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.responses.PostChatMessageResult
import com.habitrpg.android.habitica.models.social.ChatMessage
import com.habitrpg.android.habitica.models.social.FindUsernameResult
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.models.social.GroupMembership
import com.habitrpg.android.habitica.models.social.InboxConversation
import com.habitrpg.android.habitica.models.user.User
import io.reactivex.rxjava3.core.Flowable
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import java.util.UUID
class SocialRepositoryImpl(
localRepository: SocialLocalRepository,
apiClient: ApiClient,
userID: String
) : BaseRepositoryImpl<SocialLocalRepository>(localRepository, apiClient, userID), SocialRepository {
override suspend fun transferGroupOwnership(groupID: String, userID: String): Group? {
val group = localRepository.getGroup(groupID).first()?.let { localRepository.getUnmanagedCopy(it) }
group?.leaderID = userID
return group?.let { apiClient.updateGroup(groupID, it) }
}
override suspend fun removeMemberFromGroup(groupID: String, userID: String): List<Member>? {
apiClient.removeMemberFromGroup(groupID, userID)
return retrievePartyMembers(groupID, true)
}
override fun blockMember(userID: String): Flowable<List<String>> {
return apiClient.blockMember(userID)
}
override fun getGroupMembership(id: String) = localRepository.getGroupMembership(userID, id)
override fun getGroupMemberships(): Flowable<out List<GroupMembership>> {
return localRepository.getGroupMemberships(userID)
}
override suspend fun retrieveGroupChat(groupId: String): List<ChatMessage>? {
val messages = apiClient.listGroupChat(groupId)
messages?.forEach { it.groupId = groupId }
return messages
}
override fun getGroupChat(groupId: String): Flowable<out List<ChatMessage>> {
return localRepository.getGroupChat(groupId)
}
override fun markMessagesSeen(seenGroupId: String) {
apiClient.seenMessages(seenGroupId).subscribe({ }, ExceptionHandler.rx())
}
override fun flagMessage(chatMessageID: String, additionalInfo: String, groupID: String?): Flowable<Void> {
return when {
chatMessageID.isBlank() -> Flowable.empty()
userID == BuildConfig.ANDROID_TESTING_UUID -> Flowable.empty()
else -> {
val data = mutableMapOf<String, String>()
data["comment"] = additionalInfo
if (groupID?.isNotBlank() != true) {
apiClient.flagInboxMessage(chatMessageID, data)
} else {
apiClient.flagMessage(groupID, chatMessageID, data)
}
}
}
}
override fun likeMessage(chatMessage: ChatMessage): Flowable<ChatMessage> {
if (chatMessage.id.isBlank()) {
return Flowable.empty()
}
val liked = chatMessage.userLikesMessage(userID)
if (chatMessage.isManaged) {
localRepository.likeMessage(chatMessage, userID, !liked)
}
return apiClient.likeMessage(chatMessage.groupId ?: "", chatMessage.id)
.map {
it.groupId = chatMessage.groupId
it
}
}
override fun deleteMessage(chatMessage: ChatMessage): Flowable<Void> {
return if (chatMessage.isInboxMessage) {
apiClient.deleteInboxMessage(chatMessage.id)
} else {
apiClient.deleteMessage(chatMessage.groupId ?: "", chatMessage.id)
}.doOnNext { localRepository.deleteMessage(chatMessage.id) }
}
override fun postGroupChat(groupId: String, messageObject: HashMap<String, String>): Flowable<PostChatMessageResult> {
return apiClient.postGroupChat(groupId, messageObject)
.map { postChatMessageResult ->
postChatMessageResult.message.groupId = groupId
postChatMessageResult
}
}
override fun postGroupChat(groupId: String, message: String): Flowable<PostChatMessageResult> {
val messageObject = HashMap<String, String>()
messageObject["message"] = message
return postGroupChat(groupId, messageObject)
}
override suspend fun retrieveGroup(id: String): Group? {
val group = apiClient.getGroup(id)
group?.let { localRepository.saveGroup(it) }
retrieveGroupChat(id)
return group
}
override fun getGroup(id: String?): Flow<Group?> {
if (id?.isNotBlank() != true) {
return emptyFlow()
}
return localRepository.getGroup(id)
}
override suspend fun leaveGroup(id: String?, keepChallenges: Boolean): Group? {
if (id?.isNotBlank() != true) {
return null
}
apiClient.leaveGroup(id, if (keepChallenges) "remain-in-challenges" else "leave-challenges")
localRepository.updateMembership(userID, id, false)
return localRepository.getGroup(id).firstOrNull()
}
override suspend fun joinGroup(id: String?): Group? {
if (id?.isNotBlank() != true) {
return null
}
val group = apiClient.joinGroup(id)
group?.let {
localRepository.updateMembership(userID, id, true)
localRepository.save(group)
}
return group
}
override suspend fun createGroup(
name: String?,
description: String?,
leader: String?,
type: String?,
privacy: String?,
leaderCreateChallenge: Boolean?
): Group? {
val group = Group()
group.name = name
group.description = description
group.type = type
group.leaderID = leader
group.privacy = privacy
val savedGroup = apiClient.createGroup(group)
savedGroup?.let { localRepository.save(it) }
return savedGroup
}
override suspend fun updateGroup(
group: Group?,
name: String?,
description: String?,
leader: String?,
leaderCreateChallenge: Boolean?
): Group? {
if (group == null) {
return null
}
val copiedGroup = localRepository.getUnmanagedCopy(group)
copiedGroup.name = name
copiedGroup.description = description
copiedGroup.leaderID = leader
copiedGroup.leaderOnlyChallenges = leaderCreateChallenge ?: false
localRepository.save(copiedGroup)
return apiClient.updateGroup(copiedGroup.id, copiedGroup)
}
override fun retrieveGroups(type: String): Flowable<List<Group>> {
return apiClient.listGroups(type)
.doOnNext { groups ->
if ("guilds" == type) {
val memberships = groups.map {
GroupMembership(userID, it.id)
}
localRepository.saveGroupMemberships(userID, memberships)
}
localRepository.save(groups)
}
}
override fun getGroups(type: String) = localRepository.getGroups(type)
override fun getPublicGuilds() = localRepository.getPublicGuilds()
override fun getInboxConversations() = localRepository.getInboxConversation(userID)
override fun getInboxMessages(replyToUserID: String?) = localRepository.getInboxMessages(userID, replyToUserID)
override suspend fun retrieveInboxMessages(uuid: String, page: Int): List<ChatMessage>? {
val messages = apiClient.retrieveInboxMessages(uuid, page) ?: return null
messages.forEach {
it.isInboxMessage = true
}
localRepository.saveInboxMessages(userID, uuid, messages, page)
return messages
}
override fun retrieveInboxConversations(): Flowable<List<InboxConversation>> {
return apiClient.retrieveInboxConversations().doOnNext { conversations ->
localRepository.saveInboxConversations(userID, conversations)
}
}
override suspend fun postPrivateMessage(recipientId: String, messageObject: HashMap<String, String>): List<ChatMessage>? {
val message = apiClient.postPrivateMessage(messageObject)
return retrieveInboxMessages(recipientId, 0)
}
override suspend fun postPrivateMessage(recipientId: String, message: String): List<ChatMessage>? {
val messageObject = HashMap<String, String>()
messageObject["message"] = message
messageObject["toUserId"] = recipientId
return postPrivateMessage(recipientId, messageObject)
}
override suspend fun getPartyMembers(id: String) = localRepository.getPartyMembers(id)
override suspend fun getGroupMembers(id: String) = localRepository.getGroupMembers(id)
override suspend fun retrievePartyMembers(id: String, includeAllPublicFields: Boolean): List<Member>? {
val members = apiClient.getGroupMembers(id, includeAllPublicFields)
members?.let { localRepository.savePartyMembers(id, it) }
return members
}
override fun inviteToGroup(id: String, inviteData: Map<String, Any>): Flowable<List<Void>> = apiClient.inviteToGroup(id, inviteData)
override suspend fun retrieveMember(userId: String?): Member? {
return if (userId == null) {
null
} else {
try {
apiClient.getMember(UUID.fromString(userId).toString())
} catch (_: IllegalArgumentException) {
apiClient.getMemberWithUsername(userId)
}
}
}
override suspend fun retrieveMemberWithUsername(username: String?): Member? {
return retrieveMember(username)
}
override fun findUsernames(username: String, context: String?, id: String?): Flowable<List<FindUsernameResult>> {
return apiClient.findUsernames(username, context, id)
}
override fun markPrivateMessagesRead(user: User?): Flowable<Void> {
if (user?.isManaged == true) {
localRepository.modify(user) {
it.inbox?.hasUserSeenInbox = true
}
}
return apiClient.markPrivateMessagesRead()
}
override fun markSomePrivateMessagesAsRead(user: User?, messages: List<ChatMessage>) {
if (user?.isManaged == true) {
val numOfUnseenMessages = messages.count { !it.isSeen }
localRepository.modify(user) {
val numOfNewMessagesFromInbox = it.inbox?.newMessages ?: 0
if (numOfNewMessagesFromInbox > numOfUnseenMessages) {
it.inbox?.newMessages = numOfNewMessagesFromInbox - numOfUnseenMessages
} else {
it.inbox?.newMessages = 0
}
}
}
for (message in messages.filter { it.isManaged && !it.isSeen }) {
localRepository.modify(message) {
it.isSeen = true
}
}
}
override fun getUserGroups(type: String?) = localRepository.getUserGroups(userID, type)
override fun acceptQuest(user: User?, partyId: String): Flowable<Void> {
return apiClient.acceptQuest(partyId)
.doOnNext {
user?.let {
localRepository.updateRSVPNeeded(it, false)
}
}
}
override fun rejectQuest(user: User?, partyId: String): Flowable<Void> {
return apiClient.rejectQuest(partyId)
.doOnNext { _ ->
user?.let {
localRepository.updateRSVPNeeded(it, false)
}
}
}
override fun leaveQuest(partyId: String): Flowable<Void> {
return apiClient.leaveQuest(partyId)
}
override fun cancelQuest(partyId: String): Flowable<Void> {
return apiClient.cancelQuest(partyId)
.doOnNext { localRepository.removeQuest(partyId) }
}
override fun abortQuest(partyId: String): Flowable<Quest> {
return apiClient.abortQuest(partyId)
.doOnNext { localRepository.removeQuest(partyId) }
}
override fun rejectGroupInvite(groupId: String): Flowable<Void> {
return apiClient.rejectGroupInvite(groupId)
.doOnNext {
localRepository.rejectGroupInvitation(userID, groupId)
}
}
override fun forceStartQuest(party: Group): Flowable<Quest> {
return apiClient.forceStartQuest(party.id, localRepository.getUnmanagedCopy(party))
.doOnNext { localRepository.setQuestActivity(party, true) }
}
override fun getMemberAchievements(userId: String?): Flowable<List<Achievement>> {
return if (userId == null) {
Flowable.empty()
} else apiClient.getMemberAchievements(userId)
}
override fun transferGems(giftedID: String, amount: Int): Flowable<Void> {
return apiClient.transferGems(giftedID, amount)
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/data/implementation/SocialRepositoryImpl.kt | 3458820453 |
package kotlinx.collections.experimental.grouping
public inline fun <T, K, R> Iterable<T>.groupAggregateBy(keySelector: (T) -> K, operation: (key: K, value: R?, element: T, first: Boolean) -> R): Map<K, R> {
val result = mutableMapOf<K, R>()
for (e in this) {
val key = keySelector(e)
val value = result[key]
result[key] = operation(key, value, e, value == null && !result.containsKey(key))
}
return result
}
public inline fun <T, K, R> Iterable<T>.groupFoldBy1(keySelector: (T) -> K, initialValueSelector: (K, T) -> R, operation: (K, R, T) -> R): Map<K, R> =
groupAggregateBy(keySelector) { key, value, e, first -> operation(key, if (first) initialValueSelector(key, e) else value as R, e) }
public inline fun <T, K, R> Iterable<T>.groupFoldBy(crossinline keySelector: (T) -> K): ((key: K, value: R?, element: T, first: Boolean) -> R) -> Map<K, R> = {
operation -> groupAggregateBy(keySelector, operation)
}
public inline fun <T, K, R> Iterable<T>.groupFoldBy(keySelector: (T) -> K, initialValue: R, operation: (R, T) -> R): Map<K, R> =
groupAggregateBy<T, K, R>(keySelector, { k, v, e, first -> operation(if (first) initialValue else v as R, e) })
public inline fun <T, K, R> Iterable<T>.groupReduceBy(keySelector: (T) -> K, reducer: Reducer<R, T>): Map<K, R> =
groupAggregateBy(keySelector, { k, v, e, first -> if (first) reducer.initial(e) else reducer(v as R, e) })
public inline fun <T, K> Iterable<T>.groupCountBy(keySelector: (T) -> K): Map<K, Int> =
groupFoldBy(keySelector, 0, { acc, e -> acc + 1 })
public inline fun <K> IntArray.groupCountBy(keySelector: (Int) -> K): Map<K, Int> {
val result = mutableMapOf<K, Int>()
for (e in this) {
val key = keySelector(e)
val value = result[key]
result[key] = (value ?: 0) + 1
}
return result
}
public inline fun <S, T : S, K> Iterable<T>.groupReduceBy(keySelector: (T) -> K, operation: (K, S, T) -> S): Map<K, S> {
return groupAggregateBy(keySelector) { key, value, e, first ->
if (first) e else operation(key, value as S, e)
}
}
public inline fun <K> Iterable<Int>.groupBySum(keySelector: (Int) -> K): Map<K, Int> =
groupReduceBy(keySelector, { k, sum, e -> sum + e })
public inline fun <T, K> Iterable<T>.groupBySumBy(keySelector: (T) -> K, valueSelector: (T) -> Int): Map<K, Int> =
groupFoldBy(keySelector, 0, { acc, e -> acc + valueSelector(e)})
fun <T, K> Iterable<T>.countBy(keySelector: (T) -> K) =
groupBy(keySelector).mapValues { it.value.fold(0) { acc, e -> acc + 1 } }
fun main(args: Array<String>) {
val values = listOf("apple", "fooz", "bisquit", "abc", "far", "bar", "foo")
val keySelector = { s: String -> s[0] }
val countByChar = values.groupFoldBy(keySelector, 0, { acc, e -> acc + 1 })
val sumLengthByChar: Map<Char, Int> = values.groupAggregateBy({ it[0] }) { k, v, e, first -> v ?: 0 + e.length }
val sumLengthByChar2 = values.groupBySumBy( keySelector, { it.length } )
println(sumLengthByChar2)
val countByChar2 = values.groupCountBy { it.first() }
println(countByChar2)
println(values.groupReduceBy(keySelector, Count))
println(values.groupReduceBy(keySelector, Sum.by { it.length }))
}
| kotlinx-collections-experimental/src/main/kotlin/kotlinx.collections.experimental/grouping/groupFold.kt | 1079177235 |
/*
* Copyright (C) 2017, 2020-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.psi.impl.full.text
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue
import uk.co.reecedunn.intellij.plugin.xpath.ast.full.text.FTScoreVar
import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement
class FTScoreVarPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), FTScoreVar, XpmSyntaxValidationElement {
// region PsiElement
override fun getUseScope(): SearchScope = LocalSearchScope(parent.parent.parent)
// endregion
// region XpmVariableBinding
override val variableName: XsQNameValue?
get() = children().filterIsInstance<XsQNameValue>().firstOrNull()
// endregion
// region XpmSyntaxValidationElement
override val conformanceElement: PsiElement
get() = firstChild
// endregion
}
| src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/full/text/FTScoreVarPsiImpl.kt | 1400701901 |
package de.westnordost.streetcomplete.data.user.achievements
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
/** Provides the user's granted achievements and their level */
@Singleton class UserAchievementsSource @Inject constructor(
private val achievementsDao: UserAchievementsDao,
@Named("Achievements") private val allAchievements: List<Achievement>
) {
private val achievementsById = allAchievements.associateBy { it.id }
fun getAchievements(): List<Pair<Achievement, Int>> {
return achievementsDao.getAll().mapNotNull {
val achievement = achievementsById[it.key]
if (achievement != null) achievement to it.value else null
}
}
} | app/src/main/java/de/westnordost/streetcomplete/data/user/achievements/UserAchievementsSource.kt | 324216965 |
fun foo() : String {
val u = {
class B(val data : String)
B("OK").data
}
return u()
}
fun box(): String {
return foo()
} | backend.native/tests/external/codegen/box/localClasses/kt2873.kt | 1664590776 |
fun main(args : Array<String>) {
var str = "original"
val lambda = {
println(str)
}
lambda()
str = "changed"
lambda()
} | backend.native/tests/codegen/lambda/lambda10.kt | 4182109296 |
package org.stepic.droid.preferences
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import org.stepic.droid.R
import org.stepic.droid.base.App
enum class VideoPlaybackRate(val index: Int, val rateFloat: Float, val icon: Drawable) {
x0_5(0, 0.5f, ContextCompat.getDrawable(App.getAppContext(), R.drawable.ic_playbackrate_0_5_light)!!),
x0_75(1, 0.75f, ContextCompat.getDrawable(App.getAppContext(), R.drawable.ic_playbackrate_0_75_light)!!),
x1_0(2, 1f, ContextCompat.getDrawable(App.getAppContext(), R.drawable.ic_playbackrate_1_light)!!),
x1_25(3, 1.25f, ContextCompat.getDrawable(App.getAppContext(), R.drawable.ic_playbackrate_1_25_light)!!),
x1_5(4, 1.5f, ContextCompat.getDrawable(App.getAppContext(), R.drawable.ic_playbackrate_1_5_light)!!),
x1_75(5, 1.75f, ContextCompat.getDrawable(App.getAppContext(), R.drawable.ic_playbackrate_1_75_light)!!),
x2(6, 2f, ContextCompat.getDrawable(App.getAppContext(), R.drawable.ic_playbackrate_2_0_light)!!); //1.82f should be for 1080p quality for preventing freezes https://github.com/google/ExoPlayer/issues/2777
companion object {
fun getValueById(itemId: Int): VideoPlaybackRate {
return when (itemId) {
R.id.x0_5 -> {
VideoPlaybackRate.x0_5
}
R.id.x0_75 -> {
VideoPlaybackRate.x0_75
}
R.id.x1 -> {
VideoPlaybackRate.x1_0
}
R.id.x1_25 -> {
VideoPlaybackRate.x1_25
}
R.id.x1_5 -> {
VideoPlaybackRate.x1_5
}
R.id.x1_75 -> {
VideoPlaybackRate.x1_75
}
R.id.x2 -> {
VideoPlaybackRate.x2
}
else -> {
throw IllegalArgumentException("itemId was wrong for resolving VideoPlaybackRate")
}
}
}
}
}
| app/src/main/java/org/stepic/droid/preferences/VideoPlaybackRate.kt | 2789202055 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.ide.highlighter.WorkspaceFileType
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.impl.ServiceManagerImpl
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ModuleManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCoreUtil
import com.intellij.openapi.project.ex.ProjectNameProvider
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification
import com.intellij.openapi.project.impl.ProjectStoreClassProvider
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.ReadonlyStatusHandler
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.*
import com.intellij.util.containers.computeIfAny
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.io.*
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.text.nullize
import gnu.trove.THashSet
import org.jdom.Element
import java.io.File
import java.io.IOException
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.Paths
const val PROJECT_FILE = "\$PROJECT_FILE$"
const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$"
val IProjectStore.nameFile: Path
get() = Paths.get(directoryStorePath, ProjectImpl.NAME_FILE)
internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false)
internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true)
abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreImpl(), IProjectStore {
// protected setter used in upsource
// Zelix KlassMaster - ERROR: Could not find method 'getScheme()'
var scheme = StorageScheme.DEFAULT
override final var loadPolicy = StateLoadPolicy.LOAD
override final fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD
override final fun getStorageScheme() = scheme
override abstract val storageManager: StateStorageManagerImpl
protected val isDirectoryBased: Boolean
get() = scheme == StorageScheme.DIRECTORY_BASED
override final fun setOptimiseTestLoadSpeed(value: Boolean) {
// we don't load default state in tests as app store does because
// 1) we should not do it
// 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations)
loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD
}
override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE)
override final fun getWorkspaceFilePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE)
override final fun clearStorages() {
storageManager.clearStorages()
}
override final fun loadProjectFromTemplate(defaultProject: Project) {
defaultProject.save()
val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return
LOG.runAndLogException {
if (isDirectoryBased) {
normalizeDefaultProjectElement(defaultProject, element, Paths.get(storageManager.expandMacro(PROJECT_CONFIG_DIR)))
}
}
(storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element)
}
override final fun getProjectBasePath(): String {
if (isDirectoryBased) {
val path = PathUtilRt.getParentPath(storageManager.expandMacro(PROJECT_CONFIG_DIR))
if (Registry.`is`("store.basedir.parent.detection", true) && PathUtilRt.getFileName(path).startsWith("${Project.DIRECTORY_STORE_FOLDER}.")) {
return PathUtilRt.getParentPath(PathUtilRt.getParentPath(path))
}
return path
}
else {
return PathUtilRt.getParentPath(projectFilePath)
}
}
// used in upsource
protected fun setPath(filePath: String, refreshVfs: Boolean, useOldWorkspaceContentIfExists: Boolean) {
val storageManager = storageManager
val fs = LocalFileSystem.getInstance()
if (filePath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
scheme = StorageScheme.DEFAULT
storageManager.addMacro(PROJECT_FILE, filePath)
val workspacePath = composeWsPath(filePath)
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath)
if (refreshVfs) {
invokeAndWaitIfNeed {
VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath))
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !File(filePath).exists()
}
}
else {
scheme = StorageScheme.DIRECTORY_BASED
// if useOldWorkspaceContentIfExists false, so, file path is expected to be correct (we must avoid file io operations)
val isDir = !useOldWorkspaceContentIfExists || Paths.get(filePath).isDirectory()
val configDir = "${(if (isDir) filePath else PathUtilRt.getParentPath(filePath))}/${Project.DIRECTORY_STORE_FOLDER}"
storageManager.addMacro(PROJECT_CONFIG_DIR, configDir)
storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml")
storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml")
if (!isDir) {
val workspace = File(workspaceFilePath)
if (!workspace.exists()) {
useOldWorkspaceContent(filePath, workspace)
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
// load state only if there are existing files
isOptimiseTestLoadSpeed = !Paths.get(filePath).exists()
}
if (refreshVfs) {
invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) }
}
}
}
override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
if (storages.isEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
if (isDirectoryBased) {
var result: MutableList<Storage>? = null
for (storage in storages) {
if (storage.path != PROJECT_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
result!!.sortWith(deprecatedComparator)
StreamProviderFactory.EP_NAME.getExtensions(project).computeIfAny {
LOG.runAndLogException { it.customizeStorageSpecs(component, project, result!!, operation) }
}?.let {
// yes, DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION is not added in this case
return it
}
// if we create project from default, component state written not to own storage file, but to project file,
// we don't have time to fix it properly, so, ancient hack restored
result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION)
return result
}
}
else {
var result: MutableList<Storage>? = null
// FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry
var hasOnlyDeprecatedStorages = true
for (storage in storages) {
@Suppress("DEPRECATION")
if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE) {
if (result == null) {
result = SmartList()
}
result.add(storage)
if (!storage.deprecated) {
hasOnlyDeprecatedStorages = false
}
}
}
if (result.isNullOrEmpty()) {
return listOf(PROJECT_FILE_STORAGE_ANNOTATION)
}
else {
if (hasOnlyDeprecatedStorages) {
result!!.add(PROJECT_FILE_STORAGE_ANNOTATION)
}
result!!.sortWith(deprecatedComparator)
return result
}
}
}
override fun isProjectFile(file: VirtualFile): Boolean {
if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file)) {
return false
}
val filePath = file.path
if (!isDirectoryBased) {
return filePath == projectFilePath || filePath == workspaceFilePath
}
return FileUtil.isAncestor(PathUtilRt.getParentPath(projectFilePath), filePath, false)
}
override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = if (!ignoreProjectStorageScheme && !isDirectoryBased) null else PathUtilRt.getParentPath(projectFilePath).nullize()
override fun getDirectoryStoreFile() = directoryStorePath?.let { LocalFileSystem.getInstance().findFileByPath(it) }
override fun getDirectoryStorePathOrBase() = PathUtilRt.getParentPath(projectFilePath)
}
private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) {
private var lastSavedProjectName: String? = null
init {
assert(!project.isDefault)
}
override final fun getPathMacroManagerForDefaults() = pathMacroManager
override val storageManager = ProjectStateStorageManager(pathMacroManager.createTrackingSubstitutor(), project)
override fun setPath(filePath: String) {
setPath(filePath, true, true)
}
override fun getProjectName(): String {
if (!isDirectoryBased) {
return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
val baseDir = projectBasePath
val nameFile = nameFile
if (nameFile.exists()) {
LOG.runAndLogException {
nameFile.inputStream().reader().useLines { it.firstOrNull { !it.isEmpty() }?.trim() }?.let {
lastSavedProjectName = it
return it
}
}
}
return ProjectNameProvider.EP_NAME.extensions.computeIfAny {
LOG.runAndLogException { it.getDefaultName(project) }
} ?: PathUtilRt.getFileName(baseDir).replace(":", "")
}
private fun saveProjectName() {
if (!isDirectoryBased) {
return
}
val currentProjectName = project.name
if (lastSavedProjectName == currentProjectName) {
return
}
lastSavedProjectName = currentProjectName
val basePath = projectBasePath
if (currentProjectName == PathUtilRt.getFileName(basePath)) {
// name equals to base path name - just remove name
nameFile.delete()
}
else {
if (Paths.get(basePath).isDirectory()) {
nameFile.write(currentProjectName.toByteArray())
}
}
}
override fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<Pair<SaveSession, VirtualFile>>, prevErrors: MutableList<Throwable>?): MutableList<Throwable>? {
try {
saveProjectName()
}
catch (e: Throwable) {
LOG.error("Unable to store project name", e)
}
var errors = prevErrors
beforeSave(readonlyFiles)
errors = super.doSave(saveSessions, readonlyFiles, errors)
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (readonlyFiles.isEmpty()) {
for (notification in notifications) {
notification.expire()
}
return errors
}
if (!notifications.isEmpty()) {
throw IComponentStore.SaveCancelledException()
}
val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) }
if (status.hasReadonlyFiles()) {
dropUnableToSaveProjectNotification(project, status.readonlyFiles)
throw IComponentStore.SaveCancelledException()
}
val oldList = readonlyFiles.toTypedArray()
readonlyFiles.clear()
for (entry in oldList) {
errors = executeSave(entry.first, readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
if (!readonlyFiles.isEmpty()) {
dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles))
throw IComponentStore.SaveCancelledException()
}
return errors
}
protected open fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
}
}
private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) {
val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
if (notifications.isEmpty()) {
Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project)
}
else {
notifications[0].myFiles = readOnlyFiles
}
}
private fun getFilesList(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) = Array(readonlyFiles.size) { readonlyFiles[it].second }
private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) {
override fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) {
super.beforeSave(readonlyFiles)
for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) {
module.stateStore.save(readonlyFiles)
}
}
}
// used in upsource
class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java
}
}
private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider {
override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> {
return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java
}
}
private fun composeWsPath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}"
private fun useOldWorkspaceContent(filePath: String, ws: File) {
val oldWs = File(composeWsPath(filePath))
if (!oldWs.exists()) {
return
}
try {
FileUtil.copyContent(oldWs, ws)
}
catch (e: IOException) {
LOG.error(e)
}
}
private fun moveComponentConfiguration(defaultProject: Project, element: Element, projectConfigDir: Path) {
val componentElements = element.getChildren("component")
if (componentElements.isEmpty()) {
return
}
val workspaceComponentNames = THashSet(listOf("GradleLocalSettings"))
val compilerComponentNames = THashSet<String>()
fun processComponents(aClass: Class<*>) {
val stateAnnotation = StoreUtil.getStateSpec(aClass)
if (stateAnnotation == null || stateAnnotation.name.isEmpty()) {
return
}
val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return
when {
storage.path == StoragePathMacros.WORKSPACE_FILE -> workspaceComponentNames.add(stateAnnotation.name)
storage.path == "compiler.xml" -> compilerComponentNames.add(stateAnnotation.name)
}
}
@Suppress("DEPRECATION")
val projectComponents = defaultProject.getComponents(PersistentStateComponent::class.java)
projectComponents.forEachGuaranteed {
processComponents(it.javaClass)
}
ServiceManagerImpl.processAllImplementationClasses(defaultProject as ProjectImpl) { aClass, _ ->
processComponents(aClass)
true
}
@Suppress("RemoveExplicitTypeArguments")
val elements = mapOf(compilerComponentNames to SmartList<Element>(), workspaceComponentNames to SmartList<Element>())
val iterator = componentElements.iterator()
for (componentElement in iterator) {
val name = componentElement.getAttributeValue("name") ?: continue
for ((names, list) in elements) {
if (names.contains(name)) {
iterator.remove()
list.add(componentElement)
}
}
}
for ((names, list) in elements) {
writeConfigFile(list, projectConfigDir.resolve(if (names === workspaceComponentNames) "workspace.xml" else "compiler.xml"))
}
}
private fun writeConfigFile(elements: List<Element>, file: Path) {
if (elements.isEmpty()) {
return
}
var wrapper = Element("project").attribute("version", "4")
if (file.exists()) {
try {
wrapper = loadElement(file)
}
catch (e: Exception) {
LOG.warn(e)
}
}
elements.forEach { wrapper.addContent(it) }
// .idea component configuration files uses XML prolog due to historical reasons
if (file.fileSystem == FileSystems.getDefault()) {
// VFS must be used to write workspace.xml and misc.xml to ensure that project files will be not reloaded on external file change event
writeFile(file, SaveSession { }, null, wrapper, LineSeparator.LF, prependXmlProlog = true)
}
else {
file.outputStream().use {
it.write(XML_PROLOG)
it.write(LineSeparator.LF.separatorBytes)
wrapper.write(it)
}
}
}
// public only to test
fun normalizeDefaultProjectElement(defaultProject: Project, element: Element, projectConfigDir: Path) {
LOG.runAndLogException {
moveComponentConfiguration(defaultProject, element, projectConfigDir)
}
LOG.runAndLogException {
val iterator = element.getChildren("component").iterator()
for (component in iterator) {
val componentName = component.getAttributeValue("name")
fun writeProfileSettings(schemeDir: Path) {
component.removeAttribute("name")
if (!component.isEmpty()) {
val wrapper = Element("component").attribute("name", componentName)
component.name = "settings"
wrapper.addContent(component)
val file = schemeDir.resolve("profiles_settings.xml")
if (file.fileSystem == FileSystems.getDefault()) {
// VFS must be used to write workspace.xml and misc.xml to ensure that project files will be not reloaded on external file change event
writeFile(file, SaveSession { }, null, wrapper, LineSeparator.LF, prependXmlProlog = false)
}
else {
file.outputStream().use {
wrapper.write(it)
}
}
}
}
when (componentName) {
"InspectionProjectProfileManager" -> {
iterator.remove()
val schemeDir = projectConfigDir.resolve("inspectionProfiles")
convertProfiles(component.getChildren("profile").iterator(), componentName, schemeDir)
component.removeChild("version")
writeProfileSettings(schemeDir)
}
"CopyrightManager" -> {
iterator.remove()
val schemeDir = projectConfigDir.resolve("copyright")
convertProfiles(component.getChildren("copyright").iterator(), componentName, schemeDir)
writeProfileSettings(schemeDir)
}
ModuleManagerImpl.COMPONENT_NAME -> {
iterator.remove()
}
}
}
}
}
private fun convertProfiles(profileIterator: MutableIterator<Element>, componentName: String, schemeDir: Path) {
for (profile in profileIterator) {
val schemeName = profile.getChildren("option").find { it.getAttributeValue("name") == "myName" }?.getAttributeValue("value") ?: continue
profileIterator.remove()
val wrapper = Element("component").attribute("name", componentName)
wrapper.addContent(profile)
val path = schemeDir.resolve("${FileUtil.sanitizeFileName(schemeName, true)}.xml")
JDOMUtil.write(wrapper, path.outputStream(), "\n")
}
} | platform/configuration-store-impl/src/ProjectStoreImpl.kt | 2432246701 |
/*
Copyright (C) 2020 Matthew Chandler
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.mattvchandler.progressbars.db
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.provider.BaseColumns
import androidx.preference.PreferenceManager
import org.mattvchandler.progressbars.R
// DB Table schema
open class Progress_bars_table: BaseColumns
{
// associated enums
enum class Days_of_week (val index: Int, val mask: Int)
{
SUNDAY(0, 0x01),
MONDAY(1, 0x02),
TUESDAY(2, 0x04),
WEDNESDAY(3, 0x08),
THURSDAY(4, 0x10),
FRIDAY(5, 0x20),
SATURDAY(6, 0x40);
companion object
{
fun all_days_mask(): Int
{
return SUNDAY.mask or MONDAY.mask or TUESDAY.mask or WEDNESDAY.mask or THURSDAY.mask or FRIDAY.mask or SATURDAY.mask
}
}
}
enum class Unit(val index: Int)
{
SECOND(0),
MINUTE(1),
HOUR(2),
DAY(3),
WEEK(4),
MONTH(5),
YEAR(6)
}
companion object
{
const val TABLE_NAME = "progress_bar"
const val ID_COL = "id"
const val ORDER_COL = "order_ind"
const val WIDGET_ID_COL = "widget_id"
const val SEPARATE_TIME_COL = "separate_time"
const val START_TIME_COL = "start_time"
const val START_TZ_COL = "start_tz"
const val END_TIME_COL = "end_time"
const val END_TZ_COL = "end_tz"
const val REPEATS_COL = "repeats"
const val REPEAT_COUNT_COL = "repeat_count"
const val REPEAT_UNIT_COL = "repeat_unit"
const val REPEAT_DAYS_OF_WEEK_COL = "repeat_days_of_week"
const val TITLE_COL = "title"
const val PRE_TEXT_COL = "pre_text"
const val START_TEXT_COL = "start_text"
const val COUNTDOWN_TEXT_COL = "countdown_text"
const val COMPLETE_TEXT_COL = "complete_text"
const val POST_TEXT_COL = "post_text"
const val SINGLE_PRE_TEXT_COL = "single_pre_text"
const val SINGLE_COMPLETE_TEXT_COL = "single_complete_text"
const val SINGLE_POST_TEXT_COL = "single_post_text"
const val PRECISION_COL = "precision"
const val SHOW_START_COL = "show_start"
const val SHOW_END_COL = "show_end"
const val SHOW_PROGRESS_COL = "show_progress"
const val SHOW_YEARS_COL = "show_years"
const val SHOW_MONTHS_COL = "show_months"
const val SHOW_WEEKS_COL = "show_weeks"
const val SHOW_DAYS_COL = "show_days"
const val SHOW_HOURS_COL = "show_hours"
const val SHOW_MINUTES_COL = "show_minutes"
const val SHOW_SECONDS_COL = "show_seconds"
const val TERMINATE_COL = "terminate"
const val NOTIFY_START_COL = "notify_start"
const val NOTIFY_END_COL = "notify_end"
const val HAS_NOTIFICATION_CHANNEL_COL = "has_notification_channel"
const val NOTIFICATION_PRIORITY_COL = "notification_priority"
const val SELECT_ALL_ROWS = "SELECT * FROM $TABLE_NAME ORDER BY $ORDER_COL, $WIDGET_ID_COL"
const val SELECT_ALL_ROWS_NO_WIDGET = "SELECT * FROM $TABLE_NAME WHERE $WIDGET_ID_COL IS NULL ORDER BY $ORDER_COL"
const val SELECT_ALL_WIDGETS = "SELECT * FROM $TABLE_NAME WHERE $WIDGET_ID_COL IS NOT NULL ORDER BY $WIDGET_ID_COL"
const val SELECT_WIDGET = "SELECT * FROM $TABLE_NAME WHERE $WIDGET_ID_COL = ?"
// table schema
const val CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
ID_COL + " INTEGER UNIQUE NOT NULL, " +
ORDER_COL + " INTEGER UNIQUE, " +
WIDGET_ID_COL + " INTEGER UNIQUE, " +
SEPARATE_TIME_COL + " INTEGER NOT NULL, " +
START_TIME_COL + " INTEGER NOT NULL, " +
START_TZ_COL + " TEXT NOT NULL, " +
END_TIME_COL + " INTEGER NOT NULL, " +
END_TZ_COL + " TEXT NOT NULL, " +
REPEATS_COL + " INTEGER NOT NULL, " +
REPEAT_COUNT_COL + " INTEGER NOT NULL, " +
REPEAT_UNIT_COL + " INTEGER NOT NULL, " +
REPEAT_DAYS_OF_WEEK_COL + " INTEGER NOT NULL, " +
TITLE_COL + " TEXT NOT NULL, " +
PRE_TEXT_COL + " TEXT NOT NULL, " +
START_TEXT_COL + " TEXT NOT NULL, " +
COUNTDOWN_TEXT_COL + " TEXT NOT NULL, " +
COMPLETE_TEXT_COL + " TEXT NOT NULL, " +
POST_TEXT_COL + " TEXT NOT NULL, " +
SINGLE_PRE_TEXT_COL + " TEXT NOT NULL, " +
SINGLE_COMPLETE_TEXT_COL + " TEXT NOT NULL, " +
SINGLE_POST_TEXT_COL + " TEXT NOT NULL, " +
PRECISION_COL + " INTEGER NOT NULL, " +
SHOW_START_COL + " INTEGER NOT NULL, " +
SHOW_END_COL + " INTEGER NOT NULL, " +
SHOW_PROGRESS_COL + " INTEGER NOT NULL, " +
SHOW_YEARS_COL + " INTEGER NOT NULL, " +
SHOW_MONTHS_COL + " INTEGER NOT NULL, " +
SHOW_WEEKS_COL + " INTEGER NOT NULL, " +
SHOW_DAYS_COL + " INTEGER NOT NULL, " +
SHOW_HOURS_COL + " INTEGER NOT NULL, " +
SHOW_MINUTES_COL + " INTEGER NOT NULL, " +
SHOW_SECONDS_COL + " INTEGER NOT NULL, " +
TERMINATE_COL + " INTEGER NOT NULL, " +
NOTIFY_START_COL + " INTEGER NOT NULL, " +
NOTIFY_END_COL + " INTEGER NOT NULL, " +
HAS_NOTIFICATION_CHANNEL_COL + " INTEGER NOT NULL, " +
NOTIFICATION_PRIORITY_COL + " TEXT NOT NULL)"
fun upgrade(context: Context, db: SQLiteDatabase, old_version: Int)
{
val table_exists = db.query("sqlite_master", arrayOf("name"), "type = 'table' AND name = ?", arrayOf(TABLE_NAME), null, null, null)
if(table_exists.count == 0)
{
db.execSQL(CREATE_TABLE)
return
}
fun set_new_id()
{
val cursor = db.rawQuery("SELECT MAX($ID_COL) from $TABLE_NAME", null)
cursor.moveToFirst()
val count = cursor.getInt(0)
cursor.close()
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(context.resources.getString(R.string.pref_next_id_key), count + 1).apply()
}
when(old_version)
{
1 ->
{
// Added some new columns - copy old data and insert defaults for new columns
db.execSQL("ALTER TABLE $TABLE_NAME RENAME TO TMP_$TABLE_NAME")
db.execSQL(CREATE_TABLE)
db.execSQL("INSERT INTO " + TABLE_NAME +
"(" +
ID_COL + ", " +
ORDER_COL + ", " +
WIDGET_ID_COL + ", " +
SEPARATE_TIME_COL + ", " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
REPEATS_COL + ", " +
REPEAT_COUNT_COL + ", " +
REPEAT_UNIT_COL + ", " +
REPEAT_DAYS_OF_WEEK_COL + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
SINGLE_PRE_TEXT_COL + ", " +
SINGLE_COMPLETE_TEXT_COL + ", " +
SINGLE_POST_TEXT_COL + ", " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
HAS_NOTIFICATION_CHANNEL_COL + ", " +
NOTIFICATION_PRIORITY_COL +
")" +
" SELECT " +
ORDER_COL + ", " + // using order for id
ORDER_COL + ", " +
"NULL, " +
"1, " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
"0, " +
"1, " +
Unit.DAY.index.toString() + ", " +
Days_of_week.all_days_mask().toString() + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
"'" + context.getString(R.string.default_single_pre_text) + "', " +
"'" + context.getString(R.string.default_single_complete_text) + "', " +
"'" + context.getString(R.string.default_single_post_text) + "', " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
"0, " +
"'HIGH' " +
"FROM TMP_" + TABLE_NAME)
db.execSQL("DROP TABLE TMP_$TABLE_NAME")
set_new_id()
}
2, 3 ->
{
// 2 -> 3 fixed NOT NULL for some columns - copy all data over
// 3 -> 4 add SEPARATE_TIME_COL, countdown text for single time, ID col, notification channel
db.execSQL("ALTER TABLE $TABLE_NAME RENAME TO TMP_$TABLE_NAME")
db.execSQL(CREATE_TABLE)
db.execSQL("INSERT INTO " + TABLE_NAME +
"(" +
ID_COL + ", " +
ORDER_COL + ", " +
WIDGET_ID_COL + ", " +
SEPARATE_TIME_COL + ", " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
REPEATS_COL + ", " +
REPEAT_COUNT_COL + ", " +
REPEAT_UNIT_COL + ", " +
REPEAT_DAYS_OF_WEEK_COL + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
SINGLE_PRE_TEXT_COL + ", " +
SINGLE_COMPLETE_TEXT_COL + ", " +
SINGLE_POST_TEXT_COL + ", " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
HAS_NOTIFICATION_CHANNEL_COL + ", " +
NOTIFICATION_PRIORITY_COL +
")" +
" SELECT " +
ORDER_COL + ", " + // using order for id
ORDER_COL + ", " +
"NULL, " +
"1, " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
REPEATS_COL + ", " +
REPEAT_COUNT_COL + ", " +
REPEAT_UNIT_COL + ", " +
REPEAT_DAYS_OF_WEEK_COL + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
"'" + context.getString(R.string.default_single_pre_text) + "', " +
"'" + context.getString(R.string.default_single_complete_text) + "', " +
"'" + context.getString(R.string.default_single_post_text) + "', " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
"0, " +
"'HIGH' " +
"FROM TMP_" + TABLE_NAME)
db.execSQL("DROP TABLE TMP_$TABLE_NAME")
set_new_id()
}
4 ->
{
db.execSQL("ALTER TABLE $TABLE_NAME RENAME TO TMP_$TABLE_NAME")
db.execSQL(CREATE_TABLE)
db.execSQL("INSERT INTO " + TABLE_NAME +
"(" +
ID_COL + ", " +
ORDER_COL + ", " +
WIDGET_ID_COL + ", " +
SEPARATE_TIME_COL + ", " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
REPEATS_COL + ", " +
REPEAT_COUNT_COL + ", " +
REPEAT_UNIT_COL + ", " +
REPEAT_DAYS_OF_WEEK_COL + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
SINGLE_PRE_TEXT_COL + ", " +
SINGLE_COMPLETE_TEXT_COL + ", " +
SINGLE_POST_TEXT_COL + ", " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
HAS_NOTIFICATION_CHANNEL_COL + ", " +
NOTIFICATION_PRIORITY_COL +
")" +
" SELECT " +
ID_COL + ", " +
ORDER_COL + ", " +
"NULL, " +
SEPARATE_TIME_COL + ", " +
START_TIME_COL + ", " +
END_TIME_COL + ", " +
START_TZ_COL + ", " +
END_TZ_COL + ", " +
REPEATS_COL + ", " +
REPEAT_COUNT_COL + ", " +
REPEAT_UNIT_COL + ", " +
REPEAT_DAYS_OF_WEEK_COL + ", " +
TITLE_COL + ", " +
PRE_TEXT_COL + ", " +
START_TEXT_COL + ", " +
COUNTDOWN_TEXT_COL + ", " +
COMPLETE_TEXT_COL + ", " +
POST_TEXT_COL + ", " +
SINGLE_PRE_TEXT_COL + ", " +
SINGLE_COMPLETE_TEXT_COL + ", " +
SINGLE_POST_TEXT_COL + ", " +
PRECISION_COL + ", " +
SHOW_START_COL + ", " +
SHOW_END_COL + ", " +
SHOW_PROGRESS_COL + ", " +
SHOW_YEARS_COL + ", " +
SHOW_MONTHS_COL + ", " +
SHOW_WEEKS_COL + ", " +
SHOW_DAYS_COL + ", " +
SHOW_HOURS_COL + ", " +
SHOW_MINUTES_COL + ", " +
SHOW_SECONDS_COL + ", " +
TERMINATE_COL + ", " +
NOTIFY_START_COL + ", " +
NOTIFY_END_COL + ", " +
HAS_NOTIFICATION_CHANNEL_COL + ", " +
NOTIFICATION_PRIORITY_COL + " " +
"FROM TMP_" + TABLE_NAME)
db.execSQL("DROP TABLE TMP_$TABLE_NAME")
set_new_id()
}
else ->
{
db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
db.execSQL(CREATE_TABLE)
}
}
table_exists.close()
}
}
}
| app/src/main/java/db/Progress_bars_table.kt | 1134914009 |
package net.ndrei.bushmaster.api
import net.minecraft.block.state.IBlockState
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
interface IHarvestableFactory {
fun getHarvestable(world: World, pos: BlockPos): IHarvestable? =
getHarvestable(world, pos, world.getBlockState(pos))
fun getHarvestable(world: World, pos: BlockPos, state: IBlockState): IHarvestable?
} | src/api/kotlin/net/ndrei/bushmaster/api/IHarvestableFactory.kt | 3644699231 |
package abi43_0_0.expo.modules.clipboard
import android.content.Context
import android.content.ClipboardManager
import android.os.Bundle
import android.util.Log
import abi43_0_0.expo.modules.core.ModuleRegistry
import abi43_0_0.expo.modules.core.interfaces.LifecycleEventListener
import abi43_0_0.expo.modules.core.interfaces.services.EventEmitter
import abi43_0_0.expo.modules.core.interfaces.services.UIManager
class ClipboardEventEmitter(context: Context, moduleRegistry: ModuleRegistry) : LifecycleEventListener {
private val onClipboardEventName = "onClipboardChanged"
private var isListening = true
private var eventEmitter = moduleRegistry.getModule(EventEmitter::class.java)
init {
moduleRegistry.getModule(UIManager::class.java).registerLifecycleEventListener(this)
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
if (clipboard == null) {
Log.e("Clipboard", "CLIPBOARD_SERVICE unavailable. Events wont be received")
} else {
clipboard.addPrimaryClipChangedListener {
if (isListening) {
val clip = clipboard.primaryClip
if (clip != null && clip.itemCount >= 1) {
eventEmitter.emit(
onClipboardEventName,
Bundle().apply {
putString("content", clip.getItemAt(0).text.toString())
}
)
}
}
}
}
}
override fun onHostResume() {
isListening = true
}
override fun onHostPause() {
isListening = false
}
override fun onHostDestroy() = Unit
}
| android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/clipboard/ClipboardEventEmitter.kt | 4244252006 |
/*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.squareup.wire.internal.EnumJsonFormatter
import java.io.IOException
internal class EnumTypeAdapter<E>(
private val enumJsonFormatter: EnumJsonFormatter<E>,
) : TypeAdapter<E>() where E : Enum<E>, E : WireEnum {
@Throws(IOException::class)
override fun write(out: JsonWriter, value: E) {
out.value(enumJsonFormatter.toStringOrNumber(value))
}
@Throws(IOException::class)
override fun read(input: JsonReader): E {
val path: String = input.path
val nextString = input.nextString()
return enumJsonFormatter.fromString(nextString)
?: throw IOException("Unexpected $nextString at path $path")
}
}
| wire-library/wire-gson-support/src/main/java/com/squareup/wire/EnumTypeAdapter.kt | 760622330 |
package io.github.notsyncing.lightfur.integration.vertx.ql.tests
import io.github.notsyncing.lightfur.entity.dsl.EntitySelectDSL
import io.github.notsyncing.lightfur.integration.vertx.ql.VertxRawQueryProcessor
import io.github.notsyncing.lightfur.integration.vertx.ql.tests.toys.UserContactDetailsModel
import io.github.notsyncing.lightfur.integration.vertx.ql.tests.toys.UserContactInfoModel
import io.github.notsyncing.lightfur.ql.QueryExecutor
import io.github.notsyncing.lightfur.integration.vertx.ql.tests.toys.UserModel
import io.vertx.core.json.JsonArray
import io.vertx.kotlin.ext.sql.ResultSet
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.concurrent.CompletableFuture
class QueryExecutorTest {
private val simpleQuery: String
private val nestedQuery: String
private val deepQuery: String
init {
simpleQuery = javaClass.getResourceAsStream("/testSimple.json").bufferedReader().use { it.readText() }
nestedQuery = javaClass.getResourceAsStream("/testNested.json").bufferedReader().use { it.readText() }
deepQuery = javaClass.getResourceAsStream("/testDeep.json").bufferedReader().use { it.readText() }
QueryExecutor.setRawQueryProcessor { VertxRawQueryProcessor() }
}
@Test
fun testExecuteSimpleQuery() {
val q = QueryExecutor()
val m = UserModel()
q.parser.modelMap[UserModel::class.java.name + "_user"] = m
val h = m.hashCode()
val modelPrefix = UserModel::class.java.simpleName + "_${h}"
q.javaClass.getDeclaredField("_queryFunction").apply { this.isAccessible = true }.set(q) { _: EntitySelectDSL<*> ->
val columnNames = listOf("${modelPrefix}_id",
"${modelPrefix}_username",
"${modelPrefix}_mobile",
"${modelPrefix}_lastLoginTime",
"${modelPrefix}_status")
val data = mutableListOf<JsonArray>()
data.add(JsonArray(listOf(4, "133test1", "12345", "2017-01-01", 2)))
data.add(JsonArray(listOf(5, "133test2", "23456", "2017-01-02", 3)))
data.add(JsonArray(listOf(6, "133test3", "34567", "2017-01-03", 5)))
CompletableFuture.completedFuture(ResultSet(columnNames, null, null, data))
}
val data = q.execute(simpleQuery).get()
val expected = """{"user":[{"lastLogin":"2017-01-01","mobile":"12345","id":4,"username":"133test1","status":2},{"lastLogin":"2017-01-02","mobile":"23456","id":5,"username":"133test2","status":3},{"lastLogin":"2017-01-03","mobile":"34567","id":6,"username":"133test3","status":5}]}"""
assertEquals(expected, data.toJSONString())
}
@Test
fun testExecuteNestedQuery() {
val q = QueryExecutor()
val m1 = UserModel()
val m2 = UserContactInfoModel()
q.parser.modelMap[UserModel::class.java.name + "_user"] = m1
q.parser.modelMap[UserContactInfoModel::class.java.name + "_user.contacts"] = m2
val h1 = m1.hashCode()
val h2 = m2.hashCode()
val model1Prefix = UserModel::class.java.simpleName + "_${h1}"
val model2Prefix = UserContactInfoModel::class.java.simpleName + "_${h2}"
q.javaClass.getDeclaredField("_queryFunction").apply { this.isAccessible = true }.set(q) { _: EntitySelectDSL<*> ->
val columnNames = listOf("${model1Prefix}_id",
"${model1Prefix}_username",
"${model1Prefix}_mobile",
"${model1Prefix}_lastLoginTime",
"${model1Prefix}_status",
"${model2Prefix}_userId",
"${model2Prefix}_id",
"${model2Prefix}_mobile",
"${model2Prefix}_default")
val data = mutableListOf<JsonArray>()
data.add(JsonArray(listOf(4, "133test1", "12345", "2017-01-01", 2, 4, 1, "54321", true)))
data.add(JsonArray(listOf(4, "133test1", "12345", "2017-01-01", 2, 4, 2, "65432", true)))
data.add(JsonArray(listOf(5, "133test2", "23456", "2017-01-02", 3, 5, 3, "76543", true)))
data.add(JsonArray(listOf(5, "133test2", "23456", "2017-01-02", 3, 5, 4, "87654", true)))
data.add(JsonArray(listOf(5, "133test2", "23456", "2017-01-02", 3, 5, 5, "98765", true)))
data.add(JsonArray(listOf(6, "133test3", "34567", "2017-01-03", 5, 6, 6, "09876", true)))
CompletableFuture.completedFuture(ResultSet(columnNames, null, null, data))
}
val data = q.execute(nestedQuery).get()
val expected = """{"user":[{"lastLogin":"2017-01-01","mobile":"12345","id":4,"username":"133test1","status":2,"contacts":[{"default":true,"mobile":"54321","id":1,"userId":4},{"default":true,"mobile":"65432","id":2,"userId":4}]},{"lastLogin":"2017-01-02","mobile":"23456","id":5,"username":"133test2","status":3,"contacts":[{"default":true,"mobile":"76543","id":3,"userId":5},{"default":true,"mobile":"87654","id":4,"userId":5},{"default":true,"mobile":"98765","id":5,"userId":5}]},{"lastLogin":"2017-01-03","mobile":"34567","id":6,"username":"133test3","status":5,"contacts":[{"default":true,"mobile":"09876","id":6,"userId":6}]}]}"""
assertEquals(expected, data.toJSONString())
}
@Test
fun testExecuteDeepQuery() {
val q = QueryExecutor()
val m1 = UserModel()
val m2 = UserContactInfoModel()
val m3 = UserContactDetailsModel()
q.parser.modelMap[UserModel::class.java.name + "_user"] = m1
q.parser.modelMap[UserContactInfoModel::class.java.name + "_user.contacts"] = m2
q.parser.modelMap[UserContactDetailsModel::class.java.name + "_user.contacts.details"] = m3
val h1 = m1.hashCode()
val h2 = m2.hashCode()
val h3 = m3.hashCode()
val model1Prefix = UserModel::class.java.simpleName + "_${h1}"
val model2Prefix = UserContactInfoModel::class.java.simpleName + "_${h2}"
val model3Prefix = UserContactDetailsModel::class.java.simpleName + "_${h3}"
q.javaClass.getDeclaredField("_queryFunction").apply { this.isAccessible = true }.set(q) { _: EntitySelectDSL<*> ->
val columnNames = listOf("${model1Prefix}_id",
"${model1Prefix}_username",
"${model1Prefix}_mobile",
"${model1Prefix}_lastLoginTime",
"${model1Prefix}_status",
"${model2Prefix}_userId",
"${model2Prefix}_id",
"${model2Prefix}_mobile",
"${model2Prefix}_default",
"${model3Prefix}_id",
"${model3Prefix}_contactInfoId",
"${model3Prefix}_comment")
val data = mutableListOf<JsonArray>()
data.add(JsonArray(listOf(4, "133test1", "12345", "2017-01-01", 2, 4, 1, "54321", true, 10, 1, "testA")))
data.add(JsonArray(listOf(4, "133test1", "12345", "2017-01-01", 2, 4, 1, "54321", true, 11, 1, "testB")))
data.add(JsonArray(listOf(4, "133test1", "12345", "2017-01-01", 2, 4, 2, "65432", true, 12, 2, "testC")))
data.add(JsonArray(listOf(4, "133test1", "12345", "2017-01-01", 2, 4, 2, "65432", true, 13, 2, "testD")))
data.add(JsonArray(listOf(4, "133test1", "12345", "2017-01-01", 2, 4, 2, "65432", true, 14, 2, "testE")))
data.add(JsonArray(listOf(5, "133test2", "23456", "2017-01-02", 3, 5, 3, "76543", true, 15, 3, "testF")))
data.add(JsonArray(listOf(5, "133test2", "23456", "2017-01-02", 3, 5, 3, "76543", true, 16, 3, "testG")))
data.add(JsonArray(listOf(5, "133test2", "23456", "2017-01-02", 3, 5, 3, "76543", true, 17, 3, "testH")))
data.add(JsonArray(listOf(5, "133test2", "23456", "2017-01-02", 3, 5, 4, "87654", true, 18, 4, "testI")))
data.add(JsonArray(listOf(5, "133test2", "23456", "2017-01-02", 3, 5, 5, "98765", true, 19, 5, "testJ")))
data.add(JsonArray(listOf(6, "133test3", "34567", "2017-01-03", 5, 6, 6, "09876", true, 20, 6, "testK")))
data.add(JsonArray(listOf(6, "133test3", "34567", "2017-01-03", 5, 6, 6, "09876", true, 21, 6, "testL")))
CompletableFuture.completedFuture(ResultSet(columnNames, null, null, data))
}
val data = q.execute(deepQuery).get()
val expected = """{"user":[{"lastLogin":"2017-01-01","mobile":"12345","id":4,"username":"133test1","status":2,"contacts":[{"default":true,"mobile":"54321","id":1,"userId":4,"details":[{"contactInfoId":1,"comment":"testA","id":10},{"contactInfoId":1,"comment":"testB","id":11}]},{"default":true,"mobile":"65432","id":2,"userId":4,"details":[{"contactInfoId":2,"comment":"testC","id":12},{"contactInfoId":2,"comment":"testD","id":13},{"contactInfoId":2,"comment":"testE","id":14}]}]},{"lastLogin":"2017-01-02","mobile":"23456","id":5,"username":"133test2","status":3,"contacts":[{"default":true,"mobile":"76543","id":3,"userId":5,"details":[{"contactInfoId":3,"comment":"testF","id":15},{"contactInfoId":3,"comment":"testG","id":16},{"contactInfoId":3,"comment":"testH","id":17}]},{"default":true,"mobile":"87654","id":4,"userId":5,"details":[{"contactInfoId":4,"comment":"testI","id":18}]},{"default":true,"mobile":"98765","id":5,"userId":5,"details":[{"contactInfoId":5,"comment":"testJ","id":19}]}]},{"lastLogin":"2017-01-03","mobile":"34567","id":6,"username":"133test3","status":5,"contacts":[{"default":true,"mobile":"09876","id":6,"userId":6,"details":[{"contactInfoId":6,"comment":"testK","id":20},{"contactInfoId":6,"comment":"testL","id":21}]}]}]}"""
assertEquals(expected, data.toJSONString())
}
} | lightfur-integration-vertx-ql/src/test/kotlin/io/github/notsyncing/lightfur/integration/vertx/ql/tests/QueryExecutorTest.kt | 2820597003 |
package com.intellij.ide.starter.ide
import com.intellij.ide.starter.models.IdeInfo
interface IdeInstallator {
fun install(ideInfo: IdeInfo): Pair<String, InstalledIDE>
} | tools/intellij.ide.starter/src/com/intellij/ide/starter/ide/IdeInstallator.kt | 1298517317 |
package bz.stewart.bracken.db.bill.database.mongodb
import bz.stewart.bracken.db.bill.RuntimeMode
import bz.stewart.bracken.db.bill.data.Bill
import bz.stewart.bracken.db.bill.index.BillIndexDefinition
import bz.stewart.bracken.db.database.DatabaseClient
import bz.stewart.bracken.db.database.Transaction
import bz.stewart.bracken.db.database.index.InlineSyncIndex
import bz.stewart.bracken.db.database.mongo.AbstractMongoDb
import bz.stewart.bracken.db.database.mongo.CollectionWriter
import bz.stewart.bracken.db.debug.DebugUtils
import com.mongodb.MongoClient
import com.mongodb.MongoCommandException
import com.mongodb.MongoTimeoutException
import com.mongodb.MongoWriteException
import mu.KLogging
import java.io.File
/**
* Created by stew on 3/12/17.
*/
class MongoTransaction(val dbClient: DatabaseClient<MongoClient>,
val data: File,
val test: Boolean,
val mode: RuntimeMode,
val congressParseLimit: Set<Int>) : Transaction<Bill, AbstractMongoDb<Bill>> {
companion object : KLogging()
private var writer: CollectionWriter<Bill, AbstractMongoDb<Bill>>? = null
private var db: BillJsonDataDatabase? = null
private var startedTransaction: Boolean = false
override fun setWriter(writer: CollectionWriter<Bill, AbstractMongoDb<Bill>>) {
this.writer = writer
}
override fun beginTransaction() {
val writer = when (test) {
true -> emptyBillWriter()
false -> SingleBillWriter()
}
val collName = "bills"
db = BillJsonDataDatabase(this.data, this.dbClient, collName, mode, test, writer)
logger.info { "Loading bill into database@${this.dbClient.databaseName} in collection@$collName with mode@$mode and test@$test" }
db!!.openDatabase()
startedTransaction = true
}
override fun execute() {
if (!startedTransaction) {
throw IllegalStateException("trying to run MongoTransaction before calling beginTransaction() or before starting successfully.")
}
val db = this.db ?: return
try {
db.loadData(if (congressParseLimit.isEmpty()) null else congressParseLimit.map(Int::toString))//todo move this write logic to a writer
InlineSyncIndex(db, { BillIndexDefinition(it) }).doSync(this.test)
} catch (e: MongoCommandException) {
abort("Mongo exception: ${DebugUtils.stackTraceToString(e)}")
} catch (e: MongoWriteException) {
abort("Mongo write error: $e @ $e")
} catch (e: MongoTimeoutException) {
logger.error { "Timeout while connecting to the database. Is mongod running? @ $e" }
abort("Aborting due to mongod timeout @ $e")
} catch (e: RuntimeException) {
abort("Unknown error, this should be fixed:\n\n ${DebugUtils.stackTraceToString(e)}")
}
}
override fun endTransaction() {
if (startedTransaction) {
db!!.closeDatabase()
}
startedTransaction = false
}
override fun abort(msg: String) {
logger.error { "Aborting transaction: $msg" }
endTransaction()
error("Aborting transaction.")
}
} | db/src/main/kotlin/bz/stewart/bracken/db/bill/database/mongodb/MongoTransaction.kt | 1327100476 |
package com.bajdcc.LALR1.grammar.runtime.service
import com.bajdcc.LALR1.grammar.runtime.RuntimeObject
import com.bajdcc.LALR1.grammar.runtime.data.RuntimeArray
import org.apache.log4j.Logger
/**
* 【运行时】运行时共享服务
*
* @author bajdcc
*/
class RuntimeShareService(private val service: RuntimeService) : IRuntimeShareService {
private val mapShares = mutableMapOf<String, ShareStruct>()
internal data class ShareStruct(var name: String, var obj: RuntimeObject, var page: String,
var reference: Int = 1, var locked: Boolean = false) {
val objType: String
get() = obj.type.desc
}
override fun startSharing(name: String, obj: RuntimeObject, page: String): Int {
if (mapShares.size >= MAX_SHARING)
return -1
if (mapShares.containsKey(name))
return 0
mapShares[name] = ShareStruct(name, obj, page)
logger.debug("Sharing '$name' created")
return 1
}
override fun createSharing(name: String, obj: RuntimeObject, page: String): Int {
if (mapShares.size >= MAX_SHARING)
return -1
mapShares[name] = ShareStruct(name, obj, page)
logger.debug("Sharing '$name' created")
return 1
}
override fun getSharing(name: String, reference: Boolean): RuntimeObject {
val ss = mapShares[name]
if (ss != null) {
if (reference)
ss.reference++
return ss.obj
}
return RuntimeObject(null)
}
override fun stopSharing(name: String): Int {
if (!mapShares.containsKey(name))
return -1
val ss = mapShares[name]!!
ss.reference--
if (ss.reference == 0) {
mapShares.remove(name)
return 1
}
return if (ss.reference < 0) {
2
} else 0
}
override fun isLocked(name: String): Boolean {
return mapShares.containsKey(name) && mapShares[name]!!.locked
}
override fun setLocked(name: String, lock: Boolean) {
if (mapShares.containsKey(name))
mapShares[name]!!.locked = lock
}
override fun size(): Long {
return mapShares.size.toLong()
}
override fun stat(api: Boolean): RuntimeArray {
val array = RuntimeArray()
if (api) {
mapShares.values.sortedBy { it.objType }.sortedBy { it.name }
.forEach { value ->
val item = RuntimeArray()
item.add(RuntimeObject(value.name))
item.add(RuntimeObject(value.obj.type.desc))
item.add(RuntimeObject(value.page))
item.add(RuntimeObject(value.reference.toString()))
item.add(RuntimeObject(if (value.locked) "是" else "否"))
array.add(RuntimeObject(item))
}
} else {
array.add(RuntimeObject(String.format(" %-20s %-15s %-5s %-5s",
"Name", "Type", "Ref", "Locked")))
mapShares.values.sortedBy { it.objType }.sortedBy { it.name }
.forEach { value ->
array.add(RuntimeObject(String.format(" %-20s %-15s %-5s %-5s",
value.name, value.obj.type.desc, value.reference.toString(), value.locked.toString())))
}
}
return array
}
companion object {
private val logger = Logger.getLogger("share")
private const val MAX_SHARING = 1000
}
}
| src/main/kotlin/com/bajdcc/LALR1/grammar/runtime/service/RuntimeShareService.kt | 1815713314 |
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.host
import arcs.core.data.Plan
import arcs.core.entity.Handle
import arcs.core.host.ParticleState.Companion.Desynced
import arcs.core.host.ParticleState.Companion.Failed
import arcs.core.host.ParticleState.Companion.Failed_NeverStarted
import arcs.core.host.ParticleState.Companion.FirstStart
import arcs.core.host.ParticleState.Companion.Instantiated
import arcs.core.host.ParticleState.Companion.MaxFailed
import arcs.core.host.ParticleState.Companion.Running
import arcs.core.host.ParticleState.Companion.Stopped
import arcs.core.host.ParticleState.Companion.Waiting
import arcs.core.host.api.HandleHolder
import arcs.core.host.api.Particle
import arcs.core.storage.StorageProxy.StorageEvent
import arcs.core.testutil.runTest
import arcs.core.util.Scheduler
import arcs.core.util.testutil.LogRule
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.inOrder
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.only
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.nhaarman.mockitokotlin2.whenever
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.test.assertFailsWith
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mock
import org.mockito.MockitoAnnotations
@RunWith(JUnit4::class)
class ParticleContextTest {
@get:Rule
val log = LogRule()
@Mock
lateinit var particle: Particle
@Mock
lateinit var handles: HandleHolder
@Mock
lateinit var mark: (String) -> Unit
lateinit var context: ParticleContext
val scheduler = Scheduler(EmptyCoroutineContext)
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
whenever(particle.handles).thenReturn(handles)
context = ParticleContext(
particle,
Plan.Particle("name", "location", mapOf())
)
}
@Ignore("b/159257058: write-only handles still need to sync")
@Test
fun fullLifecycle_writeOnlyParticle() = runTest {
val handle = mockHandle(HandleMode.Write)
mark("initParticle")
context.initParticle(scheduler)
assertThat(context.particleState).isEqualTo(Waiting)
mark("registerHandle")
context.registerHandle(handle)
assertThat(context.particleState).isEqualTo(Waiting)
mark("runParticleAsync")
context.runParticleAsync(scheduler).await()
assertThat(context.particleState).isEqualTo(Running)
mark("stopParticle")
context.stopParticle(scheduler)
assertThat(context.particleState).isEqualTo(Stopped)
val mocks = arrayOf(particle, mark, handles, handle)
with(inOrder(*mocks)) {
verify(mark).invoke("initParticle")
verify(particle).onFirstStart()
verify(particle).onStart()
verify(mark).invoke("registerHandle")
verify(handle).mode
verify(mark).invoke("runParticleAsync")
verify(particle).onReady()
verify(mark).invoke("stopParticle")
verify(handles).detach()
verify(particle).onShutdown()
verify(particle).handles
verify(handles).reset()
}
verifyNoMoreInteractions(*mocks)
}
@Test
fun fullLifecycle_readingParticle() = runTest {
val handle = mockHandle(HandleMode.ReadWrite)
mark("initParticle")
context.initParticle(scheduler)
assertThat(context.particleState).isEqualTo(Waiting)
mark("registerHandle")
context.registerHandle(handle)
assertThat(context.particleState).isEqualTo(Waiting)
mark("runParticleAsync")
val particleReady = context.runParticleAsync(scheduler)
assertThat(context.particleState).isEqualTo(Waiting)
mark("notify(READY)")
context.notify(StorageEvent.READY, handle)
particleReady.await()
assertThat(context.particleState).isEqualTo(Running)
mark("stopParticle")
context.stopParticle(scheduler)
assertThat(context.particleState).isEqualTo(Stopped)
val mocks = arrayOf(particle, mark, handles, handle)
with(inOrder(*mocks)) {
verify(mark).invoke("initParticle")
verify(particle).onFirstStart()
verify(particle).onStart()
verify(mark).invoke("registerHandle")
verify(handle).mode
verify(handle).registerForStorageEvents(any())
verify(mark).invoke("runParticleAsync")
verify(handle).maybeInitiateSync()
verify(mark).invoke("notify(READY)")
verify(particle).onReady()
verify(mark).invoke("stopParticle")
verify(particle).handles
verify(handles).detach()
verify(particle).onShutdown()
verify(particle).handles
verify(handles).reset()
}
verifyNoMoreInteractions(*mocks)
}
@Test
fun initParticle_secondInstantiation() = runTest {
context.particleState = Stopped
context.initParticle(scheduler)
verify(particle, only()).onStart()
assertThat(context.particleState).isEqualTo(Waiting)
}
@Test
fun storageEvents() = runTest {
context.initParticle(scheduler)
val handle1 = mockHandle(HandleMode.Write).also { context.registerHandle(it) }
val handle2 = mockHandle(HandleMode.ReadWrite).also { context.registerHandle(it) }
val handle3 = mockHandle(HandleMode.Read).also { context.registerHandle(it) }
val handle4 = mockHandle(HandleMode.ReadWrite).also { context.registerHandle(it) }
val particleReady = context.runParticleAsync(scheduler)
verify(particle).onFirstStart()
verify(particle).onStart()
// TODO(b/159257058): write-only handles still need to sync
arrayOf(handle1, handle2, handle3, handle4).forEach {
verify(it).mode
verify(it).registerForStorageEvents(any())
verify(it).maybeInitiateSync()
}
// All handle.onReady calls are required for particle.onReady
context.notify(StorageEvent.READY, handle1) // TODO(b/159257058)
context.notify(StorageEvent.READY, handle2)
assertThat(context.particleState).isEqualTo(Waiting)
context.notify(StorageEvent.READY, handle3)
assertThat(context.particleState).isEqualTo(Waiting)
mark("ready")
context.notify(StorageEvent.READY, handle4)
particleReady.await()
assertThat(context.particleState).isEqualTo(Running)
// Every handle.onUpdate triggers particle.onUpdate
mark("update")
context.notify(StorageEvent.UPDATE, handle2)
context.notify(StorageEvent.UPDATE, handle3)
context.notify(StorageEvent.UPDATE, handle4)
// Only the first handle.onDesync triggers particle.onDesync
// All handle.onResyncs are required for particle.onResync
mark("desync1")
context.notify(StorageEvent.DESYNC, handle2) // h2 desynced
assertThat(context.particleState).isEqualTo(Desynced)
context.notify(StorageEvent.DESYNC, handle3) // h2, h3 desynced
context.notify(StorageEvent.RESYNC, handle2) // h3 desynced
context.notify(StorageEvent.DESYNC, handle4) // h3, h4 desynced
context.notify(StorageEvent.RESYNC, handle4) // h3 desynced
assertThat(context.particleState).isEqualTo(Desynced)
mark("desync2")
context.notify(StorageEvent.RESYNC, handle3) // all resynced
assertThat(context.particleState).isEqualTo(Running)
val mocks = arrayOf(particle, mark, handle1, handle2, handle3, handle4)
with(inOrder(*mocks)) {
verify(mark).invoke("ready")
verify(particle).onReady()
verify(mark).invoke("update")
verify(particle, times(3)).onUpdate()
verify(mark).invoke("desync1")
verify(particle).onDesync()
verify(mark).invoke("desync2")
verify(particle).onResync()
}
verifyNoMoreInteractions(*mocks)
}
@Test
fun errors_onFirstStart_firstInstantiation() = runTest {
whenever(particle.onFirstStart()).thenThrow(RuntimeException("boom"))
assertFailsWith<RuntimeException> { context.initParticle(scheduler) }
verify(particle, only()).onFirstStart()
assertThat(context.particleState).isEqualTo(Failed_NeverStarted)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
}
@Test
fun errors_onStart_secondInstantiation() = runTest {
whenever(particle.onStart()).thenThrow(RuntimeException("boom"))
assertFailsWith<RuntimeException> { context.initParticle(scheduler) }
with(inOrder(particle)) {
verify(particle).onFirstStart()
verify(particle).onStart()
}
verifyNoMoreInteractions(particle, handles)
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
}
@Test
fun errors_onReady_runParticle() = runTest {
whenever(particle.onReady()).thenThrow(RuntimeException("boom"))
context.initParticle(scheduler)
val deferred = context.runParticleAsync(scheduler)
assertFailsWith<RuntimeException> {
deferred.await()
}
with(inOrder(particle)) {
verify(particle).onFirstStart()
verify(particle).onStart()
verify(particle).onReady()
}
verifyNoMoreInteractions(particle, handles)
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
}
@Test
fun errors_storageEventTriggered() = runTest {
val handle = mockHandle(HandleMode.ReadWrite)
val error = RuntimeException("boom")
context.particleState = Running
whenever(particle.onUpdate()).thenThrow(error)
mock<(Exception) -> Unit>().let {
context.notify(StorageEvent.UPDATE, handle, it)
verify(it).invoke(error)
}
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).isEqualTo(error)
context.particleState = Running
whenever(particle.onDesync()).thenThrow(error)
mock<(Exception) -> Unit>().let {
context.notify(StorageEvent.DESYNC, handle, it)
verify(it).invoke(error)
}
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).isEqualTo(error)
context.particleState = Desynced
whenever(particle.onResync()).thenThrow(error)
mock<(Exception) -> Unit>().let {
context.notify(StorageEvent.RESYNC, handle, it)
verify(it).invoke(error)
}
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).isEqualTo(error)
}
@Test
fun errors_onShutdown() = runTest {
whenever(particle.onShutdown()).thenThrow(RuntimeException("boom"))
context.initParticle(scheduler)
context.runParticleAsync(scheduler).await()
// stopParticle doesn't throw but still marks the particle as failed
context.stopParticle(scheduler)
with(inOrder(particle, handles)) {
verify(particle).onFirstStart()
verify(particle).onStart()
verify(particle).onReady()
verify(particle).handles
verify(handles).detach()
verify(particle).onShutdown()
verify(particle).handles
verify(handles).reset()
}
verifyNoMoreInteractions(particle, handles)
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
}
@Test
fun errors_crashLoopingParticle() = runTest {
whenever(particle.onStart()).thenThrow(RuntimeException("boom"))
for (i in 1..MAX_CONSECUTIVE_FAILURES) {
assertFailsWith<RuntimeException> { context.initParticle(scheduler) }
assertThat(context.consecutiveFailureCount).isEqualTo(i)
}
assertThat(context.particleState).isEqualTo(Failed)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
assertFailsWith<RuntimeException> { context.initParticle(scheduler) }
assertThat(context.particleState).isEqualTo(MaxFailed)
assertThat(context.particleState.cause).hasMessageThat().isEqualTo("boom")
}
@Test
fun copyWith() {
val originalParticle = mock<Particle>()
val planParticle = Plan.Particle("PlanParticle", "location", emptyMap())
val newParticle = mock<Particle>()
val originalContext = ParticleContext(
particle = originalParticle,
planParticle = planParticle,
particleState = Running,
consecutiveFailureCount = 0
)
val copiedContext = originalContext.copyWith(newParticle)
assertThat(copiedContext.particle).isSameInstanceAs(newParticle)
assertThat(copiedContext.planParticle).isSameInstanceAs(planParticle)
assertThat(copiedContext.particleState).isEqualTo(Running)
assertThat(copiedContext.consecutiveFailureCount).isEqualTo(0)
}
@Test
fun toString_rendersImportantPieces() {
assertThat(context.toString()).contains("particle=")
assertThat(context.toString()).contains("particleState=")
assertThat(context.toString()).contains("consecutiveFailureCount=")
assertThat(context.toString()).contains("awaitingReady=")
}
@Test
fun registerHandle_readWrite_notifiesOnFirstReady() = runTest {
val handle = mockHandle(HandleMode.ReadWrite)
val captor = argumentCaptor<(StorageEvent) -> Unit>()
whenever(handle.registerForStorageEvents(captor.capture())).then { }
context.registerHandle(handle)
context.initParticle(scheduler)
val capturedRegistration = captor.firstValue
capturedRegistration(StorageEvent.READY)
capturedRegistration(StorageEvent.READY)
// Only one of the READY events should make it to the particle.
verify(particle).onReady()
}
@Test
fun registerHandle_readWrite_notifiesOnFirstDesync() = runTest {
val handle = mockHandle(HandleMode.ReadWrite)
val captor = argumentCaptor<(StorageEvent) -> Unit>()
whenever(handle.registerForStorageEvents(captor.capture())).then { }
context.registerHandle(handle)
context.initParticle(scheduler)
val capturedRegistration = captor.firstValue
capturedRegistration(StorageEvent.DESYNC)
capturedRegistration(StorageEvent.DESYNC)
// Only one of the DESYNC events should make it to the particle.
verify(particle).onDesync()
}
@Test
fun registerHandle_readWrite_notifiesOnAnyResync() = runTest {
val handle = mockHandle(HandleMode.ReadWrite)
val captor = argumentCaptor<(StorageEvent) -> Unit>()
whenever(handle.registerForStorageEvents(captor.capture())).then { }
context.registerHandle(handle)
context.initParticle(scheduler)
val capturedRegistration = captor.firstValue
capturedRegistration(StorageEvent.RESYNC)
capturedRegistration(StorageEvent.RESYNC)
// Any resync event should make it through.
verify(particle, times(2)).onResync()
}
@Test
fun registerHandle_writeOnly_onlyNotifiesOnReady() = runTest {
val handle = mockHandle(HandleMode.Write)
val captor = argumentCaptor<(StorageEvent) -> Unit>()
whenever(handle.registerForStorageEvents(captor.capture())).then { }
context.registerHandle(handle)
context.initParticle(scheduler)
val capturedRegistration = captor.firstValue
capturedRegistration(StorageEvent.READY)
capturedRegistration(StorageEvent.DESYNC)
capturedRegistration(StorageEvent.RESYNC)
capturedRegistration(StorageEvent.UPDATE)
// Only the onReady event should make it through.
verify(particle).onReady()
verify(particle, never()).onDesync()
verify(particle, never()).onResync()
verify(particle, never()).onUpdate()
}
@Test
fun initParticle_whenFirstStart_throws() = runTest {
val context = createParticleContext(particleState = FirstStart)
val e = assertFailsWith<IllegalStateException> { context.initParticle(scheduler) }
assertThat(e).hasMessageThat()
.contains("initParticle should not be called on a particle in state $FirstStart")
}
@Test
fun initParticle_whenWaiting_throws() = runTest {
val context = createParticleContext(particleState = Waiting)
val e = assertFailsWith<IllegalStateException> { context.initParticle(scheduler) }
assertThat(e).hasMessageThat()
.contains("initParticle should not be called on a particle in state $Waiting")
}
@Test
fun initParticle_whenRunning_throws() = runTest {
val context = createParticleContext(particleState = Running)
val e = assertFailsWith<IllegalStateException> { context.initParticle(scheduler) }
assertThat(e).hasMessageThat()
.contains("initParticle should not be called on a particle in state $Running")
}
@Test
fun initParticle_whenDesynced_throws() = runTest {
val context = createParticleContext(particleState = Desynced)
val e = assertFailsWith<IllegalStateException> { context.initParticle(scheduler) }
assertThat(e).hasMessageThat()
.contains("initParticle should not be called on a particle in state $Desynced")
}
@Test
fun initParticle_whenMaxFailed_throws() = runTest {
val context = createParticleContext(particleState = MaxFailed)
val e = assertFailsWith<IllegalStateException> { context.initParticle(scheduler) }
assertThat(e).hasMessageThat()
.contains("initParticle should not be called on a particle in state $MaxFailed")
}
@Test
fun notify_whenInstantiated_throws() = runTest {
val context = createParticleContext(particleState = Instantiated)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $Instantiated")
}
@Test
fun notify_whenFirstStart_throws() = runTest {
val context = createParticleContext(particleState = FirstStart)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $FirstStart")
}
@Test
fun notify_whenStopped_throws() = runTest {
val context = createParticleContext(particleState = Stopped)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $Stopped")
}
@Test
fun notify_whenFailed_throws() = runTest {
val context = createParticleContext(particleState = Failed)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $Failed")
}
@Test
fun notify_whenFailedNeverStarted_throws() = runTest {
val context = createParticleContext(particleState = Failed_NeverStarted)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $Failed_NeverStarted")
}
@Test
fun notify_whenMaxFailed_throws() = runTest {
val context = createParticleContext(particleState = MaxFailed)
val e = assertFailsWith<IllegalStateException> {
context.notify(StorageEvent.READY, mockHandle(HandleMode.ReadWrite))
}
assertThat(e).hasMessageThat()
.contains("storage events should not be received in state $MaxFailed")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenRunningAndAwaitingReadyFromAHandle_throws() = runTest {
val context = createParticleContext(particleState = Running)
context.registerHandle(mockHandle(HandleMode.ReadWrite))
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains(
"runParticleAsync called on an already running particle; awaitingReady should be empty " +
"but still has 1 handles"
)
}
@Test
fun runParticleAsync_whenRunningAndHandlesReady_returnsCompletedDeferred() = runTest {
val context = createParticleContext(particleState = Running)
val actualDeferred = context.runParticleAsync(scheduler)
assertThat(actualDeferred.isCompleted).isTrue()
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_calledMoreThanOnceWhenWaiting_throws() = runTest {
val context = createParticleContext(particleState = Waiting)
context.registerHandle(mockHandle(HandleMode.ReadWrite))
// First call should be okay.
context.runParticleAsync(scheduler)
// Second call should fail.
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync called more than once on a waiting particle")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenInstantiated_throws() = runTest {
val context = createParticleContext(particleState = Instantiated)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $Instantiated")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenFirstStart_throws() = runTest {
val context = createParticleContext(particleState = FirstStart)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $FirstStart")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenDesynced_throws() = runTest {
val context = createParticleContext(particleState = Desynced)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $Desynced")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenStopped_throws() = runTest {
val context = createParticleContext(particleState = Stopped)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $Stopped")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenFailed_throws() = runTest {
val context = createParticleContext(particleState = Failed)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $Failed")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenFailedNeverStarted_throws() = runTest {
val context = createParticleContext(particleState = Failed_NeverStarted)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $Failed_NeverStarted")
}
@Suppress("DeferredResultUnused")
@Test
fun runParticleAsync_whenMaxFailed_throws() = runTest {
val context = createParticleContext(particleState = MaxFailed)
val e = assertFailsWith<IllegalStateException> { context.runParticleAsync(scheduler) }
assertThat(e).hasMessageThat()
.contains("runParticleAsync should not be called on a particle in state $MaxFailed")
}
private fun mockHandle(handleMode: HandleMode) =
mock<Handle> { on { mode }.thenReturn(handleMode) }
private fun createParticleContext(
particle: Particle = this.particle,
planParticle: Plan.Particle = Plan.Particle("name", "location", mapOf()),
particleState: ParticleState = Instantiated
): ParticleContext = ParticleContext(particle, planParticle, particleState)
}
| javatests/arcs/core/host/ParticleContextTest.kt | 1809727699 |
package nl.jstege.adventofcode.aoc2017.days
import nl.jstege.adventofcode.aoccommon.utils.DayTester
/**
* Test for Day20
* @author Jelle Stege
*/
class Day20Test : DayTester(Day20()) | aoc-2017/src/test/kotlin/nl/jstege/adventofcode/aoc2017/days/Day20Test.kt | 2208383113 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.api
abstract class VimProcessGroupBase : VimProcessGroup
| vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/VimProcessGroupBase.kt | 2258808853 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package org.jetbrains.plugins.ideavim.action.scroll
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.helper.VimBehaviorDiffers
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt
import org.jetbrains.plugins.ideavim.VimTestCase
/*
*z<CR>*
z<CR> Redraw, line [count] at top of window (default
cursor line). Put cursor at first non-blank in the
line.
*/
class ScrollFirstScreenLineStartActionTest : VimTestCase() {
fun `test scroll current line to top of screen`() {
configureByPages(5)
setPositionAndScroll(0, 19)
typeText(injector.parser.parseKeys("z<CR>"))
assertPosition(19, 0)
assertVisibleArea(19, 53)
}
fun `test scroll current line to top of screen and move to first non-blank`() {
configureByLines(100, " I found it in a legendary land")
setPositionAndScroll(0, 19, 0)
typeText(injector.parser.parseKeys("z<CR>"))
assertPosition(19, 4)
assertVisibleArea(19, 53)
}
fun `test scroll current line to top of screen minus scrolloff`() {
VimPlugin.getOptionService().setOptionValue(OptionScope.GLOBAL, OptionConstants.scrolloffName, VimInt(10))
configureByPages(5)
setPositionAndScroll(0, 19)
typeText(injector.parser.parseKeys("z<CR>"))
assertPosition(19, 0)
assertVisibleArea(9, 43)
}
fun `test scrolls count line to top of screen`() {
configureByPages(5)
setPositionAndScroll(0, 19)
typeText(injector.parser.parseKeys("100z<CR>"))
assertPosition(99, 0)
assertVisibleArea(99, 133)
}
fun `test scrolls count line to top of screen minus scrolloff`() {
VimPlugin.getOptionService().setOptionValue(OptionScope.GLOBAL, OptionConstants.scrolljumpName, VimInt(10))
configureByPages(5)
setPositionAndScroll(0, 19)
typeText(injector.parser.parseKeys("z<CR>"))
assertPosition(19, 0)
assertVisibleArea(19, 53)
}
@VimBehaviorDiffers(description = "Virtual space at end of file")
fun `test invalid count scrolls last line to top of screen`() {
configureByPages(5)
setPositionAndScroll(0, 19)
typeText(injector.parser.parseKeys("1000z<CR>"))
assertPosition(175, 0)
assertVisibleArea(146, 175)
}
fun `test scroll current line to top of screen ignoring scrolljump`() {
VimPlugin.getOptionService().setOptionValue(OptionScope.GLOBAL, OptionConstants.scrolljumpName, VimInt(10))
configureByPages(5)
setPositionAndScroll(0, 19)
typeText(injector.parser.parseKeys("z<CR>"))
assertPosition(19, 0)
assertVisibleArea(19, 53)
}
}
| src/test/java/org/jetbrains/plugins/ideavim/action/scroll/ScrollFirstScreenLineStartActionTest.kt | 816134869 |
package com.timepath.hl2.swing
import com.timepath.Logger
import com.timepath.hl2.io.font.VBF
import com.timepath.hl2.io.image.VTF
import java.awt.*
import java.awt.event.MouseEvent
import java.awt.event.MouseListener
import java.awt.event.MouseMotionListener
import java.io.IOException
import java.util.LinkedList
import java.util.logging.Level
import javax.swing.JPanel
import javax.swing.SwingUtilities
public class VBFCanvas
/**
* Creates new form VBFTest
*/
: JPanel(), MouseListener, MouseMotionListener {
private var img: Image? = null
private var last: Point? = null
var selected: MutableList<VBF.BitmapGlyph> = LinkedList()
private var vbf: VBF? = null
private var vtf: VTF? = null
init {
addMouseListener(this)
addMouseMotionListener(this)
}
public fun setVBF(vbf: VBF) {
this.vbf = vbf
revalidate()
}
public fun setVTF(t: VTF) {
vtf = t
vbf!!.width = vtf!!.width.toShort()
vbf!!.height = vtf!!.height.toShort()
repaint()
}
override fun mouseClicked(e: MouseEvent) {
}
override fun mousePressed(e: MouseEvent) {
last = e.getPoint()
if (!SwingUtilities.isLeftMouseButton(e)) {
return
}
val old = LinkedList(selected)
val clicked = get(e.getPoint())
for (g in clicked) {
if (g in selected) {
return
}
}
if (e.isControlDown()) {
selected.addAll(clicked)
} else {
selected = clicked
}
for (g in old) {
repaint(g.bounds)
}
for (g in selected) {
repaint(g.bounds)
}
}
fun get(p: Point): MutableList<VBF.BitmapGlyph> {
val intersected = LinkedList<VBF.BitmapGlyph>()
vbf?.let {
for (g in it.glyphs) {
if (p in g.bounds) {
intersected.add(g)
}
}
}
return intersected
}
override fun mouseReleased(e: MouseEvent) {
}
override fun mouseEntered(e: MouseEvent) {
}
override fun mouseExited(e: MouseEvent) {
}
override fun mouseDragged(e: MouseEvent) {
val p = e.getPoint()
last?.let {
e.translatePoint(-it.x, -it.y)
}
for (sel in selected) {
if (SwingUtilities.isRightMouseButton(e)) {
sel.bounds.width += e.getPoint().x
sel.bounds.height += e.getPoint().y
} else {
sel.bounds.x += e.getPoint().x
sel.bounds.y += e.getPoint().y
}
}
last = p
repaint()
}
override fun mouseMoved(e: MouseEvent) {
}
public fun select(g: VBF.BitmapGlyph?) {
selected.clear()
g?.let { g ->
selected.add(g)
repaint(g.bounds)
}
}
override fun paintComponent(g: Graphics) {
val g2 = g as Graphics2D
g2.setComposite(acNormal)
g2.setColor(Color.BLACK)
g2.fillRect(0, 0, getWidth(), getHeight())
if ((img == null) && (vtf != null)) {
try {
img = vtf!!.getImage(0)
} catch (ex: IOException) {
LOG.log(Level.SEVERE, { null }, ex)
}
}
vbf?.let {
g2.setColor(Color.GRAY)
g2.fillRect(0, 0, it.width.toInt(), it.height.toInt())
}
img?.let {
g2.drawImage(it, 0, 0, this)
}
vbf?.let {
for (glyph in it.glyphs) {
if (glyph == null) {
continue
}
val bounds = glyph.bounds
if ((bounds == null) || bounds.isEmpty()) {
continue
}
g2.setComposite(acNormal)
g2.setColor(Color.GREEN)
g2.drawRect(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1)
if (glyph in selected) {
g2.setComposite(acSelected)
g2.fillRect(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1)
}
// TODO: Negative font folor
// Map<TextAttribute, Object> map = new Hashtable<TextAttribute, Object>();
// map.put(TextAttribute.SWAP_COLORS, TextAttribute.SWAP_COLORS_ON);
// map.put(TextAttribute.FOREGROUND, Color.BLACK);
// map.put(TextAttribute.BACKGROUND, Color.TRANSLUCENT);
// Font f = this.getFont().deriveFont(map);
// g.setFont(f);
// g.setXORMode(Color.WHITE);
g2.setComposite(acText)
g2.setColor(Color.GREEN)
g2.drawString(Integer.toString(glyph.index.toInt()), bounds.x + 1, (bounds.y + bounds.height) - 1)
}
}
}
override fun getPreferredSize() = vbf?.let {
Dimension(it.width.toInt(), it.height.toInt())
} ?: Dimension(128, 128)
companion object {
private val LOG = Logger()
private val serialVersionUID = 1
private val acNormal = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)
private val acSelected = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)
private val acText = AlphaComposite.getInstance(AlphaComposite.SRC_OVER)
}
}
| src/main/kotlin/com/timepath/hl2/swing/VBFCanvas.kt | 1311667586 |
package org.wordpress.android.ui.bloggingprompts.onboarding
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.firstOrNull
import org.wordpress.android.R
import org.wordpress.android.fluxc.store.SiteStore
import org.wordpress.android.fluxc.store.bloggingprompts.BloggingPromptsStore
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.DismissDialog
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.DoNothing
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.OpenEditor
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.OpenRemindersIntro
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingAction.OpenSitePicker
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingDialogFragment.DialogType
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingDialogFragment.DialogType.INFORMATION
import org.wordpress.android.ui.bloggingprompts.onboarding.BloggingPromptsOnboardingDialogFragment.DialogType.ONBOARDING
import org.wordpress.android.ui.bloggingprompts.onboarding.usecase.GetIsFirstBloggingPromptsOnboardingUseCase
import org.wordpress.android.ui.bloggingprompts.onboarding.usecase.SaveFirstBloggingPromptsOnboardingUseCase
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.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import java.util.Date
import javax.inject.Inject
import javax.inject.Named
class BloggingPromptsOnboardingViewModel @Inject constructor(
private val siteStore: SiteStore,
private val uiStateMapper: BloggingPromptsOnboardingUiStateMapper,
private val selectedSiteRepository: SelectedSiteRepository,
private val bloggingPromptsStore: BloggingPromptsStore,
private val analyticsTracker: BloggingPromptsOnboardingAnalyticsTracker,
@Named(BG_THREAD) val bgDispatcher: CoroutineDispatcher,
private val getIsFirstBloggingPromptsOnboardingUseCase: GetIsFirstBloggingPromptsOnboardingUseCase,
private val saveFirstBloggingPromptsOnboardingUseCase: SaveFirstBloggingPromptsOnboardingUseCase
) : ScopedViewModel(bgDispatcher) {
private val _uiState = MutableLiveData<BloggingPromptsOnboardingUiState>()
val uiState: LiveData<BloggingPromptsOnboardingUiState> = _uiState
private val _action = MutableLiveData<BloggingPromptsOnboardingAction>()
val action: LiveData<BloggingPromptsOnboardingAction> = _action
private val _snackBarMessage = MutableLiveData<Event<SnackbarMessageHolder>>()
val snackBarMessage = _snackBarMessage as LiveData<Event<SnackbarMessageHolder>>
private lateinit var dialogType: DialogType
private var hasTrackedScreenShown = false
private var isFirstBloggingPromptsOnboarding = false
fun start(type: DialogType) {
if (!hasTrackedScreenShown) {
hasTrackedScreenShown = true
analyticsTracker.trackScreenShown()
}
if (type == ONBOARDING) {
isFirstBloggingPromptsOnboarding = getIsFirstBloggingPromptsOnboardingUseCase.execute()
saveFirstBloggingPromptsOnboardingUseCase.execute(isFirstTime = false)
}
dialogType = type
_uiState.value = uiStateMapper.mapReady(dialogType, ::onPrimaryButtonClick, ::onSecondaryButtonClick)
}
fun onSiteSelected(selectedSiteLocalId: Int) {
_action.value = OpenRemindersIntro(selectedSiteLocalId)
}
private fun onPrimaryButtonClick() = launch {
val action = when (dialogType) {
ONBOARDING -> {
analyticsTracker.trackTryItNowClicked()
val site = selectedSiteRepository.getSelectedSite()
val bloggingPrompt = bloggingPromptsStore.getPromptForDate(site!!, Date()).firstOrNull()?.model
if (bloggingPrompt == null) {
_snackBarMessage.postValue(
Event(
SnackbarMessageHolder(
UiStringRes(R.string.blogging_prompts_onboarding_prompts_loading)
)
)
)
DoNothing
} else {
OpenEditor(bloggingPrompt.id)
}
}
INFORMATION -> {
analyticsTracker.trackGotItClicked()
DismissDialog
}
}
_action.postValue(action)
}
private fun onSecondaryButtonClick() {
analyticsTracker.trackRemindMeClicked()
if (siteStore.sitesCount > 1 && isFirstBloggingPromptsOnboarding) {
_action.value = OpenSitePicker(selectedSiteRepository.getSelectedSite())
} else {
siteStore.sites.firstOrNull()?.let {
_action.value = OpenRemindersIntro(it.id)
}
}
}
}
| WordPress/src/main/java/org/wordpress/android/ui/bloggingprompts/onboarding/BloggingPromptsOnboardingViewModel.kt | 1516501938 |
package org.wordpress.android.workers.reminder
import android.app.PendingIntent
import androidx.core.app.NotificationCompat.CATEGORY_REMINDER
import androidx.core.app.NotificationCompat.PRIORITY_DEFAULT
import org.wordpress.android.BuildConfig
import org.wordpress.android.R
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.fluxc.store.SiteStore
import org.wordpress.android.push.NotificationPushIds.REMINDER_NOTIFICATION_ID
import org.wordpress.android.push.NotificationType.BLOGGING_REMINDERS
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersAnalyticsTracker
import org.wordpress.android.ui.posts.PostListType
import org.wordpress.android.ui.posts.PostsListActivity
import org.wordpress.android.util.SiteUtils
import org.wordpress.android.viewmodel.ContextProvider
import org.wordpress.android.viewmodel.ResourceProvider
import javax.inject.Inject
class ReminderNotifier @Inject constructor(
val contextProvider: ContextProvider,
val resourceProvider: ResourceProvider,
val siteStore: SiteStore,
val accountStore: AccountStore,
val reminderNotificationManager: ReminderNotificationManager,
val analyticsTracker: BloggingRemindersAnalyticsTracker
) {
fun notify(siteId: Int) {
val context = contextProvider.getContext()
val site = siteStore.getSiteByLocalId(siteId) ?: return
val siteName = SiteUtils.getSiteNameOrHomeURL(site)
val reminderNotification = ReminderNotification(
channel = resourceProvider.getString(R.string.notification_channel_reminder_id),
contentIntentBuilder = {
PendingIntent.getActivity(
context,
REMINDER_NOTIFICATION_ID + siteId,
PostsListActivity.buildIntent(
context,
site,
PostListType.DRAFTS,
actionsShownByDefault = true,
notificationType = BLOGGING_REMINDERS
),
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
},
contentTitle = resourceProvider.getString(R.string.blogging_reminders_notification_title, siteName),
contentText = resourceProvider.getString(R.string.blogging_reminders_notification_text),
priority = PRIORITY_DEFAULT,
category = CATEGORY_REMINDER,
autoCancel = true,
colorized = true,
color = if (BuildConfig.IS_JETPACK_APP) {
resourceProvider.getColor(R.color.jetpack_green)
} else {
resourceProvider.getColor(R.color.blue_50)
},
smallIcon = R.drawable.ic_app_white_24dp
)
reminderNotificationManager.notify(REMINDER_NOTIFICATION_ID + siteId, reminderNotification)
analyticsTracker.setSite(siteId)
analyticsTracker.trackNotificationReceived(false)
}
fun shouldNotify(siteId: Int) =
siteId != NO_SITE_ID && siteStore.getSiteByLocalId(siteId) != null && accountStore.hasAccessToken()
companion object {
const val NO_SITE_ID = -1
}
}
| WordPress/src/main/java/org/wordpress/android/workers/reminder/ReminderNotifier.kt | 472768395 |
package com.joe.zatuji.data.bean
/**
* Description:
* author:Joey
* date:2018/11/20
*/
class Empty | bak/src/main/java/com/joey/bak/data/bean/Empty.kt | 1406569413 |
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.recurrent.ltm
import com.kotlinnlp.simplednn.core.arrays.getInputErrors
import com.kotlinnlp.simplednn.core.layers.helpers.BackwardHelper
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
/**
* The helper which executes the backward on a [layer].
*
* @property layer the [LTMLayer] in which the backward is executed
*/
internal class LTMBackwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>(
override val layer: LTMLayer<InputNDArrayType>
) : BackwardHelper<InputNDArrayType>(layer) {
/**
* Executes the backward calculating the errors of the parameters and eventually of the input through the SGD
* algorithm, starting from the preset errors of the output array.
*
* @param propagateToInput whether to propagate the errors to the input array
*/
override fun execBackward(propagateToInput: Boolean) {
val prevStateLayer = this.layer.layersWindow.getPrevState() as? LTMLayer
val nextStateLayer = this.layer.layersWindow.getNextState() as? LTMLayer
if (nextStateLayer != null) this.addOutputRecurrentGradients(nextStateLayer)
this.assignCellGradients(nextStateLayer)
this.assignGatesGradients()
this.assignParamsGradients()
// Note: the previous layer will use the input gradients of this layer because they are equal to the recurrent
// error of the output.
if (propagateToInput || prevStateLayer != null) {
this.assignInputGradients()
}
}
/**
* @param nextStateLayer the layer in the next state
*/
private fun assignCellGradients(nextStateLayer: LTMLayer<*>?) {
val l3: DenseNDArray = this.layer.inputGate3.values
val gy: DenseNDArray = this.layer.outputArray.errors
val cellDeriv: DenseNDArray = this.layer.cell.calculateActivationDeriv()
this.layer.cell.assignErrorsByProd(gy, l3)
if (nextStateLayer != null)
this.layer.cell.errors.assignSum(nextStateLayer.c.errors)
this.layer.cell.errors.assignProd(cellDeriv)
val wCell: DenseNDArray = this.layer.params.cell.weights.values
this.layer.c.assignErrors(this.layer.cell.getInputErrors(wCell))
}
/**
* Assign the gradients of the gates.
*/
private fun assignGatesGradients() {
val gy: DenseNDArray = this.layer.outputArray.errors
val gC: DenseNDArray = this.layer.c.errors
val l1: DenseNDArray = this.layer.inputGate1.values
val l2: DenseNDArray = this.layer.inputGate2.values
val cell: DenseNDArray = this.layer.cell.values
val l1Deriv: DenseNDArray = this.layer.inputGate1.calculateActivationDeriv()
val l2Deriv: DenseNDArray = this.layer.inputGate2.calculateActivationDeriv()
val l3Deriv: DenseNDArray = this.layer.inputGate3.calculateActivationDeriv()
this.layer.inputGate1.assignErrorsByProd(gC, l1Deriv.assignProd(l2))
this.layer.inputGate2.assignErrorsByProd(gC, l2Deriv.assignProd(l1))
this.layer.inputGate3.assignErrorsByProd(gy, l3Deriv.assignProd(cell))
}
/**
* Assign the gradients of the parameters.
*/
private fun assignParamsGradients() {
this.layer.inputGate1.assignParamsGradients(
gw = this.layer.params.inputGate1.weights.errors.values,
gb = null,
x = this.layer.x)
this.layer.inputGate2.assignParamsGradients(
gw = this.layer.params.inputGate2.weights.errors.values,
gb = null,
x = this.layer.x)
this.layer.inputGate3.assignParamsGradients(
gw = this.layer.params.inputGate3.weights.errors.values,
gb = null,
x = this.layer.x)
this.layer.cell.assignParamsGradients(
gw = this.layer.params.cell.weights.errors.values,
gb = null,
x = this.layer.c.values)
}
/**
* Add output gradients coming from the next state.
*
* @param nextStateLayer the layer structure in the next state
*/
private fun addOutputRecurrentGradients(nextStateLayer: LTMLayer<*>) {
val gy: DenseNDArray = this.layer.outputArray.errors
// Note: the output recurrent errors are equal to the input errors of the next state
val gyRec: DenseNDArray = nextStateLayer.inputArray.errors
gy.assignSum(gyRec)
}
/**
* Assign the gradients of the input.
*/
private fun assignInputGradients() {
val w1: DenseNDArray = this.layer.params.inputGate1.weights.values
val w2: DenseNDArray = this.layer.params.inputGate2.weights.values
val w3: DenseNDArray = this.layer.params.inputGate3.weights.values
val gL1: DenseNDArray = this.layer.inputGate1.getInputErrors(w1)
val gL2: DenseNDArray = this.layer.inputGate2.getInputErrors(w2)
val gL3: DenseNDArray = this.layer.inputGate3.getInputErrors(w3)
this.layer.inputArray.assignErrors(gL1.assignSum(gL2).assignSum(gL3))
}
}
| src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/ltm/LTMBackwardHelper.kt | 550050560 |
package ee.es
import org.elasticsearch.client.Client
import org.elasticsearch.cluster.ClusterModule
import org.elasticsearch.common.unit.TimeValue
import org.elasticsearch.common.xcontent.NamedXContentRegistry
import org.elasticsearch.common.xcontent.XContentFactory
import org.elasticsearch.common.xcontent.XContentType
import org.elasticsearch.search.builder.SearchSourceBuilder
import java.nio.file.Path
open class Exporter(val client: Client) {
fun export(index: Array<String>, searchSource: String, targetPath: Path, fields: Array<String>,
separator: String = " ") {
val scroll = TimeValue(60000)
var scrollResp =
client.prepareSearch(*index).setSource(searchSourceBuilder(searchSource)).setScroll(scroll).execute()
.actionGet()
targetPath.toFile().bufferedWriter().use { out ->
println("Export started to $targetPath, please wait...")
while (scrollResp.hits.hits.isNotEmpty()) {
scrollResp.hits.forEach { hit ->
val s = hit.sourceAsMap
fields.forEach { field ->
if (s.containsKey(field)) {
out.write(s[field].toString().removeSuffix("\n").removeSuffix("\r"))
} else {
out.write(" ")
}
out.write(separator)
}
out.write("\n")
}
scrollResp = client.prepareSearchScroll(scrollResp.scrollId).setScroll(scroll).execute().actionGet()
}
println("Export done to $targetPath.")
}
client.close()
}
protected fun searchSourceBuilder(searchSource: String): SearchSourceBuilder {
/*
// from Map to XContent
XContentBuilder builder = ... // see above
// from XContent to JSON
String json = new String(builder.getBytes(), "UTF-8");
// use JSON to populate SearchSourceBuilder
JsonXContent parser = createParser(JsonXContent.jsonXContent, json));
sourceBuilder.parseXContent(new QueryParseContext(parser));
*/
//val parser = XContentFactory.xContent(XContentType.JSON).createParser(namedXContentRegistry(), searchSource)
val searchSourceBuilder = SearchSourceBuilder.fromXContent(null) //QueryParseContext(parser)
return searchSourceBuilder
}
private fun namedXContentRegistry(): NamedXContentRegistry {
//return NamedXContentRegistry(NetworkModule.getNamedXContents())
return NamedXContentRegistry(ClusterModule.getNamedXWriteables())
}
} | ee-elastic/src/main/kotlin/ee/es/Exporter.kt | 1501521042 |
package com.sheepsgohome.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Gdx.gl
import com.badlogic.gdx.Gdx.graphics
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.FPSLogger
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.*
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad
import com.badlogic.gdx.utils.viewport.StretchViewport
import com.sheepsgohome.dataholders.WolvesData
import com.sheepsgohome.enums.GameResult
import com.sheepsgohome.enums.GameState.*
import com.sheepsgohome.gameobjects.*
import com.sheepsgohome.gdx.screens.switchScreen
import com.sheepsgohome.positioning.BodyPositioner
import com.sheepsgohome.enums.GameResult.*
import com.sheepsgohome.shared.GameData.CAMERA_HEIGHT
import com.sheepsgohome.shared.GameData.CAMERA_WIDTH
import com.sheepsgohome.shared.GameData.LEVEL
import com.sheepsgohome.shared.GameData.SOUND_ENABLED
import com.sheepsgohome.shared.GameData.VIRTUAL_JOYSTICK
import com.sheepsgohome.shared.GameData.VIRTUAL_JOYSTICK_LEFT
import com.sheepsgohome.shared.GameData.VIRTUAL_JOYSTICK_NONE
import com.sheepsgohome.shared.GameData.VIRTUAL_JOYSTICK_RIGHT
import com.sheepsgohome.shared.GameData.loc
import com.sheepsgohome.shared.GameMusic.ambient
import com.sheepsgohome.shared.GameSkins.skin
import java.util.*
class GameplayClassicModeScreen : Screen, ContactListener {
private val fpsLogger by lazy { FPSLogger() }
//Box2D Physics
private val debugRenderer = Box2DDebugRenderer()
private val world = World(Vector2(0f, 0f), true)
private val multiplier = 1f
private val camera: OrthographicCamera = OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT)
private val batch = SpriteBatch()
private var gameState = RUNNING
private val touchpadEnabled = VIRTUAL_JOYSTICK != VIRTUAL_JOYSTICK_NONE
private val touchpad by lazy { Touchpad(0f, skin).apply {
val touchPadSize = 30f
when (VIRTUAL_JOYSTICK) {
VIRTUAL_JOYSTICK_RIGHT -> setBounds(CAMERA_WIDTH - touchPadSize, 0f, touchPadSize, touchPadSize)
VIRTUAL_JOYSTICK_LEFT -> setBounds(0f, 0f, touchPadSize, touchPadSize)
}
addAction(Actions.alpha(0.5f))
}}
private val stage = Stage(StretchViewport(CAMERA_WIDTH * multiplier, CAMERA_HEIGHT * multiplier))
private val levelLabel = Label(loc.format("level", LEVEL), skin, "levelTitle").apply {
setFontScale((CAMERA_WIDTH * multiplier - 40) / prefWidth)
addAction(Actions.sequence(
Actions.alpha(1f),
Actions.fadeOut(3f)
))
}
private val grass = Grass()
private val home = Home(world)
private val sheep = Sheep(world)
private val walls = listOf(
TopWall(world),
BottomWall(world),
LeftWall(world),
RightWall(world)
)
private val wolves: List<Wolf>
init {
Box2D.init()
world.setContactListener(this)
val data = getWolvesData(LEVEL)
wolves = mutableListOf(
List(data.wildWolvesCount) { WildWolf(world) },
List(data.hungryWolvesCount) { HungryWolf(world, sheep) },
List(data.alphaWolvesCount) { AlphaWolf(world, sheep) }
).flatten()
Collections.shuffle(wolves)
}
override fun show() {
//catch menu and back buttons
Gdx.input.isCatchBackKey = true
Gdx.input.setCatchMenuKey(true)
//Ambient
if (SOUND_ENABLED && !ambient.isPlaying) {
ambient.play()
}
val table = Table().apply {
add(levelLabel)
setFillParent(true)
}
stage.addActor(table)
if (touchpadEnabled) {
stage.addActor(touchpad)
}
Gdx.input.inputProcessor = stage
kickOffWildWolves()
}
override fun render(delta: Float) {
gl.glClearColor(0.9f, 0.9f, 0.9f, 1f)
gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
when (gameState) {
RUNNING -> renderGameScene()
GAME_OVER_BY_WILD_WOLF -> gameOver(SHEEP_EATEN_BY_WILD_WOLF)
GAME_OVER_BY_HUNGRY_WOLF -> gameOver(SHEEP_EATEN_BY_HUNGRY_WOLF)
GAME_OVER_BY_ALPHA_WOLF -> gameOver(SHEEP_EATEN_BY_ALPHA_WOLF)
NEXT_LEVEL -> nextLevel()
}
// fpsLogger.log();
}
private fun renderGameScene() {
//positioning
sheep.updateSprite()
//input
if (touchpadEnabled) {
if (touchpad.isTouched) {
handleTouch()
} else {
sheep.nullifyVelocity()
}
} else {
if (Gdx.input.isTouched) {
handleTouch(Gdx.input.x, Gdx.input.y)
} else {
sheep.nullifyVelocity()
}
}
//drawing
batch.projectionMatrix = camera.combined
batch.begin()
grass.draw(batch)
sheep.draw(batch)
//draw home (top center)
home.draw(batch)
//draw wolves
for (wolf in wolves) {
when (wolf) {
is AlphaWolf -> {
wolf.updateVelocity()
wolf.updateSprite()
}
is HungryWolf -> {
wolf.calculateSteeringBehaviour()
wolf.updateSprite()
}
else -> wolf.updateSprite()
}
wolf.draw(batch)
}
batch.end()
// fpsLogger.log()
// debugRenderer.render(world, camera.combined);
world.step(graphics.deltaTime, 6, 2)
stage.act()
stage.draw()
}
override fun resize(width: Int, height: Int) {
stage.viewport.update(width, height, true)
//world boundaries
walls.forEach { it.setDefaultPosition() }
//sheep
sheep.positionBottomCenter()
//home
home.positionTopCenter()
//wolves positioning
val wolfBodies = wolves.map { it.body }
BodyPositioner().alignInCenteredGrid(
wolfBodies,
maxBodiesInRow = 13,
columnSize = WildWolf.WILD_WOLF_SIZE + 0.5f,
verticalOffset = (CAMERA_HEIGHT / 2) - Home.HOME_SIZE - 5
)
}
override fun pause() {}
override fun resume() {}
override fun hide() {
//stop ambient
if (ambient.isPlaying) {
ambient.pause()
}
//release menu and back buttons
Gdx.input.isCatchBackKey = false
Gdx.input.setCatchMenuKey(false)
dispose()
}
override fun dispose() {
grass.dispose()
home.dispose()
sheep.dispose()
wolves.forEach { it.dispose() }
batch.dispose()
world.dispose()
stage.dispose()
}
private fun getWolvesData(level: Int): WolvesData {
val data = WolvesData()
data.wildWolvesCount = ((level - 1) % 5 + 1) * 5
if (level < 6) {
data.hungryWolvesCount = 0
} else {
data.hungryWolvesCount = (level - 1 - 5) / 5 % 4 + 1
}
if (level < 26) {
data.alphaWolvesCount = 0
} else {
data.alphaWolvesCount = (level - 1 - 5) / 20
}
return data
}
//Touchpad touch
private fun handleTouch() {
val vec = Vector2(touchpad.knobPercentX, touchpad.knobPercentY).nor()
sheep.updateVelocity(vec)
}
//Finger touch
private fun handleTouch(x: Int, y: Int) {
var targetx = x.toFloat()
var targety = (Gdx.graphics.height - y).toFloat()
targetx = targetx / Gdx.graphics.width.toFloat() * CAMERA_WIDTH - CAMERA_WIDTH / 2f
targety = targety / Gdx.graphics.height.toFloat() * CAMERA_HEIGHT - CAMERA_HEIGHT / 2f
val pos = sheep.steerableBody.position
targetx -= pos.x
targety -= pos.y
val divider = Math.max(Math.abs(targetx), Math.abs(targety))
targetx /= divider
targety /= divider
sheep.updateVelocity(targetx, targety)
}
private fun kickOffWildWolves() {
wolves.filterIsInstance<WildWolf>().forEach { it.setRandomMovement() }
}
private fun handleContact(bodyA: Body, bodyB: Body) {
val objA = bodyA.userData
val objB = bodyB.userData
when (objA) {
is WildWolf -> objA.setRandomMovement()
is Sheep -> when (objB) {
is WildWolf -> gameState = GAME_OVER_BY_WILD_WOLF
is HungryWolf -> gameState = GAME_OVER_BY_HUNGRY_WOLF
is AlphaWolf -> gameState = GAME_OVER_BY_ALPHA_WOLF
is Home -> gameState = NEXT_LEVEL
}
}
}
private fun gameOver(result: GameResult) = switchScreen(ClassicModeResultScreen(result))
private fun nextLevel() = gameOver(SHEEP_SUCCEEDED)
/**
* Contact handling
*/
override fun beginContact(contact: Contact) {
val bodyA = contact.fixtureA.body
val bodyB = contact.fixtureB.body
// Both combinations - reducing quadratic complexity to linear
handleContact(bodyA, bodyB)
handleContact(bodyB, bodyA)
}
override fun endContact(contact: Contact) {}
override fun preSolve(contact: Contact, oldManifold: Manifold) {}
override fun postSolve(contact: Contact, impulse: ContactImpulse) {}
}
| core/src/com/sheepsgohome/screens/GameplayClassicModeScreen.kt | 1190603804 |
package com.redmadrobot.inputmask.model
/**
* ### Notation
*
* Custom rule for characters inside square brackets.
*
* Internal `Mask` compiler supports a series of symbols which represent letters and numbers in user input.
* Each symbol stands for its own character set; for instance, `0` and `9` stand for numeric character set.
* This means user can type any digit instead of `0` or `9`, or any letter instead of `A` or `a`.
*
* The difference between `0` and `9` is that `0` stands for a **mandatory** digit, while `9` stands for **optional**.
* This means with the mask like `[099][A]` user may enter `1b`, `12c` or `123d`, while with the mask `[000][A]` user
* won't be able to enter the last letter unless he has entered three digits: `1` or `12` or `123` or `123e`.
*
* Summarizing, each symbol supported by the compiler has its own **character set** associated with it,
* and also has an option to be **mandatory** or not.
*/
data class Notation(
/**
* A symbol in format string.
*/
val character: Char,
/**
* An associated character set of acceptable input characters.
*/
val characterSet: String,
/**
* Is it an optional symbol or mandatory?
*/
val isOptional: Boolean
)
| inputmask/src/main/kotlin/com/redmadrobot/inputmask/model/Notation.kt | 2069338571 |
/*
* Copyright 2017, Abhi Muktheeswarar
*
* 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.abhi.spectacle
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.abhi.spectacle", appContext.packageName)
}
}
| spectacle/src/androidTest/java/com/abhi/spectacle/ExampleInstrumentedTest.kt | 1051125576 |
// PARAM_TYPES: kotlin.Int
// PARAM_DESCRIPTOR: value-parameter a: kotlin.Int defined in A.foo
class A(val n: Int) {
fun foo(a: Int, b: Int = <selection>a + n</selection>) = a + b - n - 1
} | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/initializers/functions/memberFunctionParameters.kt | 2880962409 |
// IS_APPLICABLE: false
class A(s: String) {
fun bar(s: String) {}
}
fun foo(f: (String) -> Unit) {}
fun test() {
foo { A(it).bar(it) <caret>}
} | plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/receiverParameter2.kt | 1525191387 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.keymap.impl
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.configurationStore.SerializableScheme
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.PluginManagerConfigurable
import com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.keymap.ex.KeymapManagerEx
import com.intellij.openapi.options.ExternalizableSchemeAdapter
import com.intellij.openapi.options.SchemeState
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.KeyStrokeAdapter
import com.intellij.util.ArrayUtilRt
import com.intellij.util.SmartList
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.mapSmart
import com.intellij.util.containers.nullize
import org.jdom.Element
import java.util.*
import javax.swing.KeyStroke
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private const val KEY_MAP = "keymap"
private const val KEYBOARD_SHORTCUT = "keyboard-shortcut"
private const val KEYBOARD_GESTURE_SHORTCUT = "keyboard-gesture-shortcut"
private const val KEYBOARD_GESTURE_KEY = "keystroke"
private const val KEYBOARD_GESTURE_MODIFIER = "modifier"
private const val KEYSTROKE_ATTRIBUTE = "keystroke"
private const val FIRST_KEYSTROKE_ATTRIBUTE = "first-keystroke"
private const val SECOND_KEYSTROKE_ATTRIBUTE = "second-keystroke"
private const val ACTION = "action"
private const val VERSION_ATTRIBUTE = "version"
private const val PARENT_ATTRIBUTE = "parent"
private const val NAME_ATTRIBUTE = "name"
private const val ID_ATTRIBUTE = "id"
private const val MOUSE_SHORTCUT = "mouse-shortcut"
fun KeymapImpl(name: String, dataHolder: SchemeDataHolder<KeymapImpl>): KeymapImpl {
val result = KeymapImpl(dataHolder)
result.name = name
result.schemeState = SchemeState.UNCHANGED
return result
}
open class KeymapImpl @JvmOverloads constructor(private var dataHolder: SchemeDataHolder<KeymapImpl>? = null)
: ExternalizableSchemeAdapter(), Keymap, SerializableScheme {
private var parent: KeymapImpl? = null
private var unknownParentName: String? = null
open var canModify: Boolean = true
@JvmField
internal var schemeState: SchemeState? = null
override fun getSchemeState(): SchemeState? = schemeState
private val actionIdToShortcuts = HashMap<String, MutableList<Shortcut>>()
get() {
val dataHolder = dataHolder
if (dataHolder != null) {
this.dataHolder = null
readExternal(dataHolder.read())
}
return field
}
private val keymapManager by lazy { KeymapManagerEx.getInstanceEx()!! }
/**
* @return IDs of the action which are specified in the keymap. It doesn't return IDs of action from parent keymap.
*/
val ownActionIds: Array<String>
get() = actionIdToShortcuts.keys.toTypedArray()
private fun <T> cachedShortcuts(mapper: (Shortcut) -> T?): ReadWriteProperty<Any?, Map<T, MutableList<String>>> =
object : ReadWriteProperty<Any?, Map<T, MutableList<String>>> {
private var cache: Map<T, MutableList<String>>? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): Map<T, MutableList<String>> =
cache ?: mapShortcuts(mapper).also { cache = it }
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Map<T, MutableList<String>>) {
cache = null
}
private fun mapShortcuts(mapper: (Shortcut) -> T?): Map<T, MutableList<String>> {
fun addActionToShortcutMap(actionId: String, map: MutableMap<T, MutableList<String>>) {
for (shortcut in getOwnOrBoundShortcuts(actionId)) {
mapper(shortcut)?.let {
val ids = map.getOrPut(it) { SmartList() }
if (!ids.contains(actionId)) {
ids.add(actionId)
}
}
}
}
val map = HashMap<T, MutableList<String>>()
actionIdToShortcuts.keys.forEach { addActionToShortcutMap(it, map) }
keymapManager.boundActions.forEach { addActionToShortcutMap(it, map) }
return map
}
}
private var keystrokeToActionIds: Map<KeyStroke, MutableList<String>> by cachedShortcuts { (it as? KeyboardShortcut)?.firstKeyStroke }
private var mouseShortcutToActionIds: Map<MouseShortcut, MutableList<String>> by cachedShortcuts { it as? MouseShortcut }
private var gestureToActionIds: Map<KeyboardModifierGestureShortcut, MutableList<String>> by cachedShortcuts { it as? KeyboardModifierGestureShortcut }
override fun getPresentableName(): String = name
override fun deriveKeymap(newName: String): KeymapImpl =
if (canModify()) {
val newKeymap = copy()
newKeymap.name = newName
newKeymap
}
else {
val newKeymap = KeymapImpl()
newKeymap.parent = this
newKeymap.name = newName
newKeymap
}
fun copy(): KeymapImpl =
dataHolder?.let { KeymapImpl(name, it) }
?: copyTo(KeymapImpl())
fun copyTo(otherKeymap: KeymapImpl): KeymapImpl {
otherKeymap.cleanShortcutsCache()
otherKeymap.actionIdToShortcuts.clear()
for (entry in actionIdToShortcuts.entries) {
otherKeymap.actionIdToShortcuts[entry.key] = ContainerUtil.copyList(entry.value)
}
// after actionIdToShortcuts (on first access we lazily read itself)
otherKeymap.parent = parent
otherKeymap.name = name
otherKeymap.canModify = canModify()
return otherKeymap
}
override fun getParent(): KeymapImpl? = parent
final override fun canModify(): Boolean = canModify
override fun addShortcut(actionId: String, shortcut: Shortcut) {
addShortcut(actionId, shortcut, false)
}
fun addShortcut(actionId: String, shortcut: Shortcut, fromSettings: Boolean) {
val list = actionIdToShortcuts.getOrPut(actionId) {
val result = SmartList<Shortcut>()
val boundShortcuts = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
if (boundShortcuts != null) {
result.addAll(boundShortcuts)
}
else {
parent?.getMutableShortcutList(actionId)?.mapTo(result) { convertShortcut(it) }
}
result
}
if (!list.contains(shortcut)) {
list.add(shortcut)
}
if (list.areShortcutsEqualToParent(actionId)) {
actionIdToShortcuts.remove(actionId)
}
cleanShortcutsCache()
fireShortcutChanged(actionId, fromSettings)
}
private fun cleanShortcutsCache() {
keystrokeToActionIds = emptyMap()
mouseShortcutToActionIds = emptyMap()
gestureToActionIds = emptyMap()
schemeState = SchemeState.POSSIBLY_CHANGED
}
override fun removeAllActionShortcuts(actionId: String) {
for (shortcut in getShortcuts(actionId)) {
removeShortcut(actionId, shortcut)
}
}
override fun removeShortcut(actionId: String, toDelete: Shortcut) {
removeShortcut(actionId, toDelete, false)
}
fun removeShortcut(actionId: String, toDelete: Shortcut, fromSettings: Boolean) {
val list = actionIdToShortcuts[actionId]
if (list == null) {
val inherited = keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
?: parent?.getMutableShortcutList(actionId)?.mapSmart { convertShortcut(it) }.nullize()
if (inherited != null) {
var newShortcuts: MutableList<Shortcut>? = null
for (itemIndex in 0..inherited.lastIndex) {
val item = inherited[itemIndex]
if (toDelete == item) {
if (newShortcuts == null) {
newShortcuts = SmartList()
for (notAddedItemIndex in 0 until itemIndex) {
newShortcuts.add(inherited[notAddedItemIndex])
}
}
}
else newShortcuts?.add(item)
}
newShortcuts?.let {
actionIdToShortcuts.put(actionId, it)
}
}
}
else {
val index = list.indexOf(toDelete)
if (index >= 0) {
if (parent == null) {
if (list.size == 1) {
actionIdToShortcuts.remove(actionId)
}
else {
list.removeAt(index)
}
}
else {
list.removeAt(index)
if (list.areShortcutsEqualToParent(actionId)) {
actionIdToShortcuts.remove(actionId)
}
}
}
}
cleanShortcutsCache()
fireShortcutChanged(actionId, fromSettings)
}
private fun MutableList<Shortcut>.areShortcutsEqualToParent(actionId: String) =
parent.let { parent -> parent != null && areShortcutsEqual(this, parent.getMutableShortcutList(actionId).mapSmart { convertShortcut(it) }) }
private fun getOwnOrBoundShortcuts(actionId: String): List<Shortcut> {
actionIdToShortcuts[actionId]?.let {
return it
}
val result = SmartList<Shortcut>()
keymapManager.getActionBinding(actionId)?.let {
result.addAll(getOwnOrBoundShortcuts(it))
}
return result
}
private fun getActionIds(shortcut: KeyboardModifierGestureShortcut): List<String> {
// first, get keystrokes from our own map
val list = SmartList<String>()
for ((key, value) in gestureToActionIds) {
if (shortcut.startsWith(key)) {
list.addAll(value)
}
}
if (parent != null) {
val ids = parent!!.getActionIds(shortcut)
if (ids.isNotEmpty()) {
for (id in ids) {
// add actions from the parent keymap only if they are absent in this keymap
if (!actionIdToShortcuts.containsKey(id)) {
list.add(id)
}
}
}
}
sortInRegistrationOrder(list)
return list
}
override fun getActionIds(firstKeyStroke: KeyStroke): Array<String> {
return ArrayUtilRt.toStringArray(getActionIds(firstKeyStroke, { it.keystrokeToActionIds }, KeymapImpl::convertKeyStroke))
}
override fun getActionIds(firstKeyStroke: KeyStroke, secondKeyStroke: KeyStroke?): Array<String> {
val ids = getActionIds(firstKeyStroke)
var actualBindings: MutableList<String>? = null
for (id in ids) {
val shortcuts = getShortcuts(id)
for (shortcut in shortcuts) {
if (shortcut !is KeyboardShortcut) {
continue
}
if (firstKeyStroke == shortcut.firstKeyStroke && secondKeyStroke == shortcut.secondKeyStroke) {
if (actualBindings == null) {
actualBindings = SmartList()
}
actualBindings.add(id)
break
}
}
}
return ArrayUtilRt.toStringArray(actualBindings)
}
override fun getActionIds(shortcut: Shortcut): Array<String> {
return when (shortcut) {
is KeyboardShortcut -> {
val first = shortcut.firstKeyStroke
val second = shortcut.secondKeyStroke
if (second == null) getActionIds(first) else getActionIds(first, second)
}
is MouseShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut))
is KeyboardModifierGestureShortcut -> ArrayUtilRt.toStringArray(getActionIds(shortcut))
else -> ArrayUtilRt.EMPTY_STRING_ARRAY
}
}
override fun hasActionId(actionId: String, shortcut: MouseShortcut): Boolean {
var convertedShortcut = shortcut
var keymap = this
do {
val list = keymap.mouseShortcutToActionIds[convertedShortcut]
if (list != null && list.contains(actionId)) {
return true
}
val parent = keymap.parent ?: return false
convertedShortcut = keymap.convertMouseShortcut(shortcut)
keymap = parent
}
while (true)
}
override fun getActionIds(shortcut: MouseShortcut): List<String> {
return getActionIds(shortcut, { it.mouseShortcutToActionIds }, KeymapImpl::convertMouseShortcut)
}
private fun <T> getActionIds(shortcut: T,
shortcutToActionIds: (keymap: KeymapImpl) -> Map<T, MutableList<String>>,
convertShortcut: (keymap: KeymapImpl, shortcut: T) -> T): List<String> {
// first, get keystrokes from our own map
var list = shortcutToActionIds(this)[shortcut]
val parentIds = parent?.getActionIds(convertShortcut(this, shortcut), shortcutToActionIds, convertShortcut) ?: emptyList()
var isOriginalListInstance = list != null
for (id in parentIds) {
// add actions from the parent keymap only if they are absent in this keymap
// do not add parent bind actions, if bind-on action is overwritten in the child
if (actionIdToShortcuts.containsKey(id) || actionIdToShortcuts.containsKey(keymapManager.getActionBinding(id))) {
continue
}
if (list == null) {
list = SmartList()
}
else if (isOriginalListInstance) {
list = SmartList(list)
isOriginalListInstance = false
}
if (!list.contains(id)) {
list.add(id)
}
}
sortInRegistrationOrder(list ?: return emptyList())
return list
}
fun isActionBound(actionId: String): Boolean = keymapManager.boundActions.contains(actionId)
override fun getShortcuts(actionId: String?): Array<Shortcut> =
getMutableShortcutList(actionId).let { if (it.isEmpty()) Shortcut.EMPTY_ARRAY else it.toTypedArray() }
private fun getMutableShortcutList(actionId: String?): List<Shortcut> {
if (actionId == null) {
return emptyList()
}
// it is critical to use convertShortcut - otherwise MacOSDefaultKeymap doesn't convert shortcuts
// todo why not convert on add? why we don't need to convert our own shortcuts?
return actionIdToShortcuts[actionId]
?: keymapManager.getActionBinding(actionId)?.let { actionIdToShortcuts[it] }
?: parent?.getMutableShortcutList(actionId)?.mapSmart { convertShortcut(it) }
?: emptyList()
}
fun getOwnShortcuts(actionId: String): Array<Shortcut> {
val own = actionIdToShortcuts[actionId] ?: return Shortcut.EMPTY_ARRAY
return if (own.isEmpty()) Shortcut.EMPTY_ARRAY else own.toTypedArray()
}
fun hasShortcutDefined(actionId: String): Boolean =
actionIdToShortcuts[actionId] != null || parent?.hasShortcutDefined(actionId) == true
// you must clear `actionIdToShortcuts` before calling
protected open fun readExternal(keymapElement: Element) {
if (KEY_MAP != keymapElement.name) {
throw InvalidDataException("unknown element: $keymapElement")
}
name = keymapElement.getAttributeValue(NAME_ATTRIBUTE)!!
unknownParentName = null
keymapElement.getAttributeValue(PARENT_ATTRIBUTE)?.let { parentSchemeName ->
var parentScheme = findParentScheme(parentSchemeName)
if (parentScheme == null && parentSchemeName == "Default for Mac OS X") {
// https://youtrack.jetbrains.com/issue/RUBY-17767#comment=27-1374197
parentScheme = findParentScheme("Mac OS X")
}
if (parentScheme == null) {
logger<KeymapImpl>().warn("Cannot find parent scheme $parentSchemeName for scheme $name")
unknownParentName = parentSchemeName
notifyAboutMissingKeymap(parentSchemeName, IdeBundle.message("notification.content.cannot.find.parent.keymap", parentSchemeName, name), true)
}
else {
parent = parentScheme as KeymapImpl
canModify = true
}
}
val actionIds = HashSet<String>()
val skipInserts = SystemInfo.isMac && (ApplicationManager.getApplication() == null || !ApplicationManager.getApplication().isUnitTestMode)
for (actionElement in keymapElement.children) {
if (actionElement.name != ACTION) {
throw InvalidDataException("unknown element: $actionElement; Keymap's name=$name")
}
val id = actionElement.getAttributeValue(ID_ATTRIBUTE) ?: throw InvalidDataException("Attribute 'id' cannot be null; Keymap's name=$name")
actionIds.add(id)
val shortcuts = SmartList<Shortcut>()
// creating the list even when there are no shortcuts (empty element means that an action overrides a parent one to clear shortcuts)
actionIdToShortcuts[id] = shortcuts
for (shortcutElement in actionElement.children) {
if (KEYBOARD_SHORTCUT == shortcutElement.name) {
// Parse first keystroke
val firstKeyStrokeStr = shortcutElement.getAttributeValue(FIRST_KEYSTROKE_ATTRIBUTE)
?: throw InvalidDataException("Attribute '$FIRST_KEYSTROKE_ATTRIBUTE' cannot be null; Action's id=$id; Keymap's name=$name")
if (skipInserts && firstKeyStrokeStr.contains("INSERT")) {
continue
}
val firstKeyStroke = KeyStrokeAdapter.getKeyStroke(firstKeyStrokeStr) ?: continue
// Parse second keystroke
var secondKeyStroke: KeyStroke? = null
val secondKeyStrokeStr = shortcutElement.getAttributeValue(SECOND_KEYSTROKE_ATTRIBUTE)
if (secondKeyStrokeStr != null) {
secondKeyStroke = KeyStrokeAdapter.getKeyStroke(secondKeyStrokeStr) ?: continue
}
shortcuts.add(KeyboardShortcut(firstKeyStroke, secondKeyStroke))
}
else if (KEYBOARD_GESTURE_SHORTCUT == shortcutElement.name) {
val strokeText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_KEY) ?: throw InvalidDataException(
"Attribute '$KEYBOARD_GESTURE_KEY' cannot be null; Action's id=$id; Keymap's name=$name")
val stroke = KeyStrokeAdapter.getKeyStroke(strokeText) ?: continue
val modifierText = shortcutElement.getAttributeValue(KEYBOARD_GESTURE_MODIFIER)
var modifier: KeyboardGestureAction.ModifierType? = null
if (KeyboardGestureAction.ModifierType.dblClick.toString().equals(modifierText, ignoreCase = true)) {
modifier = KeyboardGestureAction.ModifierType.dblClick
}
else if (KeyboardGestureAction.ModifierType.hold.toString().equals(modifierText, ignoreCase = true)) {
modifier = KeyboardGestureAction.ModifierType.hold
}
if (modifier == null) {
throw InvalidDataException("Wrong modifier=$modifierText action id=$id keymap=$name")
}
shortcuts.add(KeyboardModifierGestureShortcut.newInstance(modifier, stroke))
}
else if (MOUSE_SHORTCUT == shortcutElement.name) {
val keystrokeString = shortcutElement.getAttributeValue(KEYSTROKE_ATTRIBUTE)
?: throw InvalidDataException("Attribute 'keystroke' cannot be null; Action's id=$id; Keymap's name=$name")
try {
shortcuts.add(KeymapUtil.parseMouseShortcut(keystrokeString))
}
catch (e: InvalidDataException) {
throw InvalidDataException("Wrong mouse-shortcut: '$keystrokeString'; Action's id=$id; Keymap's name=$name")
}
}
else {
throw InvalidDataException("unknown element: $shortcutElement; Keymap's name=$name")
}
}
}
ActionsCollectorImpl.onActionsLoadedFromKeymapXml(this, actionIds)
cleanShortcutsCache()
}
protected open fun findParentScheme(parentSchemeName: String): Keymap? = keymapManager.schemeManager.findSchemeByName(parentSchemeName)
override fun writeScheme(): Element {
dataHolder?.let {
return it.read()
}
val keymapElement = Element(KEY_MAP)
keymapElement.setAttribute(VERSION_ATTRIBUTE, "1")
keymapElement.setAttribute(NAME_ATTRIBUTE, name)
(parent?.name ?: unknownParentName)?.let {
keymapElement.setAttribute(PARENT_ATTRIBUTE, it)
}
writeOwnActionIds(keymapElement)
schemeState = SchemeState.UNCHANGED
return keymapElement
}
private fun writeOwnActionIds(keymapElement: Element) {
val ownActionIds = ownActionIds
Arrays.sort(ownActionIds)
for (actionId in ownActionIds) {
val shortcuts = actionIdToShortcuts[actionId] ?: continue
val actionElement = Element(ACTION)
actionElement.setAttribute(ID_ATTRIBUTE, actionId)
for (shortcut in shortcuts) {
when (shortcut) {
is KeyboardShortcut -> {
val element = Element(KEYBOARD_SHORTCUT)
element.setAttribute(FIRST_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(shortcut.firstKeyStroke))
shortcut.secondKeyStroke?.let {
element.setAttribute(SECOND_KEYSTROKE_ATTRIBUTE, KeyStrokeAdapter.toString(it))
}
actionElement.addContent(element)
}
is MouseShortcut -> {
val element = Element(MOUSE_SHORTCUT)
element.setAttribute(KEYSTROKE_ATTRIBUTE, KeymapUtil.getMouseShortcutString(shortcut))
actionElement.addContent(element)
}
is KeyboardModifierGestureShortcut -> {
val element = Element(KEYBOARD_GESTURE_SHORTCUT)
element.setAttribute(KEYBOARD_GESTURE_SHORTCUT, KeyStrokeAdapter.toString(shortcut.stroke))
element.setAttribute(KEYBOARD_GESTURE_MODIFIER, shortcut.type.name)
actionElement.addContent(element)
}
else -> throw IllegalStateException("unknown shortcut class: $shortcut")
}
}
keymapElement.addContent(actionElement)
}
}
fun clearOwnActionsIds() {
actionIdToShortcuts.clear()
cleanShortcutsCache()
}
fun hasOwnActionId(actionId: String): Boolean = actionIdToShortcuts.containsKey(actionId)
fun clearOwnActionsId(actionId: String) {
actionIdToShortcuts.remove(actionId)
cleanShortcutsCache()
}
override fun getActionIds(): Array<String> = ArrayUtilRt.toStringArray(actionIdList)
override fun getActionIdList(): Set<String> {
val ids = LinkedHashSet<String>()
ids.addAll(actionIdToShortcuts.keys)
var parent = parent
while (parent != null) {
ids.addAll(parent.actionIdToShortcuts.keys)
parent = parent.parent
}
return ids
}
override fun getConflicts(actionId: String, keyboardShortcut: KeyboardShortcut): Map<String, MutableList<KeyboardShortcut>> {
val result = HashMap<String, MutableList<KeyboardShortcut>>()
for (id in getActionIds(keyboardShortcut.firstKeyStroke)) {
if (id == actionId || (actionId.startsWith("Editor") && id == "$${actionId.substring(6)}")) {
continue
}
val useShortcutOf = keymapManager.getActionBinding(id)
if (useShortcutOf != null && useShortcutOf == actionId) {
continue
}
for (shortcut1 in getMutableShortcutList(id)) {
if (shortcut1 !is KeyboardShortcut || shortcut1.firstKeyStroke != keyboardShortcut.firstKeyStroke) {
continue
}
if (keyboardShortcut.secondKeyStroke != null && shortcut1.secondKeyStroke != null && keyboardShortcut.secondKeyStroke != shortcut1.secondKeyStroke) {
continue
}
result.getOrPut(id) { SmartList() }.add(shortcut1)
}
}
return result
}
protected open fun convertKeyStroke(keyStroke: KeyStroke): KeyStroke = keyStroke
protected open fun convertMouseShortcut(shortcut: MouseShortcut): MouseShortcut = shortcut
protected open fun convertShortcut(shortcut: Shortcut): Shortcut = shortcut
private fun fireShortcutChanged(actionId: String, fromSettings: Boolean) {
ApplicationManager.getApplication().messageBus.syncPublisher(KeymapManagerListener.TOPIC).shortcutChanged(this, actionId, fromSettings)
}
override fun toString(): String = presentableName
override fun equals(other: Any?): Boolean {
if (other !is KeymapImpl) return false
if (other === this) return true
if (name != other.name) return false
if (canModify != other.canModify) return false
if (parent != other.parent) return false
if (actionIdToShortcuts != other.actionIdToShortcuts) return false
return true
}
override fun hashCode(): Int = name.hashCode()
}
private fun sortInRegistrationOrder(ids: MutableList<String>) {
ids.sortWith(ActionManagerEx.getInstanceEx().registrationOrderComparator)
}
// compare two lists in any order
private fun areShortcutsEqual(shortcuts1: List<Shortcut>, shortcuts2: List<Shortcut>): Boolean {
if (shortcuts1.size != shortcuts2.size) {
return false
}
for (shortcut in shortcuts1) {
if (!shortcuts2.contains(shortcut)) {
return false
}
}
return true
}
@Suppress("SpellCheckingInspection") private const val macOSKeymap = "com.intellij.plugins.macoskeymap"
@Suppress("SpellCheckingInspection") private const val gnomeKeymap = "com.intellij.plugins.gnomekeymap"
@Suppress("SpellCheckingInspection") private const val kdeKeymap = "com.intellij.plugins.kdekeymap"
@Suppress("SpellCheckingInspection") private const val xwinKeymap = "com.intellij.plugins.xwinkeymap"
@Suppress("SpellCheckingInspection") private const val eclipseKeymap = "com.intellij.plugins.eclipsekeymap"
@Suppress("SpellCheckingInspection") private const val emacsKeymap = "com.intellij.plugins.emacskeymap"
@Suppress("SpellCheckingInspection") private const val netbeansKeymap = "com.intellij.plugins.netbeanskeymap"
@Suppress("SpellCheckingInspection") private const val qtcreatorKeymap = "com.intellij.plugins.qtcreatorkeymap"
@Suppress("SpellCheckingInspection") private const val resharperKeymap = "com.intellij.plugins.resharperkeymap"
@Suppress("SpellCheckingInspection") private const val sublimeKeymap = "com.intellij.plugins.sublimetextkeymap"
@Suppress("SpellCheckingInspection") private const val visualStudioKeymap = "com.intellij.plugins.visualstudiokeymap"
private const val visualStudio2022Keymap = "com.intellij.plugins.visualstudio2022keymap"
@Suppress("SpellCheckingInspection") private const val xcodeKeymap = "com.intellij.plugins.xcodekeymap"
@Suppress("SpellCheckingInspection") private const val visualAssistKeymap = "com.intellij.plugins.visualassistkeymap"
@Suppress("SpellCheckingInspection") private const val riderKeymap = "com.intellij.plugins.riderkeymap"
@Suppress("SpellCheckingInspection") private const val vsCodeKeymap = "com.intellij.plugins.vscodekeymap"
@Suppress("SpellCheckingInspection") private const val vsForMacKeymap = "com.intellij.plugins.vsformackeymap"
internal fun notifyAboutMissingKeymap(keymapName: String, @NlsContexts.NotificationContent message: String, isParent: Boolean) {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(project: Project) {
connection.disconnect()
ApplicationManager.getApplication().invokeLater(
{
// TODO remove when PluginAdvertiser implements that
val pluginId = when (keymapName) {
"Mac OS X",
"Mac OS X 10.5+" -> macOSKeymap
"Default for GNOME" -> gnomeKeymap
"Default for KDE" -> kdeKeymap
"Default for XWin" -> xwinKeymap
"Eclipse",
"Eclipse (Mac OS X)" -> eclipseKeymap
"Emacs" -> emacsKeymap
"NetBeans 6.5" -> netbeansKeymap
"QtCreator",
"QtCreator OSX" -> qtcreatorKeymap
"ReSharper",
"ReSharper OSX" -> resharperKeymap
"Sublime Text",
"Sublime Text (Mac OS X)" -> sublimeKeymap
"Visual Studio",
"Visual Studio OSX" -> visualStudioKeymap
"Visual Studio 2022" -> visualStudio2022Keymap
"Visual Assist",
"Visual Assist OSX" -> visualAssistKeymap
"Xcode" -> xcodeKeymap
"Visual Studio for Mac" -> vsForMacKeymap
"Rider",
"Rider OSX"-> riderKeymap
"VSCode",
"VSCode OSX"-> vsCodeKeymap
else -> null
}
val action: AnAction = when (pluginId) {
null -> object : NotificationAction(IdeBundle.message("action.text.search.for.keymap", keymapName)) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
//TODO enableSearch("$keymapName /tag:Keymap")?.run()
ShowSettingsUtil.getInstance().showSettingsDialog(e.project, PluginManagerConfigurable::class.java)
}
}
else -> object : NotificationAction(IdeBundle.message("action.text.install.keymap", keymapName)) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
val connect = ApplicationManager.getApplication().messageBus.connect()
connect.subscribe(KeymapManagerListener.TOPIC, object: KeymapManagerListener {
override fun keymapAdded(keymap: Keymap) {
ApplicationManager.getApplication().invokeLater {
if (keymap.name == keymapName) {
connect.disconnect()
val successMessage = if (isParent) IdeBundle.message("notification.content.keymap.successfully.installed", keymapName)
else {
KeymapManagerEx.getInstanceEx().activeKeymap = keymap
IdeBundle.message("notification.content.keymap.successfully.activated", keymapName)
}
Notification("KeymapInstalled", successMessage,
NotificationType.INFORMATION).notify(e.project)
}
}
}
})
val plugins = mutableSetOf(PluginId.getId(pluginId))
when (pluginId) {
gnomeKeymap, kdeKeymap -> plugins += PluginId.getId(xwinKeymap)
resharperKeymap -> plugins += PluginId.getId(visualStudioKeymap)
visualAssistKeymap -> plugins += PluginId.getId(visualStudioKeymap)
visualStudio2022Keymap -> plugins += PluginId.getId(visualStudioKeymap)
xcodeKeymap, vsForMacKeymap -> plugins += PluginId.getId(macOSKeymap)
}
installAndEnable(project, plugins) { }
notification.expire()
}
}
}
Notification("KeymapMissing", IdeBundle.message("notification.group.missing.keymap"),
message, NotificationType.ERROR)
.addAction(action)
.notify(project)
},
ModalityState.NON_MODAL)
}
})
}
| platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.kt | 1188265038 |
package org.gittner.osmbugs.mapdust
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.widget.addTextChangedListener
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.gittner.osmbugs.R
import org.gittner.osmbugs.databinding.DialogAddMapdustErrorBinding
import org.gittner.osmbugs.ui.ErrorViewModel
import org.osmdroid.api.IGeoPoint
class MapdustAddErrorDialog(context: Context, viewModel: ErrorViewModel, mapCenter: IGeoPoint, successCb: SuccessCb) : AlertDialog(context) {
private val mViewModel = viewModel
private val mMapCenter = mapCenter
private val mSuccessCb = successCb
override fun onCreate(savedInstanceState: Bundle?) {
setTitle(R.string.dialog_add_mapdust_error_title)
val v = layoutInflater.inflate(R.layout.dialog_add_mapdust_error, null)
setView(v)
val binding = DialogAddMapdustErrorBinding.bind(v)
binding.apply {
spinner.adapter = MapdustTypeAdapter(context)
edtxtComment.addTextChangedListener {
imgSave.visibility = if (it!!.isEmpty()) View.GONE else View.VISIBLE
}
imgSave.setOnClickListener {
MainScope().launch {
progressbarSave.visibility = View.VISIBLE
imgSave.visibility = View.GONE
edtxtComment.isEnabled = false
try {
mViewModel.addMapdustError(
mMapCenter,
spinner.selectedItem as MapdustError.ERROR_TYPE,
edtxtComment.text.toString()
)
dismiss()
mSuccessCb.onSuccess()
} catch (err: Exception) {
Toast.makeText(context, context.getString(R.string.failed_to_add_error).format(err.message), Toast.LENGTH_LONG).show()
} finally {
progressbarSave.visibility = View.GONE
imgSave.visibility = View.VISIBLE
edtxtComment.isEnabled = true
}
}
}
}
super.onCreate(savedInstanceState)
}
interface SuccessCb {
fun onSuccess()
}
} | app/src/main/java/org/gittner/osmbugs/mapdust/MapdustAddErrorDialog.kt | 161805987 |
package au.id.micolous.metrodroid.util
import au.id.micolous.metrodroid.card.classic.ClassicSector
import au.id.micolous.metrodroid.key.ClassicSectorKey
import au.id.micolous.metrodroid.multi.Log
object HashUtils {
private fun calculateCRCReversed(data: ImmutableByteArray, init: Int, table: IntArray) =
data.fold(init) { cur1, b -> (cur1 shr 8) xor table[(cur1 xor b.toInt()) and 0xff] }
private fun getCRCTableReversed(poly: Int) =
(0..255).map { v ->
(0..7).fold(v) { cur, _ ->
if ((cur and 1) != 0)
(cur shr 1) xor poly
else
(cur shr 1)
}
}.toIntArray()
private val CRC16_IBM_TABLE = getCRCTableReversed(0xa001)
fun calculateCRC16IBM(data: ImmutableByteArray, crc: Int = 0) =
calculateCRCReversed(data, crc, CRC16_IBM_TABLE)
/**
* Checks if a salted hash of a value is found in a group of expected hash values.
*
* This is only really useful for MIFARE Classic cards, where the only way to identify a
* particular transit card is to check the key against a known list. We don't want to ship
* any agency-specific keys with Metrodroid (no matter how well-known they are), so this
* obfuscates the keys.
*
* It is fairly straight forward to crack any MIFARE Classic card anyway, and this is only
* intended to be "on par" with the level of security on the cards themselves.
*
* This isn't useful for **all** cards, and should only be used as a last resort. Many transit
* cards implement key diversification on all sectors (ie: every sector of every card has a key
* that is unique to a single card), which renders this technique unusable.
*
* The hash is defined as:
*
* hash = lowercase(base16(md5(salt + key + salt)))
*
* @param key The key to test.
* @param salt The salt string to add to the key.
* @param expectedHashes Expected hash values that might be returned.
* @return The index of the hash that matched, or a number less than 0 if the value was not
* found, or there was some other error with the input.
*/
fun checkKeyHash(key: ImmutableByteArray, salt: String, vararg expectedHashes: String): Int {
// Validate input arguments.
if (expectedHashes.isEmpty()) {
return -1
}
val md5 = MD5Ctx()
md5.update(ImmutableByteArray.fromASCII(salt))
md5.update(key)
md5.update(ImmutableByteArray.fromASCII(salt))
val digest = md5.digest().toHexString()
Log.d(TAG, "Key digest: $digest")
return expectedHashes.indexOf(digest)
}
/**
* Checks a keyhash with a {@link ClassicSectorKey}.
*
* See {@link #checkKeyHash(ImmutableByteArray, String, String...)} for further information.
*
* @param key The key to check. If this is null, then this will always return a value less than
* 0 (ie: error).
*/
fun checkKeyHash(key: ClassicSectorKey?, salt: String, vararg expectedHashes: String): Int {
if (key == null)
return -1
return checkKeyHash(key.key, salt, *expectedHashes)
}
fun checkKeyHash(key: ClassicSector?, salt: String, vararg expectedHashes: String): Int {
if (key == null)
return -1
val a = checkKeyHash(key.keyA, salt, *expectedHashes)
if (a != -1)
return a
return checkKeyHash(key.keyB, salt, *expectedHashes)
}
private const val TAG = "HashUtils"
}
| src/commonMain/kotlin/au/id/micolous/metrodroid/util/HashUtils.kt | 1887805736 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.testFramework
import com.intellij.TestCaseLoader
import org.junit.Assert
import org.junit.Test
import java.util.*
class FairBucketingTest {
private data class BucketedClass(var className: String, var expectedBucket: Int)
private val totalBucketsCount = 5
private val testClasses = Arrays.asList<BucketedClass>(
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaBuildOnJavaTest", 0),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaBuildOnKotlinTest", 1),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaCleanImportMavenProjectTest", 2),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaCreateAllServicesAndExtensionsTest", 3),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaGenerationTurbochargedSharedIndexesTest", 4),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaIndexingJavaProjectTest", 0),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaInspectionOnJavaProjectTest", 1),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaInspectionOnKotlinProjectTest", 2),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaInspectionOnSpringProjectTest", 3),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaJdkClassesCheckOnRedAfterRestartTest", 4),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaKotlinGradleOpenFilesTest", 0),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaOpenGradleProjectTest", 1),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaOpenMavenProjectTest", 2),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaReopenKotlinProjectFromCacheTest", 3),
BucketedClass("com.intellij.integrationTests.smoke.idea.IdeaSpringCloudOpenFilesTest", 4)
)
@Test
fun fairBucketingWorks() {
for (currentBucket in 0 until totalBucketsCount) {
for (testData in testClasses) {
val isMatchedBucket = testData.expectedBucket == currentBucket
Assert.assertEquals(String.format("Class `%s` should be in bucket %s", testData.className, currentBucket),
isMatchedBucket,
TestCaseLoader.matchesCurrentBucketFair(testData.className, totalBucketsCount, currentBucket))
}
}
}
@Test
fun multipleFairBucketingInvocation() {
fairBucketingWorks()
fairBucketingWorks()
fairBucketingWorks()
}
@Test
fun initTestBucketsDoesNotThrow() {
TestCaseLoader.initFairBuckets()
}
} | platform/testFramework/testSrc/com/intellij/testFramework/FairBucketingTest.kt | 1056470448 |
package org.thoughtcrime.securesms.mediasend.v2
import android.Manifest
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.permissions.Permissions
import org.thoughtcrime.securesms.util.navigation.safeNavigate
class MediaSelectionNavigator(
private val toCamera: Int = -1,
private val toGallery: Int = -1
) {
fun goToReview(navController: NavController) {
navController.popBackStack(R.id.mediaReviewFragment, false)
}
fun goToCamera(navController: NavController) {
if (toCamera == -1) return
navController.safeNavigate(toCamera)
}
fun goToGallery(navController: NavController) {
if (toGallery == -1) return
navController.safeNavigate(toGallery)
}
companion object {
fun Fragment.requestPermissionsForCamera(
onGranted: () -> Unit
) {
Permissions.with(this)
.request(Manifest.permission.CAMERA)
.ifNecessary()
.withRationaleDialog(getString(R.string.ConversationActivity_to_capture_photos_and_video_allow_signal_access_to_the_camera), R.drawable.ic_camera_24)
.withPermanentDenialDialog(getString(R.string.ConversationActivity_signal_needs_the_camera_permission_to_take_photos_or_video))
.onAllGranted(onGranted)
.onAnyDenied { Toast.makeText(requireContext(), R.string.ConversationActivity_signal_needs_camera_permissions_to_take_photos_or_video, Toast.LENGTH_LONG).show() }
.execute()
}
fun Fragment.requestPermissionsForGallery(
onGranted: () -> Unit
) {
Permissions.with(this)
.request(Manifest.permission.READ_EXTERNAL_STORAGE)
.ifNecessary()
.withPermanentDenialDialog(getString(R.string.AttachmentKeyboard_Signal_needs_permission_to_show_your_photos_and_videos))
.onAllGranted(onGranted)
.onAnyDenied { Toast.makeText(this.requireContext(), R.string.AttachmentKeyboard_Signal_needs_permission_to_show_your_photos_and_videos, Toast.LENGTH_LONG).show() }
.execute()
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/MediaSelectionNavigator.kt | 2643070100 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.impl
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiPolyVariantReferenceBase
import com.intellij.util.ArrayUtil
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference
abstract class GroovyReferenceBase<T : PsiElement>(
element: T
) : PsiPolyVariantReferenceBase<T>(element), GroovyReference {
override fun getVariants(): Array<out Any> = ArrayUtil.EMPTY_OBJECT_ARRAY
override fun resolve(): PsiElement? = super<GroovyReference>.resolve()
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyReferenceBase.kt | 3414723495 |
/*
MIT License
Copyright (c) 2020 Tiago Ornelas
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.thoughtcrime.securesms.components.segmentedprogressbar
/**
* Created by Tiago Ornelas on 18/04/2020.
* Interface to communicate progress events
*/
interface SegmentedProgressBarListener {
/**
* Notifies when selected segment changed
*/
fun onPage(oldPageIndex: Int, newPageIndex: Int)
/**
* Notifies when last segment finished animating
*/
fun onFinished()
fun onRequestSegmentProgressPercentage(): Float?
}
| app/src/main/java/org/thoughtcrime/securesms/components/segmentedprogressbar/SegmentedProgressBarListener.kt | 232904275 |
package rustyengine.resources;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.SynchronousAssetLoader;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.Array;
import com.esotericsoftware.minlog.Log;
class ShaderLoader(fileHandleResolver: FileHandleResolver) :
SynchronousAssetLoader<ShaderProgram, ShaderParameter>(fileHandleResolver) {
override fun load(assetManager: AssetManager, fileName: String, file: FileHandle, parameter: ShaderParameter?):
ShaderProgram {
val dir = file.parent()
val program = ShaderProgram(dir.child(file.name() + ".vert"), dir.child(file.name() + ".frag"))
if (!program.isCompiled) {
Log.error(program.log)
}
return program
}
override fun getDependencies(fileName: String, file: FileHandle, parameter: ShaderParameter?):
Array<AssetDescriptor<Any>> = Array()
}
| core/src/rustyengine/resources/ShaderLoader.kt | 3718587547 |
/*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("unused", "UNUSED_PARAMETER")
package io.ktor.tests.velocity
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.conditionalheaders.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import io.ktor.server.velocity.*
import org.apache.velocity.runtime.resource.loader.*
import org.apache.velocity.runtime.resource.util.*
import org.apache.velocity.tools.config.*
import java.util.*
import kotlin.test.*
@Suppress("DEPRECATION")
class VelocityToolsTest {
@Test
fun testBareVelocity() {
withTestApplication {
application.setUpTestTemplates()
application.install(ConditionalHeaders)
application.routing {
val model = mapOf("id" to 1, "title" to "Bonjour le monde!")
get("/") {
call.respondTemplate("test.vl", model)
}
}
val call = handleRequest(HttpMethod.Get, "/")
with(call.response) {
assertNotNull(content)
val lines = content!!.lines()
assertEquals("<p>Hello, 1</p>", lines[0])
assertEquals("<h1>Bonjour le monde!</h1>", lines[1])
assertEquals("<i></i>", lines[2])
}
}
}
@Test
fun testStandardTools() {
withTestApplication {
application.setUpTestTemplates {
addDefaultTools()
setProperty("locale", "en_US")
}
application.install(ConditionalHeaders)
application.routing {
val model = mapOf("id" to 1, "title" to "Bonjour le monde!")
get("/") {
call.respondTemplate("test.vl", model)
}
}
val call = handleRequest(HttpMethod.Get, "/")
with(call.response) {
assertNotNull(content)
val lines = content!!.lines()
assertEquals("<p>Hello, 1</p>", lines[0])
assertEquals("<h1>Bonjour le monde!</h1>", lines[1])
assertEquals("<i>October</i>", lines[2])
}
}
}
class DateTool {
fun toDate(vararg Any: Any): Date? = null
fun format(vararg Any: Any) = "today"
}
@Test
fun testCustomTool() {
withTestApplication {
application.setUpTestTemplates {
tool(DateTool::class.java)
}
application.install(ConditionalHeaders)
application.routing {
val model = mapOf("id" to 1, "title" to "Bonjour le monde!")
get("/") {
call.respondTemplate("test.vl", model)
}
}
val call = handleRequest(HttpMethod.Get, "/")
with(call.response) {
assertNotNull(content)
val lines = content!!.lines()
assertEquals("<p>Hello, 1</p>", lines[0])
assertEquals("<h1>Bonjour le monde!</h1>", lines[1])
assertEquals("<i>today</i>", lines[2])
}
}
}
@Test
fun testConfigureLocale() {
withTestApplication {
application.setUpTestTemplates {
addDefaultTools()
setProperty("locale", "fr_FR")
}
application.install(ConditionalHeaders)
application.routing {
val model = mapOf("id" to 1, "title" to "Bonjour le monde!")
get("/") {
call.respondTemplate("test.vl", model)
}
}
val call = handleRequest(HttpMethod.Get, "/")
with(call.response) {
assertNotNull(content)
val lines = content!!.lines()
assertEquals("<p>Hello, 1</p>", lines[0])
assertEquals("<h1>Bonjour le monde!</h1>", lines[1])
assertEquals("<i>octobre</i>", lines[2])
}
}
}
@Test
fun testNoVelocityConfig() {
withTestApplication {
application.install(VelocityTools)
application.routing {
val model = mapOf("id" to 1, "title" to "Bonjour le monde!")
get("/") {
// default engine resource loader is 'file',
// default test working directory is ktor-velocity project root
call.respondTemplate("jvm/test/resources/test-template.vhtml", model)
}
}
val call = handleRequest(HttpMethod.Get, "/")
with(call.response) {
assertNotNull(content)
val lines = content!!.lines()
assertEquals("<p>Hello, 1</p>", lines[0])
assertEquals("<h1>Bonjour le monde!</h1>", lines[1])
assertEquals("<i></i>", lines[2])
}
}
}
private fun Application.setUpTestTemplates(config: EasyFactoryConfiguration.() -> Unit = {}) {
val bax = "$"
install(VelocityTools) {
engine {
setProperty("resource.loader", "string")
addProperty("resource.loader.string.name", "myRepo")
addProperty("resource.loader.string.class", StringResourceLoader::class.java.name)
addProperty("resource.loader.string.repository.name", "myRepo")
}
apply(config)
StringResourceRepositoryImpl().apply {
putStringResource(
"test.vl",
"""
<p>Hello, ${bax}id</p>
<h1>${bax}title</h1>
<i>$bax!{date.format('MMMM', ${bax}date.toDate('intl', '2003-10-07 03:14:50'))}</i>
""".trimIndent()
)
StringResourceLoader.setRepository("myRepo", this)
}
}
}
}
| ktor-server/ktor-server-plugins/ktor-server-velocity/jvm/test/io/ktor/tests/velocity/VelocityToolsTest.kt | 963836652 |
package com.bigscreen.binarygame.setting
import dagger.Module
import dagger.Provides
import dagger.Subcomponent
@Subcomponent(modules = [(SettingModule::class)])
interface SettingComponent {
fun inject(activityDelegate: SettingActivityDelegate)
}
@Module
class SettingModule {
@Provides
fun providesPresenter(presenter: SettingPresenter): SettingContract.Presenter = presenter
} | app/src/main/java/com/bigscreen/binarygame/setting/SettingModule.kt | 2350736497 |
package com.hea3ven.idolscraper.imageenhancer
class DefaultEnhancer : ImageEnhancer {
override fun enhance(url: String): String {
return url
}
}
| src/main/kotlin/com/hea3ven/idolscraper/imageenhancer/DefaultEnhancer.kt | 2125243475 |
package blue.aodev.animeultimetv.data.model
data class AnimeDetails(
val synopsis: String,
val productionYears: IntRange,
val studios: List<String>,
val genres: List<String>,
val author: String
) | app/src/main/java/blue/aodev/animeultimetv/data/model/AnimeDetails.kt | 2083226159 |
/*
* Copyright (C) 2018 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.texter.main
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
infix fun Disposable.addTo(compositeDisposable: CompositeDisposable) = compositeDisposable.add(this)
| texter/src/main/kotlin/pl/org/seva/texter/main/DisposableObserver.kt | 752159677 |
/*
* Copyright 2021 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.grip
import io.michaelrocks.grip.io.FileSource
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.getObjectType
import io.michaelrocks.grip.mirrors.getObjectTypeByInternalName
import io.michaelrocks.mockito.RETURNS_DEEP_STUBS
import io.michaelrocks.mockito.any
import io.michaelrocks.mockito.given
import io.michaelrocks.mockito.mock
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
class FileRegistryImplTest {
@Test
fun containsFile() {
val source = mock<FileSource>()
val file = File("source1")
val factory = mock<FileSource.Factory>()
given(factory.createFileSource(file.canonicalFile)).thenReturn(source)
val registry = FileRegistryImpl(listOf(file), factory)
assertTrue(registry.contains(file))
assertFalse(registry.contains(File("source2")))
}
@Test
fun containsType() {
val source = mock<FileSource>()
given(source.listFiles(any())).thenAnswer {
@Suppress("UNCHECKED_CAST")
val callback = it.arguments[0] as (name: String, type: FileSource.EntryType) -> Unit
callback("Type1.class", FileSource.EntryType.CLASS)
}
val file = File("source")
val factory = mock<FileSource.Factory>()
given(factory.createFileSource(file.canonicalFile)).thenReturn(source)
val registry = FileRegistryImpl(listOf(file), factory)
assertTrue(registry.contains(getObjectTypeByInternalName("Type1")))
assertFalse(registry.contains(getObjectTypeByInternalName("Type2")))
}
@Test
fun classpath() {
val classpath = (1..1000).map { File("source$it") }
val factory = mock<FileSource.Factory>(RETURNS_DEEP_STUBS)
val registry = FileRegistryImpl(classpath, factory)
assertEquals(classpath.map { it.canonicalFile }, registry.classpath().toList())
}
@Test
fun readClass() {
val data = ByteArray(0)
val source = mock<FileSource>()
given(source.listFiles(any())).thenAnswer {
@Suppress("UNCHECKED_CAST")
val callback = it.arguments[0] as (name: String, type: FileSource.EntryType) -> Unit
callback("Type1.class", FileSource.EntryType.CLASS)
}
given(source.readFile("Type1.class")).thenReturn(data)
val file = File("source")
val factory = mock<FileSource.Factory>()
given(factory.createFileSource(file.canonicalFile)).thenReturn(source)
val registry = FileRegistryImpl(listOf(file), factory)
assertSame(data, registry.readClass(getObjectTypeByInternalName("Type1")))
assertThrows<IllegalArgumentException> { registry.readClass(getObjectTypeByInternalName("Type2")) }
}
@Test
fun findTypesForFile() {
val source1 = mock<FileSource>()
given(source1.listFiles(any())).thenAnswer {
@Suppress("UNCHECKED_CAST")
val callback = it.arguments[0] as (name: String, type: FileSource.EntryType) -> Unit
callback("Type1.class", FileSource.EntryType.CLASS)
}
val source2 = mock<FileSource>()
val file1 = File("file1")
val file2 = File("file2")
val factory = mock<FileSource.Factory>()
given(factory.createFileSource(file1.canonicalFile)).thenReturn(source1)
given(factory.createFileSource(file2.canonicalFile)).thenReturn(source2)
val registry = FileRegistryImpl(listOf(file1, file2), factory)
assertEquals(listOf(getObjectTypeByInternalName("Type1")), registry.findTypesForFile(file1).toList())
assertEquals(listOf<Type.Object>(), registry.findTypesForFile(file2).toList())
assertThrows<IllegalArgumentException> { registry.findTypesForFile(File("file3")) }
}
@Test
fun close() {
val factory = mock<FileSource.Factory>(RETURNS_DEEP_STUBS)
val registry = FileRegistryImpl(listOf(File("source")), factory)
registry.close()
assertThrows<IllegalStateException> { registry.contains(File("source")) }
assertThrows<IllegalStateException> { registry.contains(getObjectType<Any>()) }
assertThrows<IllegalStateException> { registry.classpath() }
assertThrows<IllegalStateException> { registry.readClass(getObjectType<Any>()) }
assertThrows<IllegalStateException> { registry.findTypesForFile(File("source")) }
registry.close()
}
private inline fun <reified T : Throwable> assertThrows(noinline body: () -> Any) {
assertThrows(T::class.java, body)
}
private fun <T : Throwable> assertThrows(exceptionClass: Class<T>, body: () -> Any) {
try {
body()
throw AssertionError("$exceptionClass expected but no exception was thrown")
} catch (exception: Throwable) {
if (exception.javaClass != exceptionClass) {
throw AssertionError("$exceptionClass expected but ${exception.javaClass} was thrown")
}
}
}
}
| library/src/test/java/io/michaelrocks/grip/FileRegistryImplTest.kt | 1837802899 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val NV_framebuffer_mixed_samples = "NVFramebufferMixedSamples".nativeClassGL("NV_framebuffer_mixed_samples", postfix = NV) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension allows multisample rendering with a raster and
depth/stencil sample count that is larger than the color sample count.
Rasterization and the results of the depth and stencil tests together
determine the portion of a pixel that is "covered". It can be useful to
evaluate coverage at a higher frequency than color samples are stored.
This coverage is then "reduced" to a collection of covered color samples,
each having an opacity value corresponding to the fraction of the color
sample covered. The opacity can optionally be blended into individual
color samples.
"""
IntConstant(
"Accepted by the {@code cap} parameter of Enable, Disable, IsEnabled.",
"RASTER_MULTISAMPLE_EXT"..0x9327,
"COVERAGE_MODULATION_TABLE_NV"..0x9331
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv.",
"RASTER_SAMPLES_EXT"..0x9328,
"MAX_RASTER_SAMPLES_EXT"..0x9329,
"RASTER_FIXED_SAMPLE_LOCATIONS_EXT"..0x932A,
"MULTISAMPLE_RASTERIZATION_ALLOWED_EXT"..0x932B,
"EFFECTIVE_RASTER_SAMPLES_EXT"..0x932C,
// COLOR_SAMPLES_NV is shared with NV_multisample_coverage
"COLOR_SAMPLES_NV"..0x8E20,
"DEPTH_SAMPLES_NV"..0x932D,
"STENCIL_SAMPLES_NV"..0x932E,
"MIXED_DEPTH_SAMPLES_SUPPORTED_NV"..0x932F,
"MIXED_STENCIL_SAMPLES_SUPPORTED_NV"..0x9330,
"COVERAGE_MODULATION_NV"..0x9332,
"COVERAGE_MODULATION_TABLE_SIZE_NV"..0x9333
)
reuse(EXT_raster_multisample, "RasterSamplesEXT")
void(
"CoverageModulationTableNV",
"",
AutoSize("v")..GLsizei("n", "The size of the coverage modulation table. Must be equal to the value of COVERAGE_MODULATION_TABLE_SIZE_NV."),
GLfloat.const.p("v", "")
)
void(
"GetCoverageModulationTableNV",
"",
AutoSize("v")..GLsizei("bufsize", ""),
GLfloat.p("v", "")
)
void(
"CoverageModulationNV",
"",
GLenum("components", "")
)
}
| modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/NV_framebuffer_mixed_samples.kt | 822717735 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package egl.templates
import egl.*
import org.lwjgl.generator.*
val KHR_mutable_render_buffer = "KHRMutableRenderBuffer".nativeClassEGL("KHR_mutable_render_buffer", postfix = KHR) {
documentation =
"""
Native bindings to the $registryLink extension.
The aim of this extension is to allow toggling of front-buffer rendering for window surfaces after their initial creation.
This allows for implementations to switch between back-buffered and single-buffered rendering without requiring re-creation of the surface. It is not
expected for toggling to be a frequent event.
This extension does not guarantee when rendering results appear on-screen. To avoid incorrect results, applications will need to use mechanisms not
included in this extension to synchronize rendering with the display. This functionality is not covered by this extension, and vendors are encouraged
to provide guidelines on how this is achieved on their implementation.
Requires ${EGL12.core}.
"""
IntConstant(
"Accepted as a new value for the #SURFACE_TYPE {@code EGLConfig} attribute.",
"MUTABLE_RENDER_BUFFER_BIT_KHR"..0x00001000
)
} | modules/lwjgl/egl/src/templates/kotlin/egl/templates/KHR_mutable_render_buffer.kt | 1032801621 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.persistence.local.room.dao
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Transaction
import com.google.android.ground.persistence.local.room.entity.SurveyEntity
import com.google.android.ground.persistence.local.room.relations.SurveyEntityAndRelations
import io.reactivex.Maybe
import io.reactivex.Single
@Dao
interface SurveyDao : BaseDao<SurveyEntity> {
@Transaction
@Query("SELECT * FROM survey")
fun getAllSurveys(): Single<List<SurveyEntityAndRelations>>
@Transaction
@Query("SELECT * FROM survey WHERE id = :id")
fun getSurveyById(id: String): Maybe<SurveyEntityAndRelations>
}
| ground/src/main/java/com/google/android/ground/persistence/local/room/dao/SurveyDao.kt | 918216908 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.lang.jvm.DefaultJvmElementVisitor
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmField
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.types.JvmReferenceType
import com.intellij.lang.jvm.util.JvmInheritanceUtil.isInheritor
import com.intellij.lang.jvm.util.JvmUtil
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import org.jetbrains.idea.devkit.util.ExtensionCandidate
import org.jetbrains.idea.devkit.util.ExtensionLocator
class StatefulEpInspection2 : DevKitJvmInspection() {
override fun buildVisitor(project: Project, sink: HighlightSink, isOnTheFly: Boolean): DefaultJvmElementVisitor<Boolean?> = object : DefaultJvmElementVisitor<Boolean?> {
override fun visitField(field: JvmField): Boolean? {
val clazz = field.containingClass ?: return null
val fieldTypeClass = JvmUtil.resolveClass(field.type as? JvmReferenceType) ?: return null
val isQuickFix by lazy(LazyThreadSafetyMode.NONE) { isInheritor(clazz, localQuickFixFqn) }
val targets = findEpCandidates(project, clazz)
if (targets.isEmpty() && !isQuickFix) return null
if (isInheritor(fieldTypeClass, PsiElement::class.java.canonicalName)) {
sink.highlight(
"Potential memory leak: don't hold PsiElement, use SmartPsiElementPointer instead${if (isQuickFix) "; also see LocalQuickFixOnPsiElement" else ""}"
)
return false
}
if (isInheritor(fieldTypeClass, PsiReference::class.java.canonicalName)) {
sink.highlight(message(PsiReference::class.java.simpleName, isQuickFix))
return false
}
if (!isProjectFieldAllowed(field, clazz, targets) && isInheritor(fieldTypeClass, Project::class.java.canonicalName)) {
sink.highlight(message(Project::class.java.simpleName, isQuickFix))
return false
}
return false
}
}
companion object {
private val localQuickFixFqn = LocalQuickFix::class.java.canonicalName
private val projectComponentFqn = ProjectComponent::class.java.canonicalName
private fun findEpCandidates(project: Project, clazz: JvmClass): Collection<ExtensionCandidate> {
val name = clazz.name ?: return emptyList()
return ExtensionLocator.byClass(project, clazz).findCandidates().filter { candidate ->
val forClass = candidate.pointer.element?.getAttributeValue("forClass")
forClass == null || !forClass.contains(name)
}
}
private fun isProjectFieldAllowed(field: JvmField, clazz: JvmClass, targets: Collection<ExtensionCandidate>): Boolean {
val finalField = field.hasModifier(JvmModifier.FINAL)
if (finalField) return true
val isProjectEP = targets.any { candidate ->
val name = candidate.pointer.element?.name
"projectService" == name || "projectConfigurable" == name
}
if (isProjectEP) return true
return isInheritor(clazz, projectComponentFqn)
}
private fun message(what: String, quickFix: Boolean): String {
val where = if (quickFix) "quick fix" else "extension"
return "Don't use $what as a field in $where"
}
}
}
| plugins/devkit/devkit-core/src/inspections/StatefulEpInspection2.kt | 3127537456 |
package org.livingdoc.engine.execution.examples.scenarios.matching
/**
* Represents a template specified by a fixture developer for scenario steps. Used for matching scenario
* steps to methods in a fixture. A valid `StepTemplate` consists of a sequence of fragments (text and variables).
* The sequence of fragments is never empty and does not contain two consecutive fragments of the same type.
*
* Variables can be quoted with optional `quotationCharacters` (e.g. single quotation marks). A matching step
* *must* contain exactly the same quotation characters. By default, no quotation characters are used.
*/
internal class StepTemplate(
val fragments: List<Fragment>,
val quotationCharacters: Set<Char>
) {
init {
assert(!fragments.isEmpty())
assertAlternatingSequenceOfFragments()
}
private fun assertAlternatingSequenceOfFragments() {
var wasTextFragment = fragments.first() !is Text
fragments.forEach {
assert(wasTextFragment xor (it is Text))
wasTextFragment = it is Text
}
}
/**
* Returns an `Alignment` of the template and the specified scenario step.
*/
fun alignWith(step: String, maxCostOfAlignment: Int = 20) = Alignment(this, step, maxCostOfAlignment)
override fun toString(): String = fragments.joinToString(separator = "") {
when (it) {
is Text -> it.content
is Variable -> "{${it.name}}"
}
}
companion object {
/**
* Reads a template for a scenario step description from a string. Optionally takes a set of quotation
* characters for variable separation.
*
* @return a valid `StepTemplate`
* @throws IllegalFormatException if the specified template string is malformed
*/
fun parse(templateAsString: String, quotationCharacters: Set<Char> = emptySet()) =
StepTemplate(parseString(templateAsString), quotationCharacters)
private fun parseString(templateAsString: String): List<Fragment> {
if (templateAsString.isEmpty()) {
throw IllegalFormatException("StepTemplates cannot be empty!")
}
return split(templateAsString).map { createFragment(it) }.toList()
}
private fun split(templateAsString: String): List<String> {
val tokens = mutableListOf<String>()
var lastIndex = 0
var isVariable = false
var isPreceededByVariable = false
for ((i, c) in templateAsString.withIndex()) {
if (c == '{' && !isEscaped(templateAsString, i)) {
if (isVariable) {
throw IllegalFormatException("Illegal opening curly brace at position $i!\nOffending string was: $templateAsString")
}
if (isPreceededByVariable) {
throw IllegalFormatException("Consecutive variables at position $i! StepTemplate must contain an intervening text fragment to keep them apart.\nOffending string was: $templateAsString")
}
isVariable = true
if (lastIndex < i) {
tokens.add(templateAsString.substring(lastIndex, i))
}
lastIndex = i
} else if (c == '}' && !isEscaped(templateAsString, i)) {
if (!isVariable) {
throw IllegalFormatException("Illegal closing curly brace at position $i!\nOffending string was: $templateAsString")
}
isPreceededByVariable = true
isVariable = false
tokens.add(templateAsString.substring(lastIndex, i + 1))
lastIndex = i + 1
} else {
isPreceededByVariable = false
}
}
if (lastIndex < templateAsString.length) {
tokens.add(templateAsString.substring(lastIndex))
}
return tokens
}
private fun isEscaped(s: String, i: Int) = (i > 0 && s[i - 1] == '\\')
private fun createFragment(fragmentAsString: String): Fragment {
return if (fragmentAsString.startsWith('{') && fragmentAsString.endsWith('}'))
Variable(fragmentAsString.substring(1, fragmentAsString.length - 1))
else
Text(fragmentAsString)
}
}
}
internal class IllegalFormatException(msg: String) : IllegalArgumentException(msg)
internal sealed class Fragment
internal data class Text(val content: String) : Fragment()
internal data class Variable(val name: String) : Fragment()
| livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/matching/StepTemplate.kt | 1995098685 |
/*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@file:JvmName("MathHelper")
package com.mcmoonlake.api.util
/** Math Helper */
/**
* * Returns the value of the [num] parameter, clamped to be within the lower and upper limits given by the [min] and [max] parameters.
* * 返回 [num] 参数的值, 被钳位在由 [min] 和 [max] 参数给出的下限和上限内.
*/
fun clamp(num: Int, min: Int, max: Int): Int
= if(num < min) min else if(num > max) max else num
/**
* * Returns the value of the [num] parameter, clamped to be within the lower and upper limits given by the [min] and [max] parameters.
* * 返回 [num] 参数的值, 被钳位在由 [min] 和 [max] 参数给出的下限和上限内.
*/
fun clamp(num: Float, min: Float, max: Float): Float
= if(num < min) min else if(num > max) max else num
/**
* * Returns the value of the [num] parameter, clamped to be within the lower and upper limits given by the [min] and [max] parameters.
* * 返回 [num] 参数的值, 被钳位在由 [min] 和 [max] 参数给出的下限和上限内.
*/
fun clamp(num: Double, min: Double, max: Double): Double
= if(num < min) min else if(num > max) max else num
| API/src/main/kotlin/com/mcmoonlake/api/util/MathHelper.kt | 3053184163 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator
import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.indicatorengine.IndicatorEngine
import org.hisp.dhis.android.core.category.internal.CategoryOptionComboStoreImpl
import org.hisp.dhis.android.core.constant.internal.ConstantStore
import org.hisp.dhis.android.core.dataelement.internal.DataElementStore
import org.hisp.dhis.android.core.organisationunit.internal.OrganisationUnitGroupStore
import org.hisp.dhis.android.core.parser.internal.service.ExpressionService
import org.hisp.dhis.android.core.program.internal.ProgramStageStore
import org.hisp.dhis.android.core.program.internal.ProgramStore
import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLExecutor
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeStore
import org.hisp.dhis.android.core.utils.runner.D2JunitRunner
import org.junit.runner.RunWith
@RunWith(D2JunitRunner::class)
internal class IndicatorEvaluatorIntegrationShould : IndicatorEvaluatorIntegrationBaseShould() {
private val dataElementEvaluator = DataElementSQLEvaluator(databaseAdapter)
private val programIndicatorExecutor = ProgramIndicatorSQLExecutor(
ConstantStore.create(databaseAdapter),
DataElementStore.create(databaseAdapter),
TrackedEntityAttributeStore.create(databaseAdapter),
databaseAdapter
)
private val programIndicatorEvaluator = ProgramIndicatorSQLEvaluator(
programIndicatorExecutor
)
private val eventDataItemEvaluator = EventDataItemSQLEvaluator(databaseAdapter)
private val expressionService = ExpressionService(
DataElementStore.create(databaseAdapter),
CategoryOptionComboStoreImpl.create(databaseAdapter),
OrganisationUnitGroupStore.create(databaseAdapter),
ProgramStageStore.create(databaseAdapter)
)
private val indicatorEngine = IndicatorEngine(
indicatorTypeStore,
DataElementStore.create(databaseAdapter),
TrackedEntityAttributeStore.create(databaseAdapter),
CategoryOptionComboStoreImpl.create(databaseAdapter),
ProgramStore.create(databaseAdapter),
d2.programModule().programIndicators(),
dataElementEvaluator,
programIndicatorEvaluator,
eventDataItemEvaluator,
ConstantStore.create(databaseAdapter),
expressionService
)
override val indicatorEvaluator = IndicatorEvaluator(indicatorEngine)
}
| core/src/androidTest/java/org/hisp/dhis/android/core/analytics/aggregated/internal/evaluator/IndicatorEvaluatorIntegrationShould.kt | 780773616 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.arch.db.stores.internal
import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction
import org.hisp.dhis.android.core.common.State
internal interface DeletableStoreWithState<O> : StoreWithState<O> {
fun setSyncStateOrDelete(uid: String, state: State): HandleAction
fun setDeleted(uid: String): Int
fun selectSyncStateWhere(where: String): List<State>
}
| core/src/main/java/org/hisp/dhis/android/core/arch/db/stores/internal/DeletableStoreWithState.kt | 2148942175 |
import kotlin.test.assertEquals
private val availableCashUnits = listOf(500_00, 200_00, 100_00, 50_00, 20_00, 10_00, 5_00, 2_00, 1_00, 50, 20, 10, 5, 2, 1)
fun Int.cashUnits(): Map<Int, Int> =
LinkedHashMap<Int, Int>(availableCashUnits.size).also { result ->
var rest = this
for (cashUnit in availableCashUnits) {
val n = rest / cashUnit
result[cashUnit] = n
rest %= cashUnit
}
}
fun main(args: Array<String>) {
val expected = mapOf(
500_00 to 3,
200_00 to 2,
100_00 to 0,
50_00 to 1,
20_00 to 1,
10_00 to 0,
5_00 to 0,
2_00 to 1,
1_00 to 0,
50 to 1,
20 to 1,
10 to 0,
5 to 1,
2 to 1,
1 to 1
)
assertEquals(expected, 1972_78.cashUnits())
}
| problems/cash-units/cash-units.kt | 2890147153 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.tracker.importer.internal.interpreters
import org.hisp.dhis.android.R
import org.hisp.dhis.android.core.tracker.importer.internal.JobValidationError
internal class E1032Interpreter internal constructor(
private val interpreterHelper: InterpreterHelper,
override val regex: Regex
) : ErrorCodeInterpreter {
override val unformattedDescription = R.string.E1032
override fun companions(error: JobValidationError): List<String> {
return listOf(
interpreterHelper.programStageDisplayName(interpreterHelper.programStageUid(error.uid)),
error.uid
)
}
}
| core/src/main/java/org/hisp/dhis/android/core/tracker/importer/internal/interpreters/E1032Interpreter.kt | 1773376166 |
package cz.filipproch.reactor.ui.events
import cz.filipproch.reactor.base.view.UiEvent
import io.reactivex.Observable
/**
* @author Filip Prochazka (@filipproch)
*/
class ViewStartedEventKtTest : BaseEventFilterTest() {
override fun filterStream(stream: Observable<UiEvent>): Observable<out UiEvent> {
return stream.whenViewStarted()
}
override fun getValidEventInstance(): UiEvent {
return ViewStartedEvent
}
} | library/src/test/java/org/reactorx/view/events/ViewStartedEventKtTest.kt | 435534135 |
fun test1234() {
with(Main()) {
val c = 42
c.minus("3")
}
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/extensionOperators/minus/Explicit2.kt | 1829593667 |
// "Change return type of enclosing function 'foo' to 'Int'" "true"
fun foo(): String {
return <caret>1
} | plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/constantTypeMismatch.kt | 1699094516 |
package org.javacs.kt.codeaction.quickfix
import org.eclipse.lsp4j.*
import org.eclipse.lsp4j.jsonrpc.messages.Either
import org.javacs.kt.CompiledFile
import org.javacs.kt.index.SymbolIndex
import org.javacs.kt.position.offset
import org.javacs.kt.position.position
import org.javacs.kt.util.toPath
import org.javacs.kt.overridemembers.createFunctionStub
import org.javacs.kt.overridemembers.createVariableStub
import org.javacs.kt.overridemembers.getClassDescriptor
import org.javacs.kt.overridemembers.getDeclarationPadding
import org.javacs.kt.overridemembers.getNewMembersStartPosition
import org.javacs.kt.overridemembers.getSuperClassTypeProjections
import org.javacs.kt.overridemembers.hasNoBody
import org.javacs.kt.overridemembers.overridesDeclaration
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.isInterface
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.KtSuperTypeListEntry
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.isAbstract
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeProjection
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
class ImplementAbstractMembersQuickFix : QuickFix {
override fun compute(file: CompiledFile, index: SymbolIndex, range: Range, diagnostics: List<Diagnostic>): List<Either<Command, CodeAction>> {
val diagnostic = findDiagnosticMatch(diagnostics, range)
val startCursor = offset(file.content, range.start)
val endCursor = offset(file.content, range.end)
val kotlinDiagnostics = file.compile.diagnostics
// If the client side and the server side diagnostics contain a valid diagnostic for this range.
if (diagnostic != null && anyDiagnosticMatch(kotlinDiagnostics, startCursor, endCursor)) {
// Get the class with the missing members
val kotlinClass = file.parseAtPoint(startCursor)
if (kotlinClass is KtClass) {
// Get the functions that need to be implemented
val membersToImplement = getAbstractMembersStubs(file, kotlinClass)
val uri = file.parse.toPath().toUri().toString()
// Get the padding to be introduced before the member declarations
val padding = getDeclarationPadding(file, kotlinClass)
// Get the location where the new code will be placed
val newMembersStartPosition = getNewMembersStartPosition(file, kotlinClass)
val bodyAppendBeginning = listOf(TextEdit(Range(newMembersStartPosition, newMembersStartPosition), "{")).takeIf { kotlinClass.hasNoBody() } ?: emptyList()
val bodyAppendEnd = listOf(TextEdit(Range(newMembersStartPosition, newMembersStartPosition), System.lineSeparator() + "}")).takeIf { kotlinClass.hasNoBody() } ?: emptyList()
val textEdits = bodyAppendBeginning + membersToImplement.map {
// We leave two new lines before the member is inserted
val newText = System.lineSeparator() + System.lineSeparator() + padding + it
TextEdit(Range(newMembersStartPosition, newMembersStartPosition), newText)
} + bodyAppendEnd
val codeAction = CodeAction()
codeAction.edit = WorkspaceEdit(mapOf(uri to textEdits))
codeAction.kind = CodeActionKind.QuickFix
codeAction.title = "Implement abstract members"
codeAction.diagnostics = listOf(diagnostic)
return listOf(Either.forRight(codeAction))
}
}
return listOf()
}
}
fun findDiagnosticMatch(diagnostics: List<Diagnostic>, range: Range) =
diagnostics.find { diagnosticMatch(it, range, hashSetOf("ABSTRACT_MEMBER_NOT_IMPLEMENTED", "ABSTRACT_CLASS_MEMBER_NOT_IMPLEMENTED")) }
private fun anyDiagnosticMatch(diagnostics: Diagnostics, startCursor: Int, endCursor: Int) =
diagnostics.any { diagnosticMatch(it, startCursor, endCursor, hashSetOf("ABSTRACT_MEMBER_NOT_IMPLEMENTED", "ABSTRACT_CLASS_MEMBER_NOT_IMPLEMENTED")) }
private fun getAbstractMembersStubs(file: CompiledFile, kotlinClass: KtClass) =
// For each of the super types used by this class
kotlinClass.superTypeListEntries.mapNotNull {
// Find the definition of this super type
val referenceAtPoint = file.referenceExpressionAtPoint(it.startOffset)
val descriptor = referenceAtPoint?.second
val classDescriptor = getClassDescriptor(descriptor)
// If the super class is abstract or an interface
if (null != classDescriptor && (classDescriptor.kind.isInterface || classDescriptor.modality == Modality.ABSTRACT)) {
val superClassTypeArguments = getSuperClassTypeProjections(file, it)
classDescriptor.getMemberScope(superClassTypeArguments).getContributedDescriptors().filter { classMember ->
(classMember is FunctionDescriptor && classMember.modality == Modality.ABSTRACT && !overridesDeclaration(kotlinClass, classMember)) || (classMember is PropertyDescriptor && classMember.modality == Modality.ABSTRACT && !overridesDeclaration(kotlinClass, classMember))
}.mapNotNull { member ->
when (member) {
is FunctionDescriptor -> createFunctionStub(member)
is PropertyDescriptor -> createVariableStub(member)
else -> null
}
}
} else {
null
}
}.flatten()
| server/src/main/kotlin/org/javacs/kt/codeaction/quickfix/ImplementAbstractMembersQuickFix.kt | 591170441 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.platforms
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import java.io.File
@ApiStatus.Internal
enum class KotlinLibraryData(val libraryName: String, val kind: PersistentLibraryKind<*>?, val classesRoot: File, val sourcesRoot: File) {
KOTLIN_STDLIB(
libraryName = "kotlin-stdlib",
kind = null,
classesRoot = KotlinArtifacts.kotlinStdlib,
sourcesRoot = KotlinArtifacts.kotlinStdlibSources
),
KOTLIN_STDLIB_JDK7(
libraryName = "kotlin-stdlib-jdk7",
kind = null,
classesRoot = KotlinArtifacts.kotlinStdlibJdk7,
sourcesRoot = KotlinArtifacts.kotlinStdlibJdk7Sources
),
KOTLIN_STDLIB_JDK8(
libraryName = "kotlin-stdlib-jdk8",
kind = null,
classesRoot = KotlinArtifacts.kotlinStdlibJdk8,
sourcesRoot = KotlinArtifacts.kotlinStdlibJdk8Sources
),
KOTLIN_STDLIB_JS(
libraryName = "kotlin-stdlib-js",
kind = KotlinJavaScriptLibraryKind,
classesRoot = KotlinArtifacts.kotlinStdlibJs,
sourcesRoot = KotlinArtifacts.kotlinStdlibSources
)
} | plugins/kotlin/base/platforms/src/org/jetbrains/kotlin/idea/base/platforms/KotlinLibraryData.kt | 3653430802 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.index.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.project.Project
import com.intellij.util.containers.asJBIterable
import git4idea.conflicts.GitConflictsUtil.acceptConflictSide
import git4idea.conflicts.GitConflictsUtil.canShowMergeWindow
import git4idea.conflicts.GitConflictsUtil.getConflictOperationLock
import git4idea.conflicts.GitConflictsUtil.showMergeWindow
import git4idea.conflicts.GitMergeHandler
import git4idea.i18n.GitBundle
import git4idea.index.ui.*
import git4idea.repo.GitConflict
import org.jetbrains.annotations.Nls
import java.util.function.Supplier
class GitStageAcceptTheirsAction : GitStageAcceptConflictSideAction(GitBundle.messagePointer("conflicts.accept.theirs.action.text"), true)
class GitStageAcceptYoursAction : GitStageAcceptConflictSideAction(GitBundle.messagePointer("conflicts.accept.yours.action.text"), false)
abstract class GitStageConflictAction(text: Supplier<@Nls String>) :
GitFileStatusNodeAction(text, Presentation.NULL_STRING, null) {
override fun update(e: AnActionEvent) {
val project = e.project
val nodes = e.getData(GitStageDataKeys.GIT_FILE_STATUS_NODES).asJBIterable()
if (project == null || nodes.filter(this::matches).isEmpty) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isVisible = true
e.presentation.isEnabled = isEnabled(project, nodes.filterMap(GitFileStatusNode::createConflict).asSequence() as Sequence<GitConflict>)
}
override fun matches(statusNode: GitFileStatusNode): Boolean = statusNode.kind == NodeKind.CONFLICTED
override fun perform(project: Project, nodes: List<GitFileStatusNode>) {
perform(project, createMergeHandler(project), nodes.mapNotNull { it.createConflict() })
}
protected open fun isEnabled(project: Project, conflicts: Sequence<GitConflict>): Boolean {
return conflicts.any { conflict -> !getConflictOperationLock(project, conflict).isLocked }
}
protected abstract fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>)
}
abstract class GitStageAcceptConflictSideAction(text: Supplier<@Nls String>, private val takeTheirs: Boolean)
: GitStageConflictAction(text) {
override fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>) {
acceptConflictSide(project, handler, conflicts, takeTheirs)
}
}
class GitStageMergeConflictAction : GitStageConflictAction(GitBundle.messagePointer("action.Git.Merge.text")) {
override fun isEnabled(project: Project, conflicts: Sequence<GitConflict>): Boolean {
val handler = createMergeHandler(project)
return conflicts.any { conflict -> canShowMergeWindow(project, handler, conflict) }
}
override fun perform(project: Project, handler: GitMergeHandler, conflicts: List<GitConflict>) {
showMergeWindow(project, handler, conflicts)
}
}
| plugins/git4idea/src/git4idea/index/actions/GitStageConflictActions.kt | 1588753316 |
package com.jwu5.giphyapp.giphyfavorites
import android.content.res.Configuration
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jwu5.giphyapp.adapters.GiphyRecyclerViewAdapter
import com.jwu5.giphyapp.R
import com.jwu5.giphyapp.network.model.GiphyModel
import java.util.ArrayList
/**
* Created by Jiawei on 8/15/2017.
*/
class FavoritesFragment : Fragment(), FavoritesView {
private var mGiphyRecyclerView: RecyclerView? = null
private var mGiphyRecyclerViewAdapter: GiphyRecyclerViewAdapter? = null
private var mGridLayoutManager: GridLayoutManager? = null
private var mFavoritesPresenter: FavoritesPresenter? = null
private var mOrientation: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mFavoritesPresenter = FavoritesPresenter(this, activity)
mOrientation = activity.resources.configuration.orientation
}
override fun onConfigurationChanged(newConfig: Configuration?) {
mOrientation = newConfig!!.orientation
mFavoritesPresenter!!.updateUI(mGridLayoutManager!!.findFirstVisibleItemPosition())
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater!!.inflate(R.layout.fragment_giphy_view, container, false)
mGiphyRecyclerView = v.findViewById(R.id.fragment_giphy_view_recycler_view) as RecyclerView
mGridLayoutManager = GridLayoutManager(activity, 2)
mGiphyRecyclerView!!.layoutManager = mGridLayoutManager
mFavoritesPresenter!!.updateUI(mGridLayoutManager!!.findFirstVisibleItemPosition())
return v
}
override fun onResume() {
super.onResume()
mFavoritesPresenter!!.updateUI(mGridLayoutManager!!.findFirstVisibleItemPosition())
}
override fun updateAdapter(items: ArrayList<GiphyModel>?, position: Int) {
mGiphyRecyclerViewAdapter = GiphyRecyclerViewAdapter(activity, TAB_NAME, mOrientation)
mGiphyRecyclerViewAdapter!!.setItemList(items)
mGiphyRecyclerView!!.adapter = mGiphyRecyclerViewAdapter
mGiphyRecyclerView!!.scrollToPosition(position)
}
companion object {
val TAB_NAME = "Favorites"
fun newInstance(): FavoritesFragment {
return FavoritesFragment()
}
}
}
| app/src/main/java/com/jwu5/giphyapp/giphyfavorites/FavoritesFragment.kt | 1266992267 |
// 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.openapi.wm.impl.headertoolbar
import org.jetbrains.annotations.ApiStatus
/**
* Factory for widgets placed in main toolbar.
* This is root interface which is not supposed to be implemented. Please implement [MainToolbarProjectWidgetFactory] for
* Application level widgets or [MainToolbarProjectWidgetFactory] for Project level widgets
*/
@ApiStatus.Experimental
@ApiStatus.Internal
interface MainToolbarWidgetFactory {
/**
* Defines part of toolbar (described in [Position]) when widget should be shown.
*/
fun getPosition(): Position
/**
* List of allowed positions for toolbar widgets
*/
enum class Position {
Left, Right, Center
}
} | platform/platform-impl/src/com/intellij/openapi/wm/impl/headertoolbar/MainToolbarWidgetFactory.kt | 1098738870 |
package eu.kanade.tachiyomi.data.source.online
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.network.GET
import eu.kanade.tachiyomi.data.network.POST
import eu.kanade.tachiyomi.data.source.getLanguages
import eu.kanade.tachiyomi.data.source.model.MangasPage
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.util.asJsoup
import eu.kanade.tachiyomi.util.attrOrText
import okhttp3.Request
import okhttp3.Response
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.*
class YamlOnlineSource(mappings: Map<*, *>) : OnlineSource() {
val map = YamlSourceNode(mappings)
override val name: String
get() = map.name
override val baseUrl = map.host.let {
if (it.endsWith("/")) it.dropLast(1) else it
}
override val lang = map.lang.toUpperCase().let { code ->
getLanguages().find { code == it.code }!!
}
override val supportsLatest = map.latestupdates != null
override val client = when(map.client) {
"cloudflare" -> network.cloudflareClient
else -> network.client
}
override val id = map.id.let {
if (it is Int) it else (lang.code.hashCode() + 31 * it.hashCode()) and 0x7fffffff
}
override fun popularMangaRequest(page: MangasPage): Request {
if (page.page == 1) {
page.url = popularMangaInitialUrl()
}
return when (map.popular.method?.toLowerCase()) {
"post" -> POST(page.url, headers, map.popular.createForm())
else -> GET(page.url, headers)
}
}
override fun popularMangaInitialUrl() = map.popular.url
override fun popularMangaParse(response: Response, page: MangasPage) {
val document = response.asJsoup()
for (element in document.select(map.popular.manga_css)) {
Manga.create(id).apply {
title = element.text()
setUrlWithoutDomain(element.attr("href"))
page.mangas.add(this)
}
}
map.popular.next_url_css?.let { selector ->
page.nextPageUrl = document.select(selector).first()?.absUrl("href")
}
}
override fun searchMangaRequest(page: MangasPage, query: String, filters: List<Filter>): Request {
if (page.page == 1) {
page.url = searchMangaInitialUrl(query, filters)
}
return when (map.search.method?.toLowerCase()) {
"post" -> POST(page.url, headers, map.search.createForm())
else -> GET(page.url, headers)
}
}
override fun searchMangaInitialUrl(query: String, filters: List<Filter>) = map.search.url.replace("\$query", query)
override fun searchMangaParse(response: Response, page: MangasPage, query: String, filters: List<Filter>) {
val document = response.asJsoup()
for (element in document.select(map.search.manga_css)) {
Manga.create(id).apply {
title = element.text()
setUrlWithoutDomain(element.attr("href"))
page.mangas.add(this)
}
}
map.search.next_url_css?.let { selector ->
page.nextPageUrl = document.select(selector).first()?.absUrl("href")
}
}
override fun latestUpdatesRequest(page: MangasPage): Request {
if (page.page == 1) {
page.url = latestUpdatesInitialUrl()
}
return when (map.latestupdates!!.method?.toLowerCase()) {
"post" -> POST(page.url, headers, map.latestupdates.createForm())
else -> GET(page.url, headers)
}
}
override fun latestUpdatesInitialUrl() = map.latestupdates!!.url
override fun latestUpdatesParse(response: Response, page: MangasPage) {
val document = response.asJsoup()
for (element in document.select(map.latestupdates!!.manga_css)) {
Manga.create(id).apply {
title = element.text()
setUrlWithoutDomain(element.attr("href"))
page.mangas.add(this)
}
}
map.latestupdates.next_url_css?.let { selector ->
page.nextPageUrl = document.select(selector).first()?.absUrl("href")
}
}
override fun mangaDetailsParse(response: Response, manga: Manga) {
val document = response.asJsoup()
with(map.manga) {
val pool = parts.get(document)
manga.author = author?.process(document, pool)
manga.artist = artist?.process(document, pool)
manga.description = summary?.process(document, pool)
manga.thumbnail_url = cover?.process(document, pool)
manga.genre = genres?.process(document, pool)
manga.status = status?.getStatus(document, pool) ?: Manga.UNKNOWN
}
}
override fun chapterListParse(response: Response, chapters: MutableList<Chapter>) {
val document = response.asJsoup()
with(map.chapters) {
val pool = emptyMap<String, Element>()
val dateFormat = SimpleDateFormat(date?.format, Locale.ENGLISH)
for (element in document.select(chapter_css)) {
val chapter = Chapter.create()
element.select(title).first().let {
chapter.name = it.text()
chapter.setUrlWithoutDomain(it.attr("href"))
}
val dateElement = element.select(date?.select).first()
chapter.date_upload = date?.getDate(dateElement, pool, dateFormat)?.time ?: 0
chapters.add(chapter)
}
}
}
override fun pageListParse(response: Response, pages: MutableList<Page>) {
val body = response.body().string()
val url = response.request().url().toString()
// TODO lazy initialization in Kotlin 1.1
val document = Jsoup.parse(body, url)
with(map.pages) {
// Capture a list of values where page urls will be resolved.
val capturedPages = if (pages_regex != null)
pages_regex!!.toRegex().findAll(body).map { it.value }.toList()
else if (pages_css != null)
document.select(pages_css).map { it.attrOrText(pages_attr!!) }
else
null
// For each captured value, obtain the url and create a new page.
capturedPages?.forEach { value ->
// If the captured value isn't an url, we have to use replaces with the chapter url.
val pageUrl = if (replace != null && replacement != null)
url.replace(replace!!.toRegex(), replacement!!.replace("\$value", value))
else
value
pages.add(Page(pages.size, pageUrl))
}
// Capture a list of images.
val capturedImages = if (image_regex != null)
image_regex!!.toRegex().findAll(body).map { it.groups[1]?.value }.toList()
else if (image_css != null)
document.select(image_css).map { it.absUrl(image_attr) }
else
null
// Assign the image url to each page
capturedImages?.forEachIndexed { i, url ->
val page = pages.getOrElse(i) { Page(i, "").apply { pages.add(this) } }
page.imageUrl = url
}
}
}
override fun imageUrlParse(response: Response): String {
val body = response.body().string()
val url = response.request().url().toString()
with(map.pages) {
return if (image_regex != null)
image_regex!!.toRegex().find(body)!!.groups[1]!!.value
else if (image_css != null)
Jsoup.parse(body, url).select(image_css).first().absUrl(image_attr)
else
throw Exception("image_regex and image_css are null")
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/source/online/YamlOnlineSource.kt | 283831965 |
package org.secfirst.umbrella.feature.main
import android.app.SearchManager
import android.content.Context
import android.content.Intent.ACTION_VIEW
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.attachRouter
import com.github.tbouron.shakedetector.library.ShakeDetector
import com.google.android.material.bottomnavigation.BottomNavigationView
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.main_view.*
import org.secfirst.advancedsearch.interfaces.AdvancedSearchPresenter
import org.secfirst.advancedsearch.interfaces.DataProvider
import org.secfirst.advancedsearch.models.SearchCriteria
import org.secfirst.advancedsearch.util.mvp.ThreadSpec
import org.secfirst.umbrella.R
import org.secfirst.umbrella.UmbrellaApplication
import org.secfirst.umbrella.data.disk.isRepository
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper.Companion.EXTRA_LOGGED_IN
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper.Companion.EXTRA_MASK_APP
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper.Companion.EXTRA_SHOW_MOCK_VIEW
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper.Companion.PREF_NAME
import org.secfirst.umbrella.feature.account.view.AccountController
import org.secfirst.umbrella.feature.checklist.view.controller.HostChecklistController
import org.secfirst.umbrella.feature.form.view.controller.HostFormController
import org.secfirst.umbrella.feature.lesson.view.LessonController
import org.secfirst.umbrella.feature.login.view.LoginController
import org.secfirst.umbrella.feature.maskapp.view.CalculatorController
import org.secfirst.umbrella.feature.reader.view.HostReaderController
import org.secfirst.umbrella.feature.search.view.SearchController
import org.secfirst.umbrella.feature.tour.view.TourController
import org.secfirst.umbrella.misc.*
import org.secfirst.umbrella.misc.AppExecutors.Companion.uiContext
import java.util.*
class MainActivity : AppCompatActivity(), AdvancedSearchPresenter {
lateinit var router: Router
private fun performDI() = AndroidInjection.inject(this)
private lateinit var menuItem: Menu
private var disableSearch = false
private var deepLink = false
private var searchProvider: AdvancedSearchPresenter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setLanguage()
setContentView(R.layout.main_view)
router = attachRouter(baseContainer, savedInstanceState)
performDI()
isDeepLink()
initNavigation()
showNavigation()
}
override fun getCriteria(): List<SearchCriteria> {
return searchProvider?.getCriteria()
?: throw UnsupportedOperationException("The SearchProvider should be registered in the MainActivity")
}
override fun getDataProvider(): DataProvider {
return searchProvider?.getDataProvider()
?: throw UnsupportedOperationException("The SearchProvider should be registered in the MainActivity")
}
override fun getThreadSpec(): ThreadSpec {
return searchProvider?.getThreadSpec()
?: throw UnsupportedOperationException("The SearchProvider should be registered in the MainActivity")
}
override fun onResume() {
super.onResume()
ShakeDetector.start()
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
return true
}
fun registerSearchProvider(provider: AdvancedSearchPresenter) {
this.searchProvider = provider
}
fun releaseSearchProvider() {
this.searchProvider = null
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the options menu from XML
val inflater = menuInflater
menuItem = menu
inflater.inflate(R.menu.option_menu, menu)
val menuItem = menu.findItem(R.id.menu_search)
// Get the SearchView and set the searchable configuration
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
(menuItem.actionView as SearchView).apply {
menuItem.isVisible = !disableSearch
val searchEditText = this.findViewById<View>(androidx.appcompat.R.id.search_src_text) as EditText
searchEditText.setTextColor(resources.getColor(R.color.white))
searchEditText.setHintTextColor(resources.getColor(R.color.white))
// Assumes current activity is the searchable activity
if (componentName!=null && searchManager.getSearchableInfo(componentName) != null)
setSearchableInfo(searchManager.getSearchableInfo(componentName))
setIconifiedByDefault(false) // Do not iconify the widget; expand it by default
isSubmitButtonEnabled = true
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
query?.let {
router.pushController(RouterTransaction.with(SearchController(it)))
return true
}
return false
}
override fun onQueryTextChange(p0: String?): Boolean {
return false
}
})
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
hideKeyboard()
return true
}
return super.onOptionsItemSelected(item)
}
private fun setLanguage() {
val preference = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
val pref = preference.getString(AppPreferenceHelper.EXTRA_LANGUAGE, "")
val isoCountry: String
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (pref!!.isNotBlank())
this.setLocale(pref)
} else {
isoCountry = if (pref!!.isNotBlank()) pref
else Locale.getDefault().language
this.setLocale(isoCountry)
}
}
private fun initNavigation() {
navigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener)
if (isMaskMode() && isShowMockView()) {
router.setRoot(RouterTransaction.with(CalculatorController()))
} else {
when(UmbrellaApplication.instance.checkPassword()) {
false -> {
router.pushController(RouterTransaction.with(LoginController()))
}
true -> {
setShowMockView()
when {
isLoggedUser() -> {
if (!deepLink) {
router.setRoot(RouterTransaction.with(LoginController()))
navigation.menu.getItem(2).isChecked = true
disableSearch = true
}
}
isRepository() -> {
if (!deepLink) {
router.setRoot(RouterTransaction.with(HostChecklistController()))
navigation.menu.getItem(2).isChecked = true
disableSearch = false
}
}
else -> router.setRoot(RouterTransaction.with(TourController()))
}
}
}
}
}
fun resetAppbar() {
disableSearch = false
menuItem.clear()
}
private val navigationItemSelectedListener =
BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_feeds -> {
router.pushController(RouterTransaction.with(HostReaderController()))
return@OnNavigationItemSelectedListener true
}
R.id.navigation_forms -> {
router.pushController(RouterTransaction.with(HostFormController()))
return@OnNavigationItemSelectedListener true
}
R.id.navigation_checklists -> {
router.pushController(RouterTransaction.with(HostChecklistController()))
return@OnNavigationItemSelectedListener true
}
R.id.navigation_lessons -> {
router.pushController(RouterTransaction.with(LessonController()))
return@OnNavigationItemSelectedListener true
}
R.id.navigation_account -> {
router.pushController(RouterTransaction.with(AccountController()))
return@OnNavigationItemSelectedListener true
}
}
false
}
override fun onStop() {
super.onStop()
ShakeDetector.stop()
}
override fun onDestroy() {
super.onDestroy()
ShakeDetector.destroy()
}
override fun onBackPressed() {
if (!router.handleBack())
super.onBackPressed()
}
fun hideNavigation() = navigation?.let { it.visibility = INVISIBLE }
fun showNavigation() = navigation?.let { it.visibility = VISIBLE }
fun navigationPositionToCenter() {
navigation.menu.getItem(2).isChecked = true
}
private fun isLoggedUser(): Boolean {
val shared = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
return shared.getBoolean(EXTRA_LOGGED_IN, false)
}
private fun setShowMockView() {
if (isMaskMode()) {
val shared = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
shared.edit().putBoolean(EXTRA_SHOW_MOCK_VIEW, true).apply()
}
}
private fun isMaskMode(): Boolean {
val shared = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
val isMask = shared.getBoolean(EXTRA_MASK_APP, false)
if (!isMask)
setMaskMode(this, false)
return isMask
}
private fun isShowMockView(): Boolean {
val shared = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
return shared.getBoolean(EXTRA_SHOW_MOCK_VIEW, false)
}
private fun isDeepLink() {
if (ACTION_VIEW == intent.action) {
deepLink = true
val uri = intent.data
val uriString = uri?.toString() ?: ""
val path = uriString.substringAfterLast(SCHEMA)
val uriSplitted = path.split("/")
when (uri?.host) {
FEED_HOST -> openFeedByUrl(router, navigation)
FORM_HOST -> openFormByUrl(router, navigation, uriString)
// CHECKLIST_HOST -> openChecklistByUrl(router, navigation, uriString)
SEARCH_HOST -> {
intent?.data?.lastPathSegment?.let {
router.pushController(RouterTransaction.with(SearchController(it)))
}
}
else -> {
launchSilent(uiContext) {
if (isLessonDeepLink(uriSplitted))
openSpecificLessonByUrl(router, navigation, uriString)
else
openDifficultyByUrl(router, navigation, path)
}
}
}
}
}
}
| app/src/main/java/org/secfirst/umbrella/feature/main/MainActivity.kt | 2937603313 |
package fr.openium.auvergnewebcams.utils
import fr.openium.auvergnewebcams.CustomApplication
import timber.log.Timber
object LogUtils {
/**
* Method that show a generic log when error is unknown
*/
fun showSingleErrorLog(functionName: String, error: Throwable?) {
Timber.e(error, "${CustomApplication.TAG} -> $functionName")
}
} | app/src/main/java/fr/openium/auvergnewebcams/utils/LogUtils.kt | 2587826963 |
// snippet-sourcedescription:[CelebrityInfo.kt demonstrates how to get information about a detected celebrity.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Rekognition]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.rekognition
// snippet-start:[rekognition.kotlin.celebrityInfo.import]
import aws.sdk.kotlin.services.rekognition.RekognitionClient
import aws.sdk.kotlin.services.rekognition.model.GetCelebrityInfoRequest
import kotlin.system.exitProcess
// snippet-end:[rekognition.kotlin.celebrityInfo.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:
<id>
Where:
id - The id value of the celebrity. You can use the RecognizeCelebrities example to get the ID value.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val id = args[0]
getCelebrityInfo(id)
}
// snippet-start:[rekognition.kotlin.celebrityInfo.main]
suspend fun getCelebrityInfo(idVal: String?) {
val request = GetCelebrityInfoRequest {
id = idVal
}
RekognitionClient { region = "us-east-1" }.use { rekClient ->
val response = rekClient.getCelebrityInfo(request)
// Display celebrity information.
println("The celebrity name is ${response.name}")
println("Further information (if available):")
response.urls?.forEach { url ->
println(url)
}
}
}
// snippet-end:[rekognition.kotlin.celebrityInfo.main]
| kotlin/services/rekognition/src/main/kotlin/com/kotlin/rekognition/CelebrityInfo.kt | 2390251556 |
package com.selfviewdemo
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
class KtMainActivity : AppCompatActivity(),View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
init()
}
private fun init() {
java_watchview.setOnClickListener(this)
kotlin_watchview.setOnClickListener(this)
}
override fun onClick(v: View) {
when(v.id) {
R.id.java_watchview -> {
startActivity(Intent(KtMainActivity@this,WatchActivity::class.java))
// startActivity(Intent(KtMainActivity@this,WatchActivity().javaClass))
}
R.id.kotlin_watchview -> {
startActivity(Intent(KtMainActivity@this,KtWatchActivity().javaClass))
}
else -> {
//default
}
}
}
}
| app/src/main/kotlin/com.selfviewdemo/KtMainActivity.kt | 576297373 |
package net.pot8os.kotlintestsample
import androidx.test.ext.junit.runners.AndroidJUnit4
import net.pot8s.kotlintestsample.CalculatorSpec
import org.junit.runner.RunWith
/**
* @author So Nakamura, 2020-Feb-15
*/
@RunWith(AndroidJUnit4::class)
class InstrumentedCalculatorTest : CalculatorSpec()
| app/src/androidTest/kotlin/net/pot8os/kotlintestsample/InstrumentedCalculatorTest.kt | 2445609237 |
package com.example.eventbuskotlin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import org.greenrobot.eventbus.Subscribe
class BlankFragment : BlankBaseFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_blank, container, false)
}
@Subscribe // subscribe annotation in base class would not be picked up by index
override fun handleEvent(event: BlankBaseFragment.SampleEvent) {
super.handleEvent(event)
}
class SampleEvent
}
| eventbus-kotlin/app/src/main/java/com/example/eventbuskotlin/BlankFragment.kt | 3144730945 |
// 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.
@file:Suppress("PropertyName")
package com.intellij.configurationStore.xml
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.xmlb.annotations.Property
import com.intellij.util.xmlb.annotations.Tag
import com.intellij.util.xmlb.annotations.XMap
import org.junit.Test
import java.util.*
internal class XmlSerializerMapTest {
@Test
fun `empty map`() {
@Tag("bean")
class Bean {
@JvmField
var values = emptyMap<String, String>()
}
val data = Bean()
data.values = mapOf("foo" to "boo")
testSerializer("""
<bean>
<option name="values">
<map>
<entry key="foo" value="boo" />
</map>
</option>
</bean>""", data)
}
@Test fun mapAtTopLevel() {
@Tag("bean")
class BeanWithMapAtTopLevel {
@Property(surroundWithTag = false)
@XMap
var map = LinkedHashMap<String, String>()
var option: String? = null
}
val bean = BeanWithMapAtTopLevel()
bean.map.put("a", "b")
bean.option = "xxx"
testSerializer("""
<bean>
<option name="option" value="xxx" />
<entry key="a" value="b" />
</bean>""", bean)
}
@Test fun propertyElementName() {
@Tag("bean")
class Bean {
@XMap
var map = LinkedHashMap<String, String>()
}
val bean = Bean()
bean.map.put("a", "b")
testSerializer("""
<bean>
<map>
<entry key="a" value="b" />
</map>
</bean>""", bean)
}
@Test fun notSurroundingKeyAndValue() {
@Tag("bean")
class Bean {
@XMap(propertyElementName = "map")
var MAP = LinkedHashMap<BeanWithPublicFields, BeanWithTextAnnotation>()
}
val bean = Bean()
bean.MAP.put(BeanWithPublicFields(1, "a"), BeanWithTextAnnotation(2, "b"))
bean.MAP.put(BeanWithPublicFields(3, "c"), BeanWithTextAnnotation(4, "d"))
bean.MAP.put(BeanWithPublicFields(5, "e"), BeanWithTextAnnotation(6, "f"))
testSerializer("""
<bean>
<map>
<entry>
<BeanWithPublicFields>
<option name="INT_V" value="1" />
<option name="STRING_V" value="a" />
</BeanWithPublicFields>
<BeanWithTextAnnotation>
<option name="INT_V" value="2" />
b
</BeanWithTextAnnotation>
</entry>
<entry>
<BeanWithPublicFields>
<option name="INT_V" value="3" />
<option name="STRING_V" value="c" />
</BeanWithPublicFields>
<BeanWithTextAnnotation>
<option name="INT_V" value="4" />
d
</BeanWithTextAnnotation>
</entry>
<entry>
<BeanWithPublicFields>
<option name="INT_V" value="5" />
<option name="STRING_V" value="e" />
</BeanWithPublicFields>
<BeanWithTextAnnotation>
<option name="INT_V" value="6" />
f
</BeanWithTextAnnotation>
</entry>
</map>
</bean>""", bean)
}
@Test fun serialization() {
@Tag("bean")
class BeanWithMap {
var VALUES: MutableMap<String, String> = LinkedHashMap()
init {
VALUES.put("a", "1")
VALUES.put("b", "2")
VALUES.put("c", "3")
}
}
val bean = BeanWithMap()
testSerializer("""
<bean>
<option name="VALUES">
<map>
<entry key="a" value="1" />
<entry key="b" value="2" />
<entry key="c" value="3" />
</map>
</option>
</bean>""", bean)
bean.VALUES.clear()
bean.VALUES.put("1", "a")
bean.VALUES.put("2", "b")
bean.VALUES.put("3", "c")
testSerializer("""
<bean>
<option name="VALUES">
<map>
<entry key="1" value="a" />
<entry key="2" value="b" />
<entry key="3" value="c" />
</map>
</option>
</bean>""", bean)
}
@Test fun withBeanValue() {
class BeanWithMapWithBeanValue {
var VALUES: MutableMap<String, BeanWithProperty> = LinkedHashMap()
}
val bean = BeanWithMapWithBeanValue()
bean.VALUES.put("a", BeanWithProperty("James"))
bean.VALUES.put("b", BeanWithProperty("Bond"))
bean.VALUES.put("c", BeanWithProperty("Bill"))
testSerializer("""
<BeanWithMapWithBeanValue>
<option name="VALUES">
<map>
<entry key="a">
<value>
<BeanWithProperty>
<option name="name" value="James" />
</BeanWithProperty>
</value>
</entry>
<entry key="b">
<value>
<BeanWithProperty>
<option name="name" value="Bond" />
</BeanWithProperty>
</value>
</entry>
<entry key="c">
<value>
<BeanWithProperty>
<option name="name" value="Bill" />
</BeanWithProperty>
</value>
</entry>
</map>
</option>
</BeanWithMapWithBeanValue>""", bean)
}
@Test fun setKeysInMap() {
@Tag("bean")
class BeanWithSetKeysInMap {
var myMap = LinkedHashMap<Collection<String>, String>()
}
val bean = BeanWithSetKeysInMap()
bean.myMap.put(LinkedHashSet(Arrays.asList("a", "b", "c")), "letters")
bean.myMap.put(LinkedHashSet(Arrays.asList("1", "2", "3")), "numbers")
val bb = testSerializer("""
<bean>
<option name="myMap">
<map>
<entry value="letters">
<key>
<set>
<option value="a" />
<option value="b" />
<option value="c" />
</set>
</key>
</entry>
<entry value="numbers">
<key>
<set>
<option value="1" />
<option value="2" />
<option value="3" />
</set>
</key>
</entry>
</map>
</option>
</bean>""", bean)
for (collection in bb.myMap.keys) {
assertThat(collection).isInstanceOf(Set::class.java)
}
}
@Test
fun nestedMapAndFinalFieldWithoutAnnotation() {
@Tag("bean")
class MapMap {
// do not add store annotations - this test also checks that map field without annotation is supported
@JvmField
val foo: MutableMap<String, TreeMap<Long, String>> = TreeMap()
}
val bean = MapMap()
bean.foo.put("bar", TreeMap(mapOf(12L to "22")))
testSerializer("""
<bean>
<option name="foo">
<map>
<entry key="bar">
<value>
<map>
<entry key="12" value="22" />
</map>
</value>
</entry>
</map>
</option>
</bean>
""", bean)
}
} | platform/configuration-store-impl/testSrc/xml/XmlSerializerMapTest.kt | 2513532688 |
package com.alexstyl.specialdates.events.namedays.calendar.resource
import com.alexstyl.specialdates.date.Date
import com.alexstyl.specialdates.events.namedays.calendar.OrthodoxEasterCalculator
import org.fest.assertions.api.Assertions.assertThat
import org.junit.Test
class RomanianEasterSpecialCalculatorTest {
private var orthodoxEasterCalculator = OrthodoxEasterCalculator()
@Test
fun calculatesSundayBeforeEasterCorrectly() {
val calculator = RomanianEasterSpecialCalculator(orthodoxEasterCalculator)
val expectedDates = buildExpectedDates()
for (expectedDate in expectedDates) {
val actualDate = calculator.calculateSpecialRomanianDayForYear(expectedDate.year)
assertThat(expectedDate).isEqualTo(actualDate)
}
}
private fun buildExpectedDates(): List<Date> =
listOf(Date.on(9, 4, 2017),
Date.on(1, 4, 2018),
Date.on(21, 4, 2019),
Date.on(12, 4, 2020),
Date.on(25, 4, 2021),
Date.on(17, 4, 2022))
}
| memento/src/test/java/com/alexstyl/specialdates/events/namedays/calendar/resource/RomanianEasterSpecialCalculatorTest.kt | 1809067202 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.inspection
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.util.findContainingMethod
import com.intellij.codeInspection.InspectionSuppressor
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.PsiElement
class StaticListenerInspectionSuppressor : InspectionSuppressor {
override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean {
if (toolId != "MethodMayBeStatic") {
return false
}
val method = element.findContainingMethod() ?: return false
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return false
val facet = MinecraftFacet.getInstance(module) ?: return false
return facet.suppressStaticListener(method)
}
override fun getSuppressActions(element: PsiElement?, toolId: String): Array<SuppressQuickFix> =
SuppressQuickFix.EMPTY_ARRAY
}
| src/main/kotlin/com/demonwav/mcdev/inspection/StaticListenerInspectionSuppressor.kt | 3594329542 |
package backend.model.sponsoring
import backend.Integration.IntegrationTest
import backend.model.misc.Coord
import backend.model.sponsoring.SponsoringStatus.*
import backend.model.user.Address
import backend.model.user.Participant
import backend.model.user.Sponsor
import backend.util.euroOf
import org.junit.Before
import org.junit.Test
import java.time.LocalDateTime
import kotlin.test.assertEquals
import kotlin.test.assertFails
class SponsoringServiceImplTest : IntegrationTest() {
@Before
override fun setUp() {
super.setUp()
}
@Test
fun emailEventEnded() {
sponsoringService.sendEmailsToSponsorsWhenEventHasEnded()
}
@Test
fun testCreateSponsoring() {
val sponsor = userService.create("[email protected]", "password", { addRole(Sponsor::class) }).getRole(Sponsor::class)!!
val creator = userService.create("[email protected]", "password", { addRole(Participant::class) }).getRole(Participant::class)!!
val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36)
val team = teamService.create(creator, "name", "description", event, null)
val sponsoring = sponsoringService.createSponsoring(sponsor, team, euroOf(10), euroOf(20))
val found = sponsoringRepository.findOne(sponsoring.id)
assertEquals(sponsoring.id, found.id)
}
@Test
fun testAcceptSponsoring() {
val sponsor = userService.create("[email protected]", "password", { addRole(Sponsor::class) }).getRole(Sponsor::class)!!
val creator = userService.create("[email protected]", "password", { addRole(Participant::class) }).getRole(Participant::class)!!
val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36)
val team = teamService.create(creator, "name", "description", event, null)
val sponsoring = sponsoringService.createSponsoring(sponsor, team, euroOf(10), euroOf(20))
setAuthenticatedUser(creator.email)
sponsoringService.acceptSponsoring(sponsoring)
val found = sponsoringRepository.findOne(sponsoring.id)
assertEquals(ACCEPTED, found.status)
}
@Test
fun testAcceptSponsoringFailsIfNotPartOfTeam() {
val sponsor = userService.create("[email protected]", "password", { addRole(Sponsor::class) }).getRole(Sponsor::class)!!
val creator = userService.create("[email protected]", "password", { addRole(Participant::class) }).getRole(Participant::class)!!
val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36)
val team = teamService.create(creator, "name", "description", event, null)
val sponsoring = sponsoringService.createSponsoring(sponsor, team, euroOf(10), euroOf(20))
setAuthenticatedUser(sponsor.email)
assertFails { sponsoringService.acceptSponsoring(sponsoring) }
val found = sponsoringRepository.findOne(sponsoring.id)
assertEquals(ACCEPTED, found.status)
}
@Test
fun testRejectSponsoring() {
val sponsor = userService.create("[email protected]", "password", { addRole(Sponsor::class) }).getRole(Sponsor::class)!!
val creator = userService.create("[email protected]", "password", { addRole(Participant::class) }).getRole(Participant::class)!!
val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36)
val team = teamService.create(creator, "name", "description", event, null)
val sponsoring = sponsoringService.createSponsoring(sponsor, team, euroOf(10), euroOf(20))
setAuthenticatedUser(creator.email)
sponsoringService.rejectSponsoring(sponsoring)
val found = sponsoringRepository.findOne(sponsoring.id)
assertEquals(REJECTED, found.status)
}
@Test
fun testRejectSponsoringFailsIfNotPartOfTeam() {
val sponsor = userService.create("[email protected]", "password", { addRole(Sponsor::class) }).getRole(Sponsor::class)!!
val creator = userService.create("[email protected]", "password", { addRole(Participant::class) }).getRole(Participant::class)!!
val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36)
val team = teamService.create(creator, "name", "description", event, null)
val sponsoring = sponsoringService.createSponsoring(sponsor, team, euroOf(10), euroOf(20))
setAuthenticatedUser(sponsor.email)
assertFails { sponsoringService.rejectSponsoring(sponsoring) }
val found = sponsoringRepository.findOne(sponsoring.id)
assertEquals(ACCEPTED, found.status)
}
@Test
fun testWithdrawSponsoringWithUnregisteredSponsorAsTeamMember() {
val creator = userService.create("[email protected]", "password", { addRole(Participant::class) }).getRole(Participant::class)!!
val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36)
val team = teamService.create(creator, "name", "description", event, null)
val unregisteredSponsor = UnregisteredSponsor(
firstname = "Firstname",
lastname = "Lastname",
url = "www.url.de",
company = "company",
gender = "gender",
address = Address(street = "street", housenumber = "5", zipcode = "10", city = "city", country = "country")
)
setAuthenticatedUser(creator.email)
val sponsoring = sponsoringService.createSponsoringWithOfflineSponsor(team, euroOf(10), euroOf(100), unregisteredSponsor)
sponsoringService.withdrawSponsoring(sponsoring)
}
@Test
fun testWithdrawSponsoringWithUnregisteredSponsorAsSponsorFails() {
val sponsor = userService.create("[email protected]", "password", { addRole(Sponsor::class) }).getRole(Sponsor::class)!!
val creator = userService.create("[email protected]", "password", { addRole(Participant::class) }).getRole(Participant::class)!!
val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36)
val team = teamService.create(creator, "name", "description", event, null)
val unregisteredSponsor = UnregisteredSponsor(
firstname = "Firstname",
lastname = "Lastname",
url = "www.url.de",
company = "company",
gender = "gender",
address = Address(street = "street", housenumber = "5", zipcode = "10", city = "city", country = "country")
)
setAuthenticatedUser(creator.email)
val sponsoring = sponsoringService.createSponsoringWithOfflineSponsor(team, euroOf(10), euroOf(100), unregisteredSponsor)
setAuthenticatedUser(sponsor.email)
assertFails { sponsoringService.withdrawSponsoring(sponsoring) }
}
@Test
fun testWithdrawSponsoringWithRegisteredSponsorAsSponsor() {
val sponsor = userService.create("[email protected]", "password", { addRole(Sponsor::class) }).getRole(Sponsor::class)!!
val creator = userService.create("[email protected]", "password", { addRole(Participant::class) }).getRole(Participant::class)!!
val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36)
val team = teamService.create(creator, "name", "description", event, null)
val sponsoring = sponsoringService.createSponsoring(sponsor, team, euroOf(10), euroOf(20))
setAuthenticatedUser(sponsor.email)
sponsoringService.withdrawSponsoring(sponsoring)
val found = sponsoringRepository.findOne(sponsoring.id)
assertEquals(WITHDRAWN, found.status)
}
@Test
fun testWithdrawSponsoringWithRegisteredSponsorAsTeamMemberFails() {
val sponsor = userService.create("[email protected]", "password", { addRole(Sponsor::class) }).getRole(Sponsor::class)!!
val creator = userService.create("[email protected]", "password", { addRole(Participant::class) }).getRole(Participant::class)!!
val event = eventService.createEvent("title", LocalDateTime.now(), "city", Coord(0.0, 1.1), 36)
val team = teamService.create(creator, "name", "description", event, null)
val sponsoring = sponsoringService.createSponsoring(sponsor, team, euroOf(10), euroOf(20))
setAuthenticatedUser(creator.email)
assertFails { sponsoringService.withdrawSponsoring(sponsoring) }
val found = sponsoringRepository.findOne(sponsoring.id)
assertEquals(ACCEPTED, found.status)
}
}
| src/test/java/backend/model/sponsoring/SponsoringServiceImplTest.kt | 893353129 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.psi.mixins.impl
import com.demonwav.mcdev.nbt.lang.psi.mixins.NbttLongArrayMixin
import com.demonwav.mcdev.nbt.tags.TagLongArray
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
abstract class NbttLongArrayImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), NbttLongArrayMixin {
override fun getLongArrayTag(): TagLongArray {
return TagLongArray(getLongList().map { it.getLongTag().value }.toLongArray())
}
}
| src/main/kotlin/com/demonwav/mcdev/nbt/lang/psi/mixins/impl/NbttLongArrayImplMixin.kt | 675702363 |
package backend.services
interface ConfigurationService {
fun get(key: String): String?
fun getRequired(key: String): String
}
| src/main/java/backend/services/ConfigurationService.kt | 244671685 |
package org.openasr.idear.actions.recognition
import com.intellij.openapi.actionSystem.DataContext
//only selected configuration
class DebugActionRecognizer : ActionRecognizer {
override fun isMatching(sentence: String) = "debug" in sentence
override fun getActionInfo(sentence: String, dataContext: DataContext) = ActionCallInfo("Debug")
}
| src/main/java/org/openasr/idear/actions/recognition/DebugActionRecognizer.kt | 3829932928 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.findUsages
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.searching.usages.KotlinElementDescriptionProviderBase
import org.jetbrains.kotlin.idea.refactoring.rename.RenameJavaSyntheticPropertyHandler
import org.jetbrains.kotlin.idea.refactoring.rename.RenameKotlinPropertyProcessor
class KotlinElementDescriptionProvider : KotlinElementDescriptionProviderBase() {
override val PsiElement.isRenameJavaSyntheticPropertyHandler: Boolean
get() = this is RenameJavaSyntheticPropertyHandler.SyntheticPropertyWrapper
override val PsiElement.isRenameKotlinPropertyProcessor: Boolean
get() = this is RenameKotlinPropertyProcessor.PropertyMethodWrapper
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/findUsages/KotlinElementDescriptionProvider.kt | 1658279022 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.domain.internal
import android.os.Handler
import android.os.Looper
/**
* A forwarding interface for [Handler] to support mocking in tests.
*/
interface IOSchedHandler {
/**
* See [Handler.post]
*/
fun post(runnable: Runnable): Boolean
/**
* See [Handler.postDelayed]
*/
fun postDelayed(runnable: Runnable, millis: Long): Boolean
/**
* See [Handler.removeCallbacks]
*/
fun removeCallbacks(runnable: Runnable)
}
/**
* Main thread handler to be used across ioshced.
*/
class IOSchedMainHandler : IOSchedHandler {
private val handler = Handler(Looper.getMainLooper())
override fun post(runnable: Runnable) = handler.post(runnable)
override fun postDelayed(runnable: Runnable, millis: Long) =
handler.postDelayed(runnable, millis)
override fun removeCallbacks(runnable: Runnable) = handler.removeCallbacks(runnable)
}
| shared/src/main/java/com/google/samples/apps/iosched/shared/domain/internal/IOSchedHandler.kt | 3876617498 |
package com.github.vhromada.catalog.repository
import com.github.vhromada.catalog.domain.Show
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.querydsl.QuerydslPredicateExecutor
import java.util.Optional
/**
* An interface represents repository for shows.
*
* @author Vladimir Hromada
*/
interface ShowRepository : JpaRepository<Show, Int>, QuerydslPredicateExecutor<Show> {
/**
* Finds show by UUID.
*
* @param uuid UUID
* @return show
*/
fun findByUuid(uuid: String): Optional<Show>
}
| core/src/main/kotlin/com/github/vhromada/catalog/repository/ShowRepository.kt | 2021263077 |
package org.jetbrains.completion.full.line.local.suggest.ranking
import org.jetbrains.completion.full.line.local.CompletionModel
/**
* Interface for ranking models that would reorder completions
* based on information from completion model, prefix and context
*/
interface RankingModel {
/**
* Performs reordering of completions based on information from model, context and prefix
*/
fun rank(context: String, prefix: String, completions: List<CompletionModel.CompletionResult>): List<CompletionModel.CompletionResult>
}
| plugins/full-line/local/src/org/jetbrains/completion/full/line/local/suggest/ranking/RankingModel.kt | 1756194721 |
package io.github.chrislo27.rhre3.editor
import com.badlogic.gdx.graphics.Texture
import io.github.chrislo27.rhre3.track.tracker.Tracker
import io.github.chrislo27.rhre3.track.tracker.musicvolume.MusicVolumeChange
import io.github.chrislo27.rhre3.track.tracker.tempo.TempoChange
import io.github.chrislo27.toolboks.registry.AssetRegistry
import kotlin.reflect.KClass
enum class Tool(val texId: String, val nameId: String,
val trackerClass: KClass<out Tracker<*>>? = null, val keybinds: List<String> = listOf(),
val showSubbeatLines: Boolean = trackerClass != null) {
SELECTION("tool_selection", "tool.normal.name"),
MULTIPART_SPLIT("tool_multipart_split", "tool.multipartSplit.name"),
TEMPO_CHANGE("tool_tempo_change", "tool.tempoChange.name", trackerClass = TempoChange::class),
MUSIC_VOLUME("tool_music_volume", "tool.musicVolume.name", trackerClass = MusicVolumeChange::class),
TIME_SIGNATURE("tool_time_signature", "tool.timeSignature.name", showSubbeatLines = true),
SWING("tool_swing", "tool.swing.name"),
RULER("tool_ruler", "tool.ruler.name", keybinds = listOf("R"), showSubbeatLines = true),
PICKAXE("tool_pickaxe", "tool.pickaxe.name");
companion object {
val VALUES: List<Tool> by lazy { Tool.values().toList() }
}
val isTrackerRelated: Boolean = trackerClass != null
val index: Int by lazy { VALUES.indexOf(this) }
val texture: Texture
get() = AssetRegistry[texId]
} | core/src/main/kotlin/io/github/chrislo27/rhre3/editor/Tool.kt | 704692458 |
package org.stepic.droid.core
import android.content.Intent
import org.stepic.droid.model.CertificateListItem
import org.stepik.android.model.*
import org.stepik.android.model.Unit
import org.stepik.android.model.user.User
interface ShareHelper {
fun getIntentForCourseSharing(course: Course): Intent
fun getIntentForShareCertificate(certificateListItem: CertificateListItem.Data): Intent
fun getIntentForStepSharing(step: Step, lesson: Lesson, unit: Unit?): Intent
fun getIntentForSectionSharing(section: Section): Intent
fun getIntentForUserSharing(user: User): Intent
fun getIntentForCourseResultSharing(course: Course, message: String): Intent
fun getIntentForCourseResultCertificateSharing(certificate: Certificate, message: String): Intent
}
| app/src/main/java/org/stepic/droid/core/ShareHelper.kt | 2723286871 |
package uk.co.paul_matthews.kotlinandroid
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("uk.co.paul_matthews.kotlinandroid", appContext.packageName)
}
}
| app/src/androidTest/java/uk/co/paul_matthews/kotlinandroid/ExampleInstrumentedTest.kt | 530676253 |
package com.devslopes.datafrost1997.gitterchat.Services
import android.content.Context
import android.util.Log
import com.android.volley.Response
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import com.devslopes.datafrost1997.gitterchat.Controller.App
import com.devslopes.datafrost1997.gitterchat.Model.Channel
import com.devslopes.datafrost1997.gitterchat.Model.Message
import com.devslopes.datafrost1997.gitterchat.Utilities.URL_GET_CHANNELS
import com.devslopes.datafrost1997.gitterchat.Utilities.URL_GET_MESSAGES
import org.json.JSONException
/**
* Created by datafrost1997 on 16/10/17.
*/
object MessageService {
val channels = ArrayList<Channel> ()
val messages = ArrayList<Message> ()
fun getChannels(complete: (Boolean) -> Unit) {
val channelsRequest = object : JsonArrayRequest(Method.GET, URL_GET_CHANNELS, null , Response.Listener { response ->
try {
for (x in 0 until response.length()) {
val channel = response.getJSONObject(x)
val name = channel.getString("name")
val chanDesc = channel.getString("description")
val channelId = channel.getString("_id")
val newChannel = Channel(name, chanDesc, channelId)
this.channels.add(newChannel)
}
complete(true)
} catch (e: JSONException) {
Log.d("JSON", "EXC: " + e.localizedMessage)
complete(false)
}
}, Response.ErrorListener { error ->
Log.d("ERROR", "Couldn't Retrieve Channels")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers.put("Authorization", "Bearer ${App.prefs.authToken}")
return headers
}
}
App.prefs.requestQueue.add(channelsRequest)
}
fun getMessages(channelId: String, complete: (Boolean) -> Unit) {
val url = "$URL_GET_MESSAGES$channelId"
val messagesRequest = object : JsonArrayRequest(Method.GET, url, null, Response.Listener { response ->
clearMessages()
try {
for (x in 0 until response.length()) {
val message = response.getJSONObject(x)
val messageBody = message.getString("messageBody")
val channelId = message.getString("channelId")
val id = message.getString("_id")
val userName = message.getString("userName")
val userAvatar = message.getString("userAvatar")
val userAvatarColor = message.getString("userAvatarColor")
val timeStamp = message.getString("timeStamp")
val newMessage = Message(messageBody, userName, channelId, userAvatar, userAvatarColor, id, timeStamp)
this.messages.add(newMessage)
}
complete(true)
} catch (e: JSONException) {
Log.d("JSON", "EXC: " + e.localizedMessage)
complete(false)
}
}, Response.ErrorListener {
Log.d("ERROR", "Couldn't Retrieve Channels")
complete(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers.put("Authorization", "Bearer ${App.prefs.authToken}")
return headers
}
}
App.prefs.requestQueue.add(messagesRequest)
}
fun clearMessages() {
messages.clear()
}
fun clearChannels(){
channels.clear()
}
} | app/src/main/java/com/devslopes/datafrost1997/gitterchat/Services/MessageService.kt | 3844992744 |
// 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.codeInspection.apiUsage
import com.intellij.lang.java.JavaLanguage
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.uast.UastVisitorAdapter
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
/**
* Non-recursive UAST visitor that detects usages of APIs in source code of UAST-supporting languages
* and reports them via [ApiUsageProcessor] interface.
*/
@ApiStatus.Experimental
class ApiUsageUastVisitor(private val apiUsageProcessor: ApiUsageProcessor) : AbstractUastNonRecursiveVisitor() {
companion object {
@JvmStatic
fun createPsiElementVisitor(apiUsageProcessor: ApiUsageProcessor): PsiElementVisitor =
UastVisitorAdapter(ApiUsageUastVisitor(apiUsageProcessor), true)
}
override fun visitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression): Boolean {
if (maybeProcessReferenceInsideImportStatement(node)) {
return true
}
if (maybeProcessJavaModuleReference(node)) {
return true
}
if (isMethodReferenceOfCallExpression(node)
|| isNewArrayClassReference(node)
|| isMethodReferenceOfCallableReferenceExpression(node)
|| isSelectorOfQualifiedReference(node)
) {
return true
}
if (isSuperOrThisCall(node)) {
return true
}
val resolved = node.resolve()
if (resolved is PsiMethod) {
if (isClassReferenceInConstructorInvocation(node) || isClassReferenceInKotlinSuperClassConstructor(node)) {
/*
Suppose a code:
```
object : SomeClass(42) { }
or
new SomeClass(42)
```
with USimpleNameReferenceExpression pointing to `SomeClass`.
We want ApiUsageProcessor to notice two events: 1) reference to `SomeClass` and 2) reference to `SomeClass(int)` constructor.
But Kotlin UAST resolves this simple reference to the PSI constructor of the class SomeClass.
So we resolve it manually to the class because the constructor will be handled separately
in "visitObjectLiteralExpression" or "visitCallExpression".
*/
val resolvedClass = resolved.containingClass
if (resolvedClass != null) {
apiUsageProcessor.processReference(node, resolvedClass, null)
}
return true
}
}
if (resolved is PsiModifierListOwner) {
apiUsageProcessor.processReference(node, resolved, null)
return true
}
if (resolved == null) {
/*
* KT-30522 UAST for Kotlin: reference to annotation parameter resolves to null.
*/
val psiReferences = node.sourcePsi?.references.orEmpty()
for (psiReference in psiReferences) {
val target = psiReference.resolve()?.toUElement()?.javaPsi as? PsiAnnotationMethod
if (target != null) {
apiUsageProcessor.processReference(node, target, null)
return true
}
}
}
return true
}
override fun visitQualifiedReferenceExpression(node: UQualifiedReferenceExpression): Boolean {
if (maybeProcessReferenceInsideImportStatement(node)) {
return true
}
if (node.sourcePsi is PsiMethodCallExpression || node.selector is UCallExpression) {
//UAST for Java produces UQualifiedReferenceExpression for both PsiMethodCallExpression and PsiReferenceExpression inside it
//UAST for Kotlin produces UQualifiedReferenceExpression with UCallExpression as selector
return true
}
var resolved = node.resolve()
if (resolved == null) {
resolved = node.selector.tryResolve()
}
if (resolved is PsiModifierListOwner) {
apiUsageProcessor.processReference(node.selector, resolved, node.receiver)
}
return true
}
private fun isKotlin(node: UElement): Boolean {
val sourcePsi = node.sourcePsi ?: return false
return sourcePsi.language.id.contains("kotlin", true)
}
override fun visitCallableReferenceExpression(node: UCallableReferenceExpression): Boolean {
/*
* KT-31181: Kotlin UAST: UCallableReferenceExpression.referenceNameElement is always null.
*/
fun workaroundKotlinGetReferenceNameElement(node: UCallableReferenceExpression): UElement? {
if (isKotlin(node)) {
val sourcePsi = node.sourcePsi
if (sourcePsi != null) {
val children = sourcePsi.children
if (children.size == 2) {
return children[1].toUElement()
}
}
}
return null
}
val resolve = node.resolve()
if (resolve is PsiModifierListOwner) {
val sourceNode = node.referenceNameElement ?: workaroundKotlinGetReferenceNameElement(node) ?: node
apiUsageProcessor.processReference(sourceNode, resolve, node.qualifierExpression)
//todo support this for other JVM languages
val javaMethodReference = node.sourcePsi as? PsiMethodReferenceExpression
if (javaMethodReference != null) {
//a reference to the functional interface will be added by compiler
val resolved = PsiUtil.resolveGenericsClassInType(javaMethodReference.functionalInterfaceType).element
if (resolved != null) {
apiUsageProcessor.processReference(node, resolved, null)
}
}
}
return true
}
override fun visitCallExpression(node: UCallExpression): Boolean {
if (node.sourcePsi is PsiExpressionStatement) {
//UAST for Java generates UCallExpression for PsiExpressionStatement and PsiMethodCallExpression inside it.
return true
}
val psiMethod = node.resolve()
val sourceNode = node.methodIdentifier ?: node.classReference?.referenceNameElement ?: node.classReference ?: node
if (psiMethod != null) {
val containingClass = psiMethod.containingClass
if (psiMethod.isConstructor) {
if (containingClass != null) {
apiUsageProcessor.processConstructorInvocation(sourceNode, containingClass, psiMethod, null)
}
}
else {
apiUsageProcessor.processReference(sourceNode, psiMethod, node.receiver)
}
return true
}
if (node.kind == UastCallKind.CONSTRUCTOR_CALL) {
//Java does not resolve constructor for subclass constructor's "super()" statement
// if the superclass has the default constructor, which is not declared in source code and lacks PsiMethod.
val superClass = node.getContainingUClass()?.javaPsi?.superClass ?: return true
apiUsageProcessor.processConstructorInvocation(sourceNode, superClass, null, null)
return true
}
val classReference = node.classReference
if (classReference != null) {
val resolvedClass = classReference.resolve() as? PsiClass
if (resolvedClass != null) {
if (node.kind == UastCallKind.CONSTRUCTOR_CALL) {
val emptyConstructor = resolvedClass.constructors.find { it.parameterList.isEmpty }
apiUsageProcessor.processConstructorInvocation(sourceNode, resolvedClass, emptyConstructor, null)
}
else {
apiUsageProcessor.processReference(sourceNode, resolvedClass, node.receiver)
}
}
return true
}
return true
}
override fun visitObjectLiteralExpression(node: UObjectLiteralExpression): Boolean {
val psiMethod = node.resolve()
val sourceNode = node.methodIdentifier
?: node.classReference?.referenceNameElement
?: node.classReference
?: node.declaration.uastSuperTypes.firstOrNull()
?: node
if (psiMethod != null) {
val containingClass = psiMethod.containingClass
if (psiMethod.isConstructor) {
if (containingClass != null) {
apiUsageProcessor.processConstructorInvocation(sourceNode, containingClass, psiMethod, node.declaration)
}
}
}
else {
maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(sourceNode, node.declaration)
}
return true
}
override fun visitElement(node: UElement): Boolean {
if (node is UNamedExpression) {
//IDEA-209279: UAstVisitor lacks a hook for UNamedExpression
//KT-30522: Kotlin does not generate UNamedExpression for annotation's parameters.
processNamedExpression(node)
return true
}
return super.visitElement(node)
}
override fun visitClass(node: UClass): Boolean {
val uastAnchor = node.uastAnchor
if (uastAnchor == null || node is UAnonymousClass || node.javaPsi is PsiTypeParameter) {
return true
}
maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(uastAnchor, node)
return true
}
override fun visitMethod(node: UMethod): Boolean {
if (node.isConstructor) {
checkImplicitCallOfSuperEmptyConstructor(node)
}
else {
checkMethodOverriding(node)
}
return true
}
override fun visitLambdaExpression(node: ULambdaExpression): Boolean {
val explicitClassReference = (node.uastParent as? UCallExpression)?.classReference
if (explicitClassReference == null) {
//a reference to the functional interface will be added by compiler
val resolved = PsiUtil.resolveGenericsClassInType(node.functionalInterfaceType).element
if (resolved != null) {
apiUsageProcessor.processReference(node, resolved, null)
}
}
return true
}
private fun maybeProcessJavaModuleReference(node: UElement): Boolean {
val sourcePsi = node.sourcePsi
if (sourcePsi is PsiJavaModuleReferenceElement) {
val reference = sourcePsi.reference
val target = reference?.resolve()
if (target != null) {
apiUsageProcessor.processJavaModuleReference(reference, target)
}
return true
}
return false
}
private fun maybeProcessReferenceInsideImportStatement(node: UReferenceExpression): Boolean {
if (isInsideImportStatement(node)) {
if (isKotlin(node)) {
/*
UAST for Kotlin 1.3.30 import statements have bugs.
KT-30546: some references resolve to nulls.
KT-30957: simple references for members resolve incorrectly to class declaration, not to the member declaration
Therefore, we have to fallback to base PSI for Kotlin references.
*/
val resolved = node.sourcePsi?.reference?.resolve()
val target = (resolved?.toUElement()?.javaPsi ?: resolved) as? PsiModifierListOwner
if (target != null) {
apiUsageProcessor.processImportReference(node, target)
}
}
else {
val resolved = node.resolve() as? PsiModifierListOwner
if (resolved != null) {
apiUsageProcessor.processImportReference(node.referenceNameElement ?: node, resolved)
}
}
return true
}
return false
}
private fun isInsideImportStatement(node: UElement): Boolean {
val sourcePsi = node.sourcePsi
if (sourcePsi != null && sourcePsi.language == JavaLanguage.INSTANCE) {
return PsiTreeUtil.getParentOfType(sourcePsi, PsiImportStatementBase::class.java) != null
}
return sourcePsi.findContaining(UImportStatement::class.java) != null
}
private fun maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(sourceNode: UElement, subclassDeclaration: UClass) {
val instantiatedClass = subclassDeclaration.javaPsi.superClass ?: return
val subclassHasExplicitConstructor = subclassDeclaration.methods.any { it.isConstructor }
val emptyConstructor = instantiatedClass.constructors.find { it.parameterList.isEmpty }
if (subclassDeclaration is UAnonymousClass || !subclassHasExplicitConstructor) {
apiUsageProcessor.processConstructorInvocation(sourceNode, instantiatedClass, emptyConstructor, subclassDeclaration)
}
}
private fun processNamedExpression(node: UNamedExpression) {
val sourcePsi = node.sourcePsi
val annotationMethod = sourcePsi?.reference?.resolve() as? PsiAnnotationMethod
if (annotationMethod != null) {
val sourceNode = (sourcePsi as? PsiNameValuePair)?.nameIdentifier?.toUElement() ?: node
apiUsageProcessor.processReference(sourceNode, annotationMethod, null)
}
}
private fun checkImplicitCallOfSuperEmptyConstructor(constructor: UMethod) {
val containingUClass = constructor.getContainingUClass() ?: return
val superClass = containingUClass.javaPsi.superClass ?: return
val uastBody = constructor.uastBody
val uastAnchor = constructor.uastAnchor
if (uastAnchor != null && isImplicitCallOfSuperEmptyConstructorFromSubclassConstructorBody(uastBody)) {
val emptyConstructor = superClass.constructors.find { it.parameterList.isEmpty }
apiUsageProcessor.processConstructorInvocation(uastAnchor, superClass, emptyConstructor, null)
}
}
private fun isImplicitCallOfSuperEmptyConstructorFromSubclassConstructorBody(constructorBody: UExpression?): Boolean {
if (constructorBody == null || constructorBody is UBlockExpression && constructorBody.expressions.isEmpty()) {
//Empty constructor body => implicit super() call.
return true
}
val firstExpression = (constructorBody as? UBlockExpression)?.expressions?.firstOrNull() ?: constructorBody
if (firstExpression !is UCallExpression) {
//First expression is not super() => the super() is implicit.
return true
}
if (firstExpression.valueArgumentCount > 0) {
//Invocation of non-empty super(args) constructor.
return false
}
val methodName = firstExpression.methodIdentifier?.name ?: firstExpression.methodName
return methodName != "super" && methodName != "this"
}
private fun checkMethodOverriding(node: UMethod) {
val method = node.javaPsi
val superMethods = method.findSuperMethods(true)
for (superMethod in superMethods) {
apiUsageProcessor.processMethodOverriding(node, superMethod)
}
}
/**
* UAST for Kotlin generates UAST tree with "UnknownKotlinExpression (CONSTRUCTOR_CALLEE)" for the following expressions:
* 1) an object literal expression: `object : BaseClass() { ... }`
* 2) a super class constructor invocation `class Derived : BaseClass(42) { ... }`
*
*
* ```
* UObjectLiteralExpression
* UnknownKotlinExpression (CONSTRUCTOR_CALLEE)
* UTypeReferenceExpression (BaseClass)
* USimpleNameReferenceExpression (BaseClass)
* ```
*
* and
*
* ```
* UCallExpression (kind = CONSTRUCTOR_CALL)
* UnknownKotlinExpression (CONSTRUCTOR_CALLEE)
* UTypeReferenceExpression (BaseClass)
* USimpleNameReferenceExpression (BaseClass)
* ```
*
* This method checks if the given simple reference points to the `BaseClass` part,
* which is treated by Kotlin UAST as a reference to `BaseClass'` constructor, not to the `BaseClass` itself.
*/
private fun isClassReferenceInKotlinSuperClassConstructor(expression: USimpleNameReferenceExpression): Boolean {
val parent1 = expression.uastParent
val parent2 = parent1?.uastParent
val parent3 = parent2?.uastParent
return parent1 is UTypeReferenceExpression
&& parent2 != null && parent2.asLogString().contains("CONSTRUCTOR_CALLEE")
&& (parent3 is UObjectLiteralExpression || parent3 is UCallExpression && parent3.kind == UastCallKind.CONSTRUCTOR_CALL)
}
private fun isSelectorOfQualifiedReference(expression: USimpleNameReferenceExpression): Boolean {
val qualifiedReference = expression.uastParent as? UQualifiedReferenceExpression ?: return false
return haveSameSourceElement(expression, qualifiedReference.selector)
}
private fun isNewArrayClassReference(simpleReference: USimpleNameReferenceExpression): Boolean {
val callExpression = simpleReference.uastParent as? UCallExpression ?: return false
return callExpression.kind == UastCallKind.NEW_ARRAY_WITH_DIMENSIONS
}
private fun isSuperOrThisCall(simpleReference: USimpleNameReferenceExpression): Boolean {
val callExpression = simpleReference.uastParent as? UCallExpression ?: return false
return callExpression.kind == UastCallKind.CONSTRUCTOR_CALL &&
(callExpression.methodIdentifier?.name == "super" || callExpression.methodIdentifier?.name == "this")
}
private fun isClassReferenceInConstructorInvocation(simpleReference: USimpleNameReferenceExpression): Boolean {
if (isSuperOrThisCall(simpleReference)) {
return false
}
val callExpression = simpleReference.uastParent as? UCallExpression ?: return false
if (callExpression.kind != UastCallKind.CONSTRUCTOR_CALL) {
return false
}
val classReferenceNameElement = callExpression.classReference?.referenceNameElement
if (classReferenceNameElement != null) {
return haveSameSourceElement(classReferenceNameElement, simpleReference.referenceNameElement)
}
return callExpression.resolve()?.name == simpleReference.resolvedName
}
private fun isMethodReferenceOfCallExpression(expression: USimpleNameReferenceExpression): Boolean {
val callExpression = expression.uastParent as? UCallExpression ?: return false
if (callExpression.kind != UastCallKind.METHOD_CALL) {
return false
}
val expressionNameElement = expression.referenceNameElement
val methodIdentifier = callExpression.methodIdentifier
return methodIdentifier != null && haveSameSourceElement(expressionNameElement, methodIdentifier)
}
private fun isMethodReferenceOfCallableReferenceExpression(expression: USimpleNameReferenceExpression): Boolean {
val callableReferenceExpression = expression.uastParent as? UCallableReferenceExpression ?: return false
if (haveSameSourceElement(callableReferenceExpression.referenceNameElement, expression)) {
return true
}
return expression.identifier == callableReferenceExpression.callableName
}
private fun haveSameSourceElement(element1: UElement?, element2: UElement?): Boolean {
if (element1 == null || element2 == null) return false
val sourcePsi1 = element1.sourcePsi
return sourcePsi1 != null && sourcePsi1 == element2.sourcePsi
}
}
| java/java-analysis-impl/src/com/intellij/codeInspection/apiUsage/ApiUsageUastVisitor.kt | 676516737 |
package ch.difty.scipamato.publ.misc
import ch.difty.scipamato.publ.config.ScipamatoPublicProperties
import org.springframework.stereotype.Service
import java.util.Locale
import java.util.regex.Pattern
/**
* [LocaleExtractor] implementation that is capable of extracting
* the locale string from a parentUrl passed in as input.
*
* Examples of `parentUrl` and the resulting locales are:
*
* * https://www.foo.ch/de/whatever/follows/next/ : Locale.German
* * https://www.foo.ch/en/projects/something/else/ : Locale.English
* * https://www.foo.ch/fr/bar/baz/ : LOCALE.FRENCH
*/
@Service
class ParentUrlLocaleExtractor(properties: ScipamatoPublicProperties) : LocaleExtractor {
private val defaultLocale: String = properties.defaultLocalization
override fun extractLocaleFrom(input: String?): Locale = Locale.forLanguageTag(extractLanguageCode(input))
private fun extractLanguageCode(input: String?): String {
if (input != null) {
val matcher = PATTERN.matcher(input)
if (matcher.find()) return matcher.group(1)
}
return defaultLocale
}
companion object {
private val PATTERN = Pattern.compile("""https?://?[^/]+/(\w\w)/.+""", Pattern.CASE_INSENSITIVE)
}
}
| public/public-web/src/main/kotlin/ch/difty/scipamato/publ/misc/ParentUrlLocaleExtractor.kt | 1151957825 |
/*
* Copyright (C) 2020 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.util
import java.io.IOException
import java.net.InetAddress
object InetAddresses {
@Throws(IOException::class)
fun from(address: Int): InetAddress = InetAddress.getByAddress(
byteArrayOf(
address.toByte(),
(address ushr 8).toByte(),
(address ushr 16).toByte(),
(address ushr 24).toByte()
)
)
} | app/src/main/java/org/monora/uprotocol/client/android/util/InetAddresses.kt | 2545452810 |
/*
* Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import java.util.concurrent.atomic.*
/**
* Atomic array with lock-free reads and synchronized modifications. It logically has an unbounded size,
* is implicitly filled with nulls, and is resized on updates as needed to grow.
*/
internal class ResizableAtomicArray<T>(initialLength: Int) {
@Volatile
private var array = AtomicReferenceArray<T>(initialLength)
// for debug output
public fun currentLength(): Int = array.length()
public operator fun get(index: Int): T? {
val array = this.array // volatile read
return if (index < array.length()) array[index] else null
}
// Must not be called concurrently, e.g. always use synchronized(this) to call this function
fun setSynchronized(index: Int, value: T?) {
val curArray = this.array
val curLen = curArray.length()
if (index < curLen) {
curArray[index] = value
} else {
val newArray = AtomicReferenceArray<T>((index + 1).coerceAtLeast(2 * curLen))
for (i in 0 until curLen) newArray[i] = curArray[i]
newArray[index] = value
array = newArray // copy done
}
}
}
| kotlinx-coroutines-core/jvm/src/internal/ResizableAtomicArray.kt | 2697023414 |
// 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 git4idea.test
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.AbstractVcsHelper
import com.intellij.openapi.vcs.Executor
import com.intellij.openapi.vcs.Executor.cd
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.VcsShowConfirmationOption
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.testFramework.RunAll
import com.intellij.testFramework.replaceService
import com.intellij.testFramework.vcs.AbstractVcsTestCase
import com.intellij.util.ThrowableRunnable
import com.intellij.vcs.log.VcsFullCommitDetails
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.test.VcsPlatformTest
import git4idea.DialogManager
import git4idea.GitUtil
import git4idea.GitVcs
import git4idea.commands.Git
import git4idea.commands.GitHandler
import git4idea.config.GitExecutableManager
import git4idea.config.GitVcsApplicationSettings
import git4idea.config.GitVcsSettings
import git4idea.config.GitSaveChangesPolicy
import git4idea.log.GitLogProvider
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.test.GitPlatformTest.ConfigScope.GLOBAL
import git4idea.test.GitPlatformTest.ConfigScope.SYSTEM
import java.io.File
abstract class GitPlatformTest : VcsPlatformTest() {
protected lateinit var repositoryManager: GitRepositoryManager
protected lateinit var settings: GitVcsSettings
protected lateinit var appSettings: GitVcsApplicationSettings
protected lateinit var git: TestGitImpl
protected lateinit var vcs: GitVcs
protected lateinit var commitContext: CommitContext
protected lateinit var dialogManager: TestDialogManager
protected lateinit var vcsHelper: MockVcsHelper
protected lateinit var logProvider: GitLogProvider
private lateinit var credentialHelpers: Map<ConfigScope, List<String>>
private var globalSslVerify: Boolean? = null
@Throws(Exception::class)
override fun setUp() {
super.setUp()
dialogManager = service<DialogManager>() as TestDialogManager
vcsHelper = MockVcsHelper(myProject)
project.replaceService(AbstractVcsHelper::class.java, vcsHelper, testRootDisposable)
repositoryManager = GitUtil.getRepositoryManager(project)
git = TestGitImpl()
ApplicationManager.getApplication().replaceService(Git::class.java, git, testRootDisposable)
vcs = GitVcs.getInstance(project)
vcs.doActivate()
commitContext = CommitContext()
settings = GitVcsSettings.getInstance(project)
appSettings = GitVcsApplicationSettings.getInstance()
appSettings.setPathToGit(gitExecutable())
GitExecutableManager.getInstance().testGitExecutableVersionValid(project)
logProvider = findGitLogProvider(project)
assumeSupportedGitVersion(vcs)
addSilently()
removeSilently()
overrideDefaultSaveChangesPolicy()
credentialHelpers = if (hasRemoteGitOperation()) readAndResetCredentialHelpers() else emptyMap()
globalSslVerify = if (hasRemoteGitOperation()) readAndDisableSslVerifyGlobally() else null
}
@Throws(Exception::class)
override fun tearDown() {
RunAll()
.append(ThrowableRunnable { restoreCredentialHelpers() })
.append(ThrowableRunnable { restoreGlobalSslVerify() })
.append(ThrowableRunnable { if (::dialogManager.isInitialized) dialogManager.cleanup() })
.append(ThrowableRunnable { if (::git.isInitialized) git.reset() })
.append(ThrowableRunnable { if (::settings.isInitialized) settings.appSettings.setPathToGit(null) })
.append(ThrowableRunnable { super.tearDown() })
.run()
}
override fun getDebugLogCategories(): Collection<String> {
return super.getDebugLogCategories().plus(listOf("#" + Executor::class.java.name,
"#git4idea",
"#output." + GitHandler::class.java.name))
}
protected open fun hasRemoteGitOperation() = false
protected open fun createRepository(rootDir: String): GitRepository {
return createRepository(project, rootDir)
}
protected open fun getDefaultSaveChangesPolicy() : GitSaveChangesPolicy = GitSaveChangesPolicy.SHELVE
private fun overrideDefaultSaveChangesPolicy() {
settings.saveChangesPolicy = getDefaultSaveChangesPolicy()
}
/**
* Clones the given source repository into a bare parent.git and adds the remote origin.
*/
protected fun prepareRemoteRepo(source: GitRepository, target: File = File(testRoot, "parent.git"), remoteName: String = "origin"): File {
cd(testRoot)
git("clone --bare '${source.root.path}' ${target.path}")
cd(source)
git("remote add ${remoteName} '${target.path}'")
return target
}
/**
* Creates 3 repositories: a bare "parent" repository, and two clones of it.
*
* One of the clones - "bro" - is outside of the project.
* Another one is inside the project, is registered as a Git root, and is represented by [GitRepository].
*
* Parent and bro are created just inside the [testRoot](myTestRoot).
* The main clone is created at [repoRoot], which is assumed to be inside the project.
*/
protected fun setupRepositories(repoRoot: String, parentName: String, broName: String): ReposTrinity {
val parentRepo = createParentRepo(parentName)
val broRepo = createBroRepo(broName, parentRepo)
val repository = createRepository(project, repoRoot)
cd(repository)
git("remote add origin " + parentRepo.path)
git("push --set-upstream origin master:master")
cd(broRepo.path)
git("pull")
return ReposTrinity(repository, parentRepo, broRepo)
}
private fun createParentRepo(parentName: String): File {
cd(testRoot)
git("init --bare $parentName.git")
return File(testRoot, "$parentName.git")
}
protected fun createBroRepo(broName: String, parentRepo: File): File {
cd(testRoot)
git("clone " + parentRepo.name + " " + broName)
cd(broName)
setupDefaultUsername(project)
return File(testRoot, broName)
}
private fun doActionSilently(op: VcsConfiguration.StandardConfirmation) {
AbstractVcsTestCase.setStandardConfirmation(project, GitVcs.NAME, op, VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY)
}
private fun addSilently() {
doActionSilently(VcsConfiguration.StandardConfirmation.ADD)
}
private fun removeSilently() {
doActionSilently(VcsConfiguration.StandardConfirmation.REMOVE)
}
protected fun installHook(gitDir: File, hookName: String, hookContent: String) {
val hookFile = File(gitDir, "hooks/$hookName")
FileUtil.writeToFile(hookFile, hookContent)
hookFile.setExecutable(true, false)
}
private fun readAndResetCredentialHelpers(): Map<ConfigScope, List<String>> {
val system = readAndResetCredentialHelper(SYSTEM)
val global = readAndResetCredentialHelper(GLOBAL)
return mapOf(SYSTEM to system, GLOBAL to global)
}
private fun readAndResetCredentialHelper(scope: ConfigScope): List<String> {
val values = git("config ${scope.param()} --get-all -z credential.helper", true).split("\u0000").filter { it.isNotBlank() }
git("config ${scope.param()} --unset-all credential.helper", true)
return values
}
private fun restoreCredentialHelpers() {
credentialHelpers.forEach { (scope, values) ->
values.forEach { git("config --add ${scope.param()} credential.helper ${it}", true) }
}
}
private fun readAndDisableSslVerifyGlobally(): Boolean? {
val value = git("config --global --get-all -z http.sslVerify", true)
.split("\u0000")
.singleOrNull { it.isNotBlank() }
?.toBoolean()
git("config --global http.sslVerify false", true)
return value
}
private fun restoreGlobalSslVerify() {
if (globalSslVerify != null) {
git("config --global http.sslVerify ${globalSslVerify}", true)
}
else {
git("config --global --unset http.sslVerify", true)
}
}
protected fun readDetails(hashes: List<String>): List<VcsFullCommitDetails> = VcsLogUtil.getDetails(logProvider, projectRoot, hashes)
protected fun readDetails(hash: String) = readDetails(listOf(hash)).first()
protected fun commit(changes: Collection<Change>) {
val exceptions = vcs.checkinEnvironment!!.commit(changes.toList(), "comment", commitContext, mutableSetOf())
exceptions?.forEach { fail("Exception during executing the commit: " + it.message) }
updateChangeListManager()
}
protected fun `do nothing on merge`() {
vcsHelper.onMerge {}
}
protected fun `mark as resolved on merge`() {
vcsHelper.onMerge { git("add -u .") }
}
protected fun `assert merge dialog was shown`() {
assertTrue("Merge dialog was not shown", vcsHelper.mergeDialogWasShown())
}
protected fun `assert commit dialog was shown`() {
assertTrue("Commit dialog was not shown", vcsHelper.commitDialogWasShown())
}
protected fun assertNoChanges() {
changeListManager.assertNoChanges()
}
protected fun assertChanges(changes: ChangesBuilder.() -> Unit): List<Change> {
return changeListManager.assertChanges(changes)
}
protected fun assertChangesWithRefresh(changes: ChangesBuilder.() -> Unit): List<Change> {
VcsDirtyScopeManager.getInstance(project).markEverythingDirty()
changeListManager.ensureUpToDate()
return changeListManager.assertChanges(changes)
}
protected data class ReposTrinity(val projectRepo: GitRepository, val parent: File, val bro: File)
private enum class ConfigScope {
SYSTEM,
GLOBAL;
fun param() = "--${name.toLowerCase()}"
}
}
| plugins/git4idea/tests/git4idea/test/GitPlatformTest.kt | 2707575340 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl.simpleTitleParts
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.project.Project
class ProductVersionTitleInfoProvider(project: Project) : SimpleTitleInfoProvider(VMOOption("ide.ui.version.in.title"), RegistryOption("ide.borderless.title.version", project)) {
override val value: String = ApplicationInfo.getInstance().fullVersion
} | platform/platform-impl/src/com/intellij/openapi/wm/impl/simpleTitleParts/ProductVersionTitleInfoProvider.kt | 436128772 |
/*
* Copyright (c) 2011 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.moe.client.codebase.expressions;
/**
* An Operation in the MOE Expression Language is an operator followed by a term.
*
* <p>E.g., |patch(file="/path/to/path.txt") or >public
*/
data class Operation(val operator: Operator, val term: Term) {
override fun toString(): String = "$operator$term"
}
| client/src/main/java/com/google/devtools/moe/client/codebase/expressions/Operation.kt | 964203822 |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* 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 kotlin.text.regex
/**
* Represents word boundary, checks current character and previous one. If they have different types returns true;
*/
internal class WordBoundarySet(var positive: Boolean) : SimpleSet() {
override fun matches(startIndex: Int, testString: CharSequence, matchResult: MatchResultImpl): Int {
val curChar = if (startIndex >= testString.length) ' ' else testString[startIndex]
val prevChar = if (startIndex == 0) ' ' else testString[startIndex - 1]
val right = curChar == ' ' || isSpace(curChar, startIndex, testString)
val left = prevChar == ' ' || isSpace(prevChar, startIndex - 1, testString)
return if (left xor right xor positive)
-1
else
next.matches(startIndex, testString, matchResult)
}
/** Returns false, because word boundary does not consumes any characters and do not move string index. */
override fun hasConsumed(matchResult: MatchResultImpl): Boolean = false
override val name: String
get() = "WordBoundarySet"
private fun isSpace(char: Char, startIndex: Int, testString: CharSequence): Boolean {
if (char.isLetterOrDigit() || char == '_') {
return false
}
if (char.category == CharCategory.NON_SPACING_MARK) {
var index = startIndex
while (--index >= 0) {
val ch = testString[index]
when {
ch.isLetterOrDigit() -> return false
char.category != CharCategory.NON_SPACING_MARK -> return true
}
}
}
return true
}
}
| runtime/src/main/kotlin/kotlin/text/regex/sets/WordBoundarySet.kt | 970408561 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation
import androidx.compose.ui.unit.Density
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.sign
/**
* Earth's gravity in SI units (m/s^2); used to compute deceleration based on friction.
*/
private const val GravityEarth = 9.80665f
private const val InchesPerMeter = 39.37f
/**
* The default rate of deceleration for a fling if not specified in the
* [FlingCalculator] constructor.
*/
private val DecelerationRate = (ln(0.78) / ln(0.9)).toFloat()
/**
* Compute the rate of deceleration based on pixel density, physical gravity
* and a [coefficient of friction][friction].
*/
private fun computeDeceleration(friction: Float, density: Float): Float =
GravityEarth * InchesPerMeter * density * 160f * friction
/**
* Configuration for Android-feel flinging motion at the given density.
*
* @param friction scroll friction.
* @param density density of the screen. Use LocalDensity to get current density in composition.
*/
internal class FlingCalculator(
private val friction: Float,
val density: Density
) {
/**
* A density-specific coefficient adjusted to physical values.
*/
private val magicPhysicalCoefficient: Float = computeDeceleration(density)
/**
* Computes the rate of deceleration in pixels based on
* the given [density].
*/
private fun computeDeceleration(density: Density) =
computeDeceleration(0.84f, density.density)
private fun getSplineDeceleration(velocity: Float): Double = AndroidFlingSpline.deceleration(
velocity,
friction * magicPhysicalCoefficient
)
/**
* Compute the duration in milliseconds of a fling with an initial velocity of [velocity]
*/
fun flingDuration(velocity: Float): Long {
val l = getSplineDeceleration(velocity)
val decelMinusOne = DecelerationRate - 1.0
return (1000.0 * exp(l / decelMinusOne)).toLong()
}
/**
* Compute the distance of a fling in units given an initial [velocity] of units/second
*/
fun flingDistance(velocity: Float): Float {
val l = getSplineDeceleration(velocity)
val decelMinusOne = DecelerationRate - 1.0
return (
friction * magicPhysicalCoefficient
* exp(DecelerationRate / decelMinusOne * l)
).toFloat()
}
/**
* Compute all interesting information about a fling of initial velocity [velocity].
*/
fun flingInfo(velocity: Float): FlingInfo {
val l = getSplineDeceleration(velocity)
val decelMinusOne = DecelerationRate - 1.0
return FlingInfo(
initialVelocity = velocity,
distance = (
friction * magicPhysicalCoefficient
* exp(DecelerationRate / decelMinusOne * l)
).toFloat(),
duration = (1000.0 * exp(l / decelMinusOne)).toLong()
)
}
/**
* Info about a fling started with [initialVelocity]. The units of [initialVelocity]
* determine the distance units of [distance] and the time units of [duration].
*/
data class FlingInfo(
val initialVelocity: Float,
val distance: Float,
val duration: Long
) {
fun position(time: Long): Float {
val splinePos = if (duration > 0) time / duration.toFloat() else 1f
return distance * sign(initialVelocity) *
AndroidFlingSpline.flingPosition(splinePos).distanceCoefficient
}
fun velocity(time: Long): Float {
val splinePos = if (duration > 0) time / duration.toFloat() else 1f
return AndroidFlingSpline.flingPosition(splinePos).velocityCoefficient *
sign(initialVelocity) * distance / duration * 1000.0f
}
}
} | compose/animation/animation/src/commonMain/kotlin/androidx/compose/animation/FlingCalculator.kt | 928329690 |
/*
* Copyright 2019 Peter Kenji Yamanaka
*
* 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.pyamsoft.padlock.model.pin
sealed class PinEntryEvent {
data class Create(val complete: Boolean) : PinEntryEvent()
data class Clear(val complete: Boolean) : PinEntryEvent()
}
| padlock-model/src/main/java/com/pyamsoft/padlock/model/pin/PinEntryEvent.kt | 1518871690 |
package de.reiss.bible2net.theword.note.export
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import de.reiss.bible2net.theword.note.export.NoteExportStatus.Exporting
open class NoteExportViewModel(private val repository: NoteExportRepository) : ViewModel() {
private val exportLiveData: MutableLiveData<NoteExportStatus> = MutableLiveData()
open fun exportLiveData() = exportLiveData
open fun exportNotes() {
repository.exportNotes(exportLiveData())
}
fun isExporting() = exportLiveData().value is Exporting
class Factory(private val repository: NoteExportRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return NoteExportViewModel(repository) as T
}
}
fun clearLiveData() {
if (isExporting().not()) {
exportLiveData().postValue(null)
}
}
}
| app/src/main/java/de/reiss/bible2net/theword/note/export/NoteExportViewModel.kt | 714864913 |
// 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 com.intellij.util
import com.intellij.openapi.util.RecursionManager
import java.util.concurrent.atomic.AtomicReference
/**
* Same as [SafePublicationLazyImpl], but returns `null` in case of computation recursion occurred.
*/
internal class RecursionPreventingSafePublicationLazy<T>(recursionKey: Any?, initializer: () -> T) : Lazy<T?> {
@Volatile
private var initializer: (() -> T)? = { ourNotNullizer.notNullize(initializer()) }
private val valueRef: AtomicReference<T?> = AtomicReference()
private val recursionKey: Any = recursionKey ?: this
override val value: T?
get() {
val computedValue = valueRef.get()
if (computedValue !== null) {
return ourNotNullizer.nullize(computedValue)
}
val initializerValue = initializer
if (initializerValue === null) {
// Some thread managed to clear the initializer => it managed to set the value.
return ourNotNullizer.nullize(requireNotNull(valueRef.get()))
}
val stamp = RecursionManager.markStack()
val newValue = ourRecursionGuard.doPreventingRecursion(recursionKey, false, initializerValue)
// In case of recursion don't update [valueRef] and don't clear [initializer].
if (newValue === null) {
// Recursion occurred for this lazy.
return null
}
if (!stamp.mayCacheNow()) {
// Recursion occurred somewhere deep.
return ourNotNullizer.nullize(newValue)
}
if (!valueRef.compareAndSet(null, newValue)) {
// Some thread managed to set the value.
return ourNotNullizer.nullize(requireNotNull(valueRef.get()))
}
initializer = null
return ourNotNullizer.nullize(newValue)
}
override fun isInitialized(): Boolean = valueRef.get() !== null
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
companion object {
private val ourRecursionGuard = RecursionManager.createGuard<Any>("RecursionPreventingSafePublicationLazy")
private val ourNotNullizer = NotNullizer("RecursionPreventingSafePublicationLazy")
}
}
| platform/util-ex/src/com/intellij/util/RecursionPreventingSafePublicationLazy.kt | 1709111512 |
package transitiveStory.bottomActual.test.smokeTest
import transitiveStory.bottomActual.mppBeginning.tlInternalInCommon
class BottomActualCommonTestCallerToBeCalled {
// val apiCall = ForTheSmokeTest
val callingInternal = tlInternalInCommon
} | plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/top-mpp/src/commonTest/kotlin/transitiveStory/bottomActual/test/smokeTest/BottomActualCaommonTestCallerToBeCalled.kt | 1384815638 |
// "Change the signature of constructor 'FooBar'" "true"
private data class FooBar(val name: String)
fun test() {
val foo = FooBar(1, <caret>"name")
}
| plugins/kotlin/idea/tests/testData/quickfix/changeSignature/changeDataClassConstructor.kt | 1293380677 |
package foo
expect fun <!LINE_MARKER("descr='Has actuals in common'")!>foo<!>(): Int | plugins/kotlin/idea/tests/testData/multiplatform/duplicateActualsOneWithStrongIncompatibility/top/top.kt | 242003490 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.