repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
icela/FriceEngine | src/org/frice/obj/button/ImageButton.kt | 1 | 1128 | package org.frice.obj.button
import org.frice.event.MOUSE_PRESSED
import org.frice.event.OnMouseEvent
import org.frice.platform.FriceImage
import org.frice.platform.owner.ImageOwner
import org.frice.resource.image.ImageResource
import org.frice.util.shape.FShapeQuad
import java.util.function.Consumer
/**
* Created by ice1000 on 2016/9/3 0003.
*
* @author ice1000
* @since v0.5
*/
class ImageButton
@JvmOverloads
constructor(
var imageNormal: ImageResource,
var imagePressed: ImageResource = imageNormal,
override var x: Double,
override var y: Double) : ImageOwner, FButton {
override fun buttonStateChange(e: OnMouseEvent) {
bool = e.type == MOUSE_PRESSED
}
private var bool = false
override var width: Double = super.width
override var height: Double = super.height
override var rotate = 0.0
override var isVisible = true
override var died = false
override var onMouseListener: Consumer<OnMouseEvent>? = null
var collisionBox: FShapeQuad? = null
override val box: FShapeQuad get() = collisionBox ?: this
override val image: FriceImage get () = if (bool) imagePressed.image else imageNormal.image
} | agpl-3.0 | 1db8d3d4a3a82bf68ae2e87c4cd030f3 | 27.948718 | 92 | 0.77039 | 3.53605 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/notifications/v2/NotificationStateProvider.kt | 1 | 8143 | package org.thoughtcrime.securesms.notifications.v2
import androidx.annotation.WorkerThread
import org.signal.core.util.CursorUtil
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.database.MmsSmsColumns
import org.thoughtcrime.securesms.database.MmsSmsDatabase
import org.thoughtcrime.securesms.database.RecipientDatabase
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.database.model.MessageId
import org.thoughtcrime.securesms.database.model.MessageRecord
import org.thoughtcrime.securesms.database.model.ReactionRecord
import org.thoughtcrime.securesms.notifications.profiles.NotificationProfile
import org.thoughtcrime.securesms.recipients.Recipient
/**
* Queries the message databases to determine messages that should be in notifications.
*/
object NotificationStateProvider {
private val TAG = Log.tag(NotificationStateProvider::class.java)
@WorkerThread
fun constructNotificationState(stickyThreads: Map<ConversationId, MessageNotifierV2.StickyThread>, notificationProfile: NotificationProfile?): NotificationStateV2 {
val messages: MutableList<NotificationMessage> = mutableListOf()
SignalDatabase.mmsSms.getMessagesForNotificationState(stickyThreads.values).use { unreadMessages ->
if (unreadMessages.count == 0) {
return NotificationStateV2.EMPTY
}
MmsSmsDatabase.readerFor(unreadMessages).use { reader ->
var record: MessageRecord? = reader.next
while (record != null) {
val threadRecipient: Recipient? = SignalDatabase.threads.getRecipientForThreadId(record.threadId)
if (threadRecipient != null) {
val hasUnreadReactions = CursorUtil.requireInt(unreadMessages, MmsSmsColumns.REACTIONS_UNREAD) == 1
val conversationId = ConversationId.fromMessageRecord(record)
val parentRecord = conversationId.groupStoryId?.let {
SignalDatabase.mms.getMessageRecord(it)
}
val hasSelfRepliedToGroupStory = conversationId.groupStoryId?.let {
SignalDatabase.mms.hasSelfReplyInGroupStory(it)
}
messages += NotificationMessage(
messageRecord = record,
reactions = if (hasUnreadReactions) SignalDatabase.reactions.getReactions(MessageId(record.id, record.isMms)) else emptyList(),
threadRecipient = threadRecipient,
thread = conversationId,
stickyThread = stickyThreads.containsKey(conversationId),
isUnreadMessage = CursorUtil.requireInt(unreadMessages, MmsSmsColumns.READ) == 0,
hasUnreadReactions = hasUnreadReactions,
lastReactionRead = CursorUtil.requireLong(unreadMessages, MmsSmsColumns.REACTIONS_LAST_SEEN),
isParentStorySentBySelf = parentRecord?.isOutgoing ?: false,
hasSelfRepliedToStory = hasSelfRepliedToGroupStory ?: false
)
}
try {
record = reader.next
} catch (e: IllegalStateException) {
// XXX Weird SQLCipher bug that's being investigated
record = null
Log.w(TAG, "Failed to read next record!", e)
}
}
}
}
val conversations: MutableList<NotificationConversation> = mutableListOf()
val muteFilteredMessages: MutableList<NotificationStateV2.FilteredMessage> = mutableListOf()
val profileFilteredMessages: MutableList<NotificationStateV2.FilteredMessage> = mutableListOf()
messages.groupBy { it.thread }
.forEach { (thread, threadMessages) ->
var notificationItems: MutableList<NotificationItemV2> = mutableListOf()
for (notification: NotificationMessage in threadMessages) {
when (notification.includeMessage(notificationProfile)) {
MessageInclusion.INCLUDE -> notificationItems.add(MessageNotification(notification.threadRecipient, notification.messageRecord))
MessageInclusion.EXCLUDE -> Unit
MessageInclusion.MUTE_FILTERED -> muteFilteredMessages += NotificationStateV2.FilteredMessage(notification.messageRecord.id, notification.messageRecord.isMms)
MessageInclusion.PROFILE_FILTERED -> profileFilteredMessages += NotificationStateV2.FilteredMessage(notification.messageRecord.id, notification.messageRecord.isMms)
}
if (notification.hasUnreadReactions) {
notification.reactions.forEach {
when (notification.includeReaction(it, notificationProfile)) {
MessageInclusion.INCLUDE -> notificationItems.add(ReactionNotification(notification.threadRecipient, notification.messageRecord, it))
MessageInclusion.EXCLUDE -> Unit
MessageInclusion.MUTE_FILTERED -> muteFilteredMessages += NotificationStateV2.FilteredMessage(notification.messageRecord.id, notification.messageRecord.isMms)
MessageInclusion.PROFILE_FILTERED -> profileFilteredMessages += NotificationStateV2.FilteredMessage(notification.messageRecord.id, notification.messageRecord.isMms)
}
}
}
}
notificationItems.sort()
if (notificationItems.isNotEmpty() && stickyThreads.containsKey(thread) && !notificationItems.last().individualRecipient.isSelf) {
val indexOfOldestNonSelfMessage: Int = notificationItems.indexOfLast { it.individualRecipient.isSelf } + 1
notificationItems = notificationItems.slice(indexOfOldestNonSelfMessage..notificationItems.lastIndex).toMutableList()
}
if (notificationItems.isNotEmpty()) {
conversations += NotificationConversation(notificationItems[0].threadRecipient, thread, notificationItems)
}
}
return NotificationStateV2(conversations, muteFilteredMessages, profileFilteredMessages)
}
private data class NotificationMessage(
val messageRecord: MessageRecord,
val reactions: List<ReactionRecord>,
val threadRecipient: Recipient,
val thread: ConversationId,
val stickyThread: Boolean,
val isUnreadMessage: Boolean,
val hasUnreadReactions: Boolean,
val lastReactionRead: Long,
val isParentStorySentBySelf: Boolean,
val hasSelfRepliedToStory: Boolean
) {
private val isGroupStoryReply: Boolean = thread.groupStoryId != null
private val isUnreadIncoming: Boolean = isUnreadMessage && !messageRecord.isOutgoing && !isGroupStoryReply
private val isNotifiableGroupStoryMessage: Boolean = isUnreadMessage && !messageRecord.isOutgoing && isGroupStoryReply && (isParentStorySentBySelf || hasSelfRepliedToStory)
fun includeMessage(notificationProfile: NotificationProfile?): MessageInclusion {
return if (isUnreadIncoming || stickyThread || isNotifiableGroupStoryMessage) {
if (threadRecipient.isMuted && (threadRecipient.isDoNotNotifyMentions || !messageRecord.hasSelfMention())) {
MessageInclusion.MUTE_FILTERED
} else if (notificationProfile != null && !notificationProfile.isRecipientAllowed(threadRecipient.id) && !(notificationProfile.allowAllMentions && messageRecord.hasSelfMention())) {
MessageInclusion.PROFILE_FILTERED
} else {
MessageInclusion.INCLUDE
}
} else {
MessageInclusion.EXCLUDE
}
}
fun includeReaction(reaction: ReactionRecord, notificationProfile: NotificationProfile?): MessageInclusion {
return if (threadRecipient.isMuted) {
MessageInclusion.MUTE_FILTERED
} else if (notificationProfile != null && !notificationProfile.isRecipientAllowed(threadRecipient.id)) {
MessageInclusion.PROFILE_FILTERED
} else if (reaction.author != Recipient.self().id && messageRecord.isOutgoing && reaction.dateReceived > lastReactionRead) {
MessageInclusion.INCLUDE
} else {
MessageInclusion.EXCLUDE
}
}
private val Recipient.isDoNotNotifyMentions: Boolean
get() = mentionSetting == RecipientDatabase.MentionSetting.DO_NOT_NOTIFY
}
private enum class MessageInclusion {
INCLUDE,
EXCLUDE,
MUTE_FILTERED,
PROFILE_FILTERED
}
}
| gpl-3.0 | 2c6eba3fc0810e4285c45ff371442b1c | 48.054217 | 189 | 0.727373 | 5.53569 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/widgets/PopUpDisplay.kt | 1 | 1416 | package lt.markmerkk.widgets
import com.jfoenix.controls.JFXPopup
import com.jfoenix.svg.SVGGlyph
import javafx.scene.Node
import javafx.scene.Parent
import javafx.scene.layout.VBox
import lt.markmerkk.Styles
import lt.markmerkk.ui_2.views.jfxButton
import tornadofx.*
interface PopUpDisplay {
fun show()
/**
* Generates and shows popup with predefined actions
*/
fun createPopUpDisplay(
actions: List<PopUpAction>,
attachTo: Node
) {
val viewPopUp = JFXPopup()
val viewContainer = object : View() {
override val root: Parent = vbox(spacing = 4) {
style {
padding = box(4.px)
}
actions.forEach { popUpAction ->
jfxButton(popUpAction.title) {
addClass(Styles.popUpLabel)
graphic = popUpAction.graphic
action {
popUpAction.action.invoke()
viewPopUp.hide()
}
}
}
}
}
viewPopUp.popupContent = viewContainer.root as VBox
viewPopUp.show(attachTo, JFXPopup.PopupVPosition.BOTTOM, JFXPopup.PopupHPosition.LEFT)
}
}
class PopUpAction(
val title: String,
val graphic: SVGGlyph,
val action: () -> Unit
)
| apache-2.0 | 6f27ea323880899af3820e90467cf723 | 27.32 | 94 | 0.544492 | 4.704319 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/EPGDetails.kt | 1 | 3811 | /*
* Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.fragments
import android.app.Dialog
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.entities.IEPG
import org.dvbviewer.controller.ui.base.BaseDialogFragment
import org.dvbviewer.controller.utils.DateUtils
/**
* Fragment for EPG details or Timer details.
*/
class EPGDetails : BaseDialogFragment() {
/**
* Gets the epg.
*
* @return the epg
*/
var epg: IEPG? = null
internal set
private var channel: TextView? = null
private var date: TextView? = null
private var title: TextView? = null
private var subTitle: TextView? = null
private var desc: TextView? = null
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreate(android.os.Bundle)
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
epg = arguments!!.getParcelable(IEPG::class.java.simpleName)
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (epg != null) {
var dateString = DateUtils.getDateInLocalFormat(epg!!.start)
if (DateUtils.isToday(epg!!.start.time)) {
dateString = resources.getString(R.string.today)
} else if (DateUtils.isTomorrow(epg!!.start.time)) {
dateString = resources.getString(R.string.tomorrow)
}
val start = DateUtils.getTimeInLocalFormat(context, epg!!.start)
val end = DateUtils.getTimeInLocalFormat(context, epg!!.end)
date!!.text = "$dateString $start - $end"
channel!!.text = epg!!.channel
title!!.text = epg!!.title
if (TextUtils.isEmpty(epg!!.subTitle)) {
subTitle!!.visibility = View.GONE
} else {
subTitle!!.text = epg!!.subTitle
}
desc!!.text = epg!!.description
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.setTitle(R.string.details)
return dialog
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = activity!!.layoutInflater.inflate(R.layout.fragment_epg_details, container, false)
channel = v.findViewById<View>(R.id.channel) as TextView
date = v.findViewById<View>(R.id.date) as TextView
title = v.findViewById<View>(R.id.title) as TextView
subTitle = v.findViewById<View>(R.id.subTitle) as TextView
desc = v.findViewById<View>(R.id.desc) as TextView
return v
}
}
| apache-2.0 | 2d5a100101f7f74619d3682e9e0338af | 34.943396 | 125 | 0.673228 | 4.354286 | false | false | false | false |
DarrenAtherton49/droid-community-app | app/src/main/kotlin/com/darrenatherton/droidcommunity/features/subscriptiondrawer/SubscriptionDrawerPresenter.kt | 1 | 1104 | package com.darrenatherton.droidcommunity.features.subscriptiondrawer
import com.darrenatherton.droidcommunity.base.presentation.BasePresenter
import com.darrenatherton.droidcommunity.base.presentation.BaseView
import com.darrenatherton.droidcommunity.common.injection.scope.PerScreen
import javax.inject.Inject
@PerScreen
class SubscriptionDrawerPresenter @Inject constructor() : BasePresenter<SubscriptionDrawerPresenter.View>() {
//===================================================================================
// View attach/detach
//===================================================================================
override fun onViewAttached() {
loadSubscriptions()
}
override fun onViewDetached() {
}
//===================================================================================
// Domain actions to execute
//===================================================================================
private fun loadSubscriptions() {
// performDomainAction {
//
// }
}
interface View : BaseView {
}
} | mit | bf54d3ab6c878823e1976e9ea1d2615c | 29.694444 | 109 | 0.501812 | 7.122581 | false | false | false | false |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/main/java/com/doctoror/particleswallpaper/framework/opengl/KnownOpenglIssuesHandler.kt | 1 | 2940 | /*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.particleswallpaper.framework.opengl
import android.opengl.GLES20
import com.doctoror.particlesdrawable.opengl.GlException
import com.doctoror.particlesdrawable.opengl.chooser.NoMatchingConfigsException
import com.doctoror.particleswallpaper.framework.util.OpenGlEnabledStateChanger
import com.doctoror.particleswallpaper.userprefs.data.DeviceSettings
import io.reactivex.exceptions.OnErrorNotImplementedException
class KnownOpenglIssuesHandler(
private val deviceSettings: DeviceSettings,
private val openGlEnabledStateChanger: OpenGlEnabledStateChanger
) {
fun handleGlError(tag: String) {
val error = GLES20.glGetError()
if (error != GLES20.GL_NO_ERROR) {
// There are reports of GL_OUT_OF_MEMORY on glUseProgram for unknown reasons.
// Since there is not enough data to handle it, disable opengl support.
// https://bugs.chromium.org/p/webrtc/issues/detail?id=8154
// https://developer.samsung.com/forum/thread/bug-in-opengl-driver--samsung-opengl-shader-linking-with-out_of_memory-on-sm-g930fd/201/307111
if (error == GLES20.GL_OUT_OF_MEMORY) {
deviceSettings.openglSupported = false
openGlEnabledStateChanger.setOpenglGlEnabled(
openGlEnabled = false,
shouldKillApp = true
)
} else {
throw GlException(error, tag)
}
}
}
/**
* Handles the uncaught exception.
*
* @return true if handled and must not be propagated.
*/
fun handleUncaughtException(throwable: Throwable): Boolean = when (throwable) {
/*
* On some devices it is impossible to choose any config. Disable OpenGL in this case.
*/
is NoMatchingConfigsException -> {
deviceSettings.openglSupported = false
openGlEnabledStateChanger.setOpenglGlEnabled(
openGlEnabled = false,
shouldKillApp = true
)
true
}
is OnErrorNotImplementedException -> {
val cause = throwable.cause
if (cause != null) {
handleUncaughtException(cause)
} else {
false
}
}
else -> false
}
}
| apache-2.0 | 082741304b87248de2262576c4fe3e9b | 37.684211 | 152 | 0.656122 | 4.749596 | false | false | false | false |
iSoron/uhabits | uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/screens/habits/list/ListHabitsBehavior.kt | 1 | 5574 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.core.ui.screens.habits.list
import org.isoron.uhabits.core.commands.CommandRunner
import org.isoron.uhabits.core.commands.CreateRepetitionCommand
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.HabitList
import org.isoron.uhabits.core.models.HabitType
import org.isoron.uhabits.core.models.PaletteColor
import org.isoron.uhabits.core.models.Timestamp
import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.tasks.ExportCSVTask
import org.isoron.uhabits.core.tasks.TaskRunner
import org.isoron.uhabits.core.utils.DateUtils.Companion.getToday
import java.io.File
import java.io.IOException
import java.util.LinkedList
import javax.inject.Inject
import kotlin.math.roundToInt
open class ListHabitsBehavior @Inject constructor(
private val habitList: HabitList,
private val dirFinder: DirFinder,
private val taskRunner: TaskRunner,
private val screen: Screen,
private val commandRunner: CommandRunner,
private val prefs: Preferences,
private val bugReporter: BugReporter
) {
fun onClickHabit(h: Habit) {
screen.showHabitScreen(h)
}
fun onEdit(habit: Habit, timestamp: Timestamp?) {
val entry = habit.computedEntries.get(timestamp!!)
if (habit.type == HabitType.NUMERICAL) {
val oldValue = entry.value.toDouble() / 1000
screen.showNumberPopup(oldValue, entry.notes) { newValue: Double, newNotes: String ->
val value = (newValue * 1000).roundToInt()
commandRunner.run(CreateRepetitionCommand(habitList, habit, timestamp, value, newNotes))
}
} else {
screen.showCheckmarkPopup(
entry.value,
entry.notes,
habit.color,
) { newValue, newNotes ->
commandRunner.run(CreateRepetitionCommand(habitList, habit, timestamp, newValue, newNotes))
}
}
}
fun onExportCSV() {
val selected: MutableList<Habit> = LinkedList()
for (h in habitList) selected.add(h)
val outputDir = dirFinder.getCSVOutputDir()
taskRunner.execute(
ExportCSVTask(habitList, selected, outputDir) { filename: String? ->
if (filename != null) screen.showSendFileScreen(filename) else screen.showMessage(
Message.COULD_NOT_EXPORT
)
}
)
}
fun onFirstRun() {
prefs.isFirstRun = false
prefs.updateLastHint(-1, getToday())
screen.showIntroScreen()
}
fun onReorderHabit(from: Habit, to: Habit) {
taskRunner.execute { habitList.reorder(from, to) }
}
fun onRepairDB() {
taskRunner.execute {
habitList.repair()
screen.showMessage(Message.DATABASE_REPAIRED)
}
}
fun onSendBugReport() {
bugReporter.dumpBugReportToFile()
try {
val log = bugReporter.getBugReport()
screen.showSendBugReportToDeveloperScreen(log)
} catch (e: IOException) {
e.printStackTrace()
screen.showMessage(Message.COULD_NOT_GENERATE_BUG_REPORT)
}
}
fun onStartup() {
prefs.incrementLaunchCount()
if (prefs.isFirstRun) onFirstRun()
}
fun onToggle(habit: Habit, timestamp: Timestamp, value: Int, notes: String) {
commandRunner.run(
CreateRepetitionCommand(habitList, habit, timestamp, value, notes)
)
}
enum class Message {
COULD_NOT_EXPORT,
IMPORT_SUCCESSFUL,
IMPORT_FAILED,
DATABASE_REPAIRED,
COULD_NOT_GENERATE_BUG_REPORT,
FILE_NOT_RECOGNIZED,
}
interface BugReporter {
fun dumpBugReportToFile()
@Throws(IOException::class)
fun getBugReport(): String
}
interface DirFinder {
fun getCSVOutputDir(): File
}
fun interface NumberPickerCallback {
fun onNumberPicked(newValue: Double, notes: String)
fun onNumberPickerDismissed() {}
}
fun interface CheckMarkDialogCallback {
fun onNotesSaved(value: Int, notes: String)
fun onNotesDismissed() {}
}
interface Screen {
fun showHabitScreen(h: Habit)
fun showIntroScreen()
fun showMessage(m: Message)
fun showNumberPopup(
value: Double,
notes: String,
callback: NumberPickerCallback
)
fun showCheckmarkPopup(
selectedValue: Int,
notes: String,
color: PaletteColor,
callback: CheckMarkDialogCallback
)
fun showSendBugReportToDeveloperScreen(log: String)
fun showSendFileScreen(filename: String)
}
}
| gpl-3.0 | 3a3633d8dd8e3ee7cd12b4ff911355a9 | 31.782353 | 107 | 0.654764 | 4.564292 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/language/LanguagesListActivity.kt | 1 | 11651 | package org.wikipedia.language
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.TextView
import androidx.appcompat.view.ActionMode
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.apache.commons.lang3.StringUtils
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.BaseActivity
import org.wikipedia.analytics.AppLanguageSearchingFunnel
import org.wikipedia.databinding.ActivityLanguagesListBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.mwapi.SiteMatrix
import org.wikipedia.history.SearchActionModeCallback
import org.wikipedia.settings.languages.WikipediaLanguagesFragment
import org.wikipedia.util.DeviceUtil
import org.wikipedia.util.log.L
import java.util.*
class LanguagesListActivity : BaseActivity() {
private lateinit var binding: ActivityLanguagesListBinding
private lateinit var searchActionModeCallback: LanguageSearchCallback
private lateinit var searchingFunnel: AppLanguageSearchingFunnel
private var app = WikipediaApp.getInstance()
private var currentSearchQuery: String? = null
private var actionMode: ActionMode? = null
private var interactionsCount = 0
private var isLanguageSearched = false
private val disposables = CompositeDisposable()
private var siteInfoList: List<SiteMatrix.SiteInfo>? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLanguagesListBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.languagesListEmptyView.setEmptyText(R.string.langlinks_no_match)
binding.languagesListEmptyView.visibility = View.GONE
binding.languagesListRecycler.adapter = LanguagesListAdapter(app.language().appMruLanguageCodes, app.language().remainingAvailableLanguageCodes)
binding.languagesListRecycler.layoutManager = LinearLayoutManager(this)
binding.languagesListLoadProgress.visibility = View.VISIBLE
searchActionModeCallback = LanguageSearchCallback()
searchingFunnel = AppLanguageSearchingFunnel(intent.getStringExtra(WikipediaLanguagesFragment.SESSION_TOKEN).orEmpty())
requestLanguages()
}
public override fun onDestroy() {
disposables.clear()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_languages_list, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_search_language -> {
if (actionMode == null) {
actionMode = startSupportActionMode(searchActionModeCallback)
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onBackPressed() {
DeviceUtil.hideSoftKeyboard(this)
val returnIntent = Intent()
returnIntent.putExtra(LANGUAGE_SEARCHED, isLanguageSearched)
setResult(RESULT_OK, returnIntent)
searchingFunnel.logNoLanguageAdded(false, currentSearchQuery)
super.onBackPressed()
}
private inner class LanguageSearchCallback : SearchActionModeCallback() {
private val languageAdapter = binding.languagesListRecycler.adapter as LanguagesListAdapter
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
// currentSearchQuery is cleared here, instead of onDestroyActionMode
// in order to make the most recent search string available to analytics
currentSearchQuery = ""
isLanguageSearched = true
actionMode = mode
return super.onCreateActionMode(mode, menu)
}
override fun onQueryChange(s: String) {
currentSearchQuery = s.trim()
languageAdapter.setFilterText(currentSearchQuery)
if (binding.languagesListRecycler.adapter?.itemCount == 0) {
binding.languagesListEmptyView.visibility = View.VISIBLE
} else {
binding.languagesListEmptyView.visibility = View.GONE
}
}
override fun onDestroyActionMode(mode: ActionMode) {
super.onDestroyActionMode(mode)
binding.languagesListEmptyView.visibility = View.GONE
languageAdapter.reset()
actionMode = null
}
override fun getSearchHintString(): String {
return resources.getString(R.string.search_hint_search_languages)
}
override fun getParentContext(): Context {
return this@LanguagesListActivity
}
}
private inner class LanguagesListAdapter(languageCodes: List<String>, private val suggestedLanguageCodes: List<String>) : RecyclerView.Adapter<DefaultViewHolder>() {
private val originalLanguageCodes = languageCodes.toMutableList()
private val languageCodes = mutableListOf<String>()
private var isSearching = false
// To remove the already selected languages and suggested languages from all languages list
private val nonDuplicateLanguageCodesList
get() = originalLanguageCodes.toMutableList().apply {
removeAll(app.language().appLanguageCodes)
removeAll(suggestedLanguageCodes)
}
init {
reset()
}
override fun getItemViewType(position: Int): Int {
return if (shouldShowSectionHeader(position)) Companion.VIEW_TYPE_HEADER else Companion.VIEW_TYPE_ITEM
}
override fun getItemCount(): Int {
return languageCodes.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefaultViewHolder {
val inflater = LayoutInflater.from(parent.context)
return if (viewType == Companion.VIEW_TYPE_HEADER) {
val view = inflater.inflate(R.layout.view_section_header, parent, false)
DefaultViewHolder(languageCodes, view)
} else {
val view = inflater.inflate(R.layout.item_language_list_entry, parent, false)
LanguagesListItemHolder(languageCodes, view)
}
}
override fun onBindViewHolder(holder: DefaultViewHolder, pos: Int) {
holder.bindItem(pos)
(holder as? LanguagesListItemHolder)?.itemView?.setOnClickListener {
val lang = languageCodes[pos]
if (lang != app.appOrSystemLanguageCode) {
app.language().addAppLanguageCode(lang)
}
interactionsCount++
searchingFunnel.logLanguageAdded(true, lang, currentSearchQuery)
DeviceUtil.hideSoftKeyboard(this@LanguagesListActivity)
val returnIntent = Intent()
returnIntent.putExtra(WikipediaLanguagesFragment.ADD_LANGUAGE_INTERACTIONS, interactionsCount)
returnIntent.putExtra(LANGUAGE_SEARCHED, isLanguageSearched)
setResult(RESULT_OK, returnIntent)
finish()
}
}
fun shouldShowSectionHeader(position: Int): Boolean {
return !isSearching && (position == 0 || (suggestedLanguageCodes.isNotEmpty() &&
position == suggestedLanguageCodes.size + 1))
}
fun setFilterText(filterText: String?) {
isSearching = true
languageCodes.clear()
val filter = StringUtils.stripAccents(filterText).toLowerCase(Locale.getDefault())
for (code in originalLanguageCodes) {
val localizedName = StringUtils.stripAccents(app.language().getAppLanguageLocalizedName(code).orEmpty())
val canonicalName = StringUtils.stripAccents(getCanonicalName(code).orEmpty())
if (code.contains(filter) ||
localizedName.toLowerCase(Locale.getDefault()).contains(filter) ||
canonicalName.toLowerCase(Locale.getDefault()).contains(filter)) {
languageCodes.add(code)
}
}
notifyDataSetChanged()
}
fun reset() {
isSearching = false
languageCodes.clear()
if (suggestedLanguageCodes.isNotEmpty()) {
languageCodes.add(getString(R.string.languages_list_suggested_text))
languageCodes.addAll(suggestedLanguageCodes)
}
languageCodes.add(getString(R.string.languages_list_all_text))
languageCodes.addAll(nonDuplicateLanguageCodesList)
// should not be able to be searched while the languages are selected
originalLanguageCodes.removeAll(app.language().appLanguageCodes)
notifyDataSetChanged()
}
}
private fun getCanonicalName(code: String): String? {
var canonicalName = siteInfoList?.find { it.code() == code }?.localName()
if (canonicalName.isNullOrEmpty()) {
canonicalName = app.language().getAppLanguageCanonicalName(code)
}
return canonicalName
}
// TODO: optimize and reuse the header view holder?
private open inner class DefaultViewHolder constructor(private val languageCodes: List<String>, itemView: View) : RecyclerView.ViewHolder(itemView) {
open fun bindItem(position: Int) {
itemView.findViewById<TextView>(R.id.section_header_text).text = languageCodes[position]
}
}
private inner class LanguagesListItemHolder constructor(private val languageCodes: List<String>, itemView: View) : DefaultViewHolder(languageCodes, itemView) {
private val localizedNameTextView = itemView.findViewById<TextView>(R.id.localized_language_name)
private val canonicalNameTextView = itemView.findViewById<TextView>(R.id.language_subtitle)
override fun bindItem(position: Int) {
val languageCode = languageCodes[position]
localizedNameTextView.text = app.language().getAppLanguageLocalizedName(languageCode).orEmpty().capitalize(Locale.getDefault())
val canonicalName = getCanonicalName(languageCode)
if (binding.languagesListLoadProgress.visibility != View.VISIBLE) {
canonicalNameTextView.text = if (canonicalName.isNullOrEmpty()) app.language().getAppLanguageCanonicalName(languageCode) else canonicalName
}
}
}
private fun requestLanguages() {
disposables.add(ServiceFactory.get(app.wikiSite).siteMatrix
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map { siteMatrix -> SiteMatrix.getSites(siteMatrix) }
.doAfterTerminate {
binding.languagesListLoadProgress.visibility = View.INVISIBLE
binding.languagesListRecycler.adapter?.notifyDataSetChanged()
}
.subscribe({ sites -> siteInfoList = sites }) { t -> L.e(t) })
}
companion object {
private const val VIEW_TYPE_HEADER = 0
private const val VIEW_TYPE_ITEM = 1
const val LANGUAGE_SEARCHED = "language_searched"
}
}
| apache-2.0 | 6ca80d272b69d94b3b60ccde586fa314 | 43.639847 | 169 | 0.67462 | 5.6394 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SimplifyWhenWithBooleanConstantConditionInspection.kt | 1 | 3594 | // 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.inspections
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isFalseConstant
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.isTrueConstant
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
class SimplifyWhenWithBooleanConstantConditionInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return whenExpressionVisitor(fun(expression) {
if (expression.closeBrace == null) return
if (expression.subjectExpression != null) return
if (expression.entries.none { it.isTrueConstantCondition() || it.isFalseConstantCondition() }) return
holder.registerProblem(
expression.whenKeyword,
KotlinBundle.message("this.when.is.simplifiable"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
SimplifyWhenFix()
)
})
}
}
private class SimplifyWhenFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("simplify.when.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement.getStrictParentOfType<KtWhenExpression>() ?: return
val closeBrace = element.closeBrace ?: return
val factory = KtPsiFactory(project)
val usedAsExpression = element.isUsedAsExpression(element.analyze())
element.deleteFalseEntries(usedAsExpression)
element.replaceTrueEntry(usedAsExpression, closeBrace, factory)
}
}
private fun KtWhenExpression.deleteFalseEntries(usedAsExpression: Boolean) {
for (entry in entries) {
if (entry.isFalseConstantCondition()) {
entry.delete()
}
}
val entries = entries
if (entries.isEmpty() && !usedAsExpression) {
delete()
} else if (entries.singleOrNull()?.isElse == true) {
elseExpression?.let { replaceWithBranch(it, usedAsExpression) }
}
}
private fun KtWhenExpression.replaceTrueEntry(usedAsExpression: Boolean, closeBrace: PsiElement, factory: KtPsiFactory) {
val entries = entries
val trueIndex = entries.indexOfFirst { it.isTrueConstantCondition() }
if (trueIndex == -1) return
val expression = entries[trueIndex].expression ?: return
if (trueIndex == 0) {
replaceWithBranch(expression, usedAsExpression)
} else {
val elseEntry = factory.createWhenEntry("else -> ${expression.text}")
for (entry in entries.subList(trueIndex, entries.size)) {
entry.delete()
}
addBefore(elseEntry, closeBrace)
}
}
private fun KtWhenEntry.isTrueConstantCondition(): Boolean =
(conditions.singleOrNull() as? KtWhenConditionWithExpression)?.expression.isTrueConstant()
private fun KtWhenEntry.isFalseConstantCondition(): Boolean =
(conditions.singleOrNull() as? KtWhenConditionWithExpression)?.expression.isFalseConstant() | apache-2.0 | f297b75d77ea696cbcf8b6520bb8cca4 | 40.321839 | 132 | 0.729827 | 5.047753 | false | false | false | false |
jcsantosbr/suadeome-backendjvm | src/main/kotlin/com/jcs/suadeome/main/App.kt | 1 | 4916 | package com.jcs.suadeome.main
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.jcs.suadeome.context.RouteFactory
import com.jcs.suadeome.professionals.Professional
import com.jcs.suadeome.professionals.ProfessionalJsonSerializer
import com.jcs.suadeome.professionals.ProfessionalResource
import com.jcs.suadeome.services.Service
import com.jcs.suadeome.services.ServiceResource
import com.jcs.suadeome.types.EntityConstructionFailed
import org.flywaydb.core.Flyway
import org.postgresql.ds.PGPoolingDataSource
import org.skife.jdbi.v2.DBI
import spark.Filter
import spark.ResponseTransformer
import spark.Route
import spark.Spark
import spark.Spark.*
import java.lang.Integer.parseInt
import java.util.Optional.ofNullable
import java.util.logging.Logger
object App {
private val logger: Logger = Logger.getLogger(this.javaClass.name)
val toJson : ResponseTransformer = ResponseTransformer { model: Any -> createGson().toJson(model) }
private fun createGson(): Gson {
val builder = GsonBuilder()
builder.registerTypeAdapter(Professional::class.java, ProfessionalJsonSerializer())
builder.registerTypeAdapter(Service::class.java, Service.ServiceJsonSerializer())
return builder.create()
}
@JvmStatic fun main(args: Array<String>) {
upgradeDB()
configureSpark()
val dbi = configureDB()
defineRoutes(dbi)
}
private fun upgradeDB() {
val flyway = Flyway()
flyway.setDataSource(DbConfig.url(), DbConfig.username(), DbConfig.password())
flyway.migrate()
}
private fun configureSpark() {
val ipAddress = getEnv("OPENSHIFT_DIY_IP", "localhost")
val port = getIntEnv("OPENSHIFT_DIY_PORT", 4567)
Spark.ipAddress(ipAddress)
Spark.port(port)
Spark.threadPool(14);
}
private fun defineRoutes(dbi: DBI) {
val routeFactory = RouteFactory(dbi)
enableCors()
get("/", Route { request, response ->
//TODO: list of endpoints, needs to learn how to fetch from Spark
listOf("professionals", "services")
}, toJson)
ProfessionalResource.routesForProfessionals(routeFactory)
ServiceResource.routesForResource(routeFactory)
exception(EntityConstructionFailed::class.java, { exception, request, response ->
response.status(400)
response.body(exception.message)
})
exception(Exception::class.java, { exception, request, response ->
response.status(500)
response.body("Something bad happened! Sorry")
exception.printStackTrace()
logger.severe { exception.message }
})
}
private fun enableCors() {
options("/*", { request, response ->
val accessControlRequestHeaders = request.headers("Access-Control-Request-Headers")
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}
val accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if (accessControlRequestMethod != null) {
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
response;
})
before(Filter { request, response ->
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Request-Method", "POST");
response.header("Access-Control-Request-Method", "GET");
response.header("Access-Control-Request-Method", "OPTIONS");
response.type("application/json");
})
}
private fun configureDB(): DBI {
val connectionPool = PGPoolingDataSource()
connectionPool.applicationName = "suadeome"
connectionPool.url = DbConfig.url()
connectionPool.user = DbConfig.username()
connectionPool.password = DbConfig.password()
connectionPool.maxConnections = 10
return DBI(connectionPool)
}
private fun getIntEnv(property: String, defaultValue: Int): Int {
return parseInt(ofNullable(System.getenv(property)).orElse(Integer.toString(defaultValue)))
}
private fun getEnv(property: String, defaultValue: String): String {
return ofNullable(System.getenv(property)).orElse(defaultValue)
}
object DbConfig {
fun url(): String {
val host = getEnv("OPENSHIFT_POSTGRESQL_DB_HOST", "localhost")
val port = getEnv("OPENSHIFT_POSTGRESQL_DB_PORT", "5432")
return "jdbc:postgresql://$host:$port/suadeome"
}
fun username(): String = getEnv("OPENSHIFT_POSTGRESQL_DB_APP_USER", "suadeome")
fun password(): String = getEnv("OPENSHIFT_POSTGRESQL_DB_APP_PASSWORD", "suadeome")
}
}
| mit | c680b7dd047751237b40a77b9563148e | 31.773333 | 103 | 0.667209 | 4.713327 | false | true | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/workers/AttachmentFilesWriter.kt | 1 | 19998 | package co.smartreceipts.android.workers
import android.content.Context
import android.graphics.*
import android.graphics.Bitmap.CompressFormat
import android.graphics.Paint.Align
import co.smartreceipts.analytics.log.Logger
import co.smartreceipts.android.R
import co.smartreceipts.android.date.DateFormatter
import co.smartreceipts.android.filters.LegacyReceiptFilter
import co.smartreceipts.android.model.*
import co.smartreceipts.android.model.comparators.ReceiptDateComparator
import co.smartreceipts.android.model.converters.DistanceToReceiptsConverter
import co.smartreceipts.android.model.factory.PriceBuilderFactory
import co.smartreceipts.android.model.impl.columns.categories.CategoryColumnDefinitions
import co.smartreceipts.android.model.impl.columns.distance.DistanceColumnDefinitions
import co.smartreceipts.android.persistence.DatabaseHelper
import co.smartreceipts.android.persistence.database.controllers.grouping.GroupingController
import co.smartreceipts.android.purchases.wallet.PurchaseWallet
import co.smartreceipts.android.settings.UserPreferenceManager
import co.smartreceipts.android.settings.catalog.UserPreference
import co.smartreceipts.android.workers.EmailAssistant.EmailOptions
import co.smartreceipts.android.workers.reports.Report
import co.smartreceipts.android.workers.reports.ReportGenerationException
import co.smartreceipts.android.workers.reports.ReportResourcesManager
import co.smartreceipts.android.workers.reports.csv.CsvReportWriter
import co.smartreceipts.android.workers.reports.csv.CsvTableGenerator
import co.smartreceipts.android.workers.reports.pdf.PdfBoxFullPdfReport
import co.smartreceipts.android.workers.reports.pdf.PdfBoxImagesOnlyReport
import co.smartreceipts.android.workers.reports.pdf.misc.TooManyColumnsException
import co.smartreceipts.core.di.scopes.ApplicationScope
import wb.android.storage.StorageManager
import java.io.File
import java.io.IOException
import java.util.*
import javax.inject.Inject
@ApplicationScope
class AttachmentFilesWriter @Inject constructor(
private val context: Context,
private val databaseHelper: DatabaseHelper,
private val preferenceManager: UserPreferenceManager,
private val storageManager: StorageManager,
private val reportResourcesManager: ReportResourcesManager,
private val purchaseWallet: PurchaseWallet,
private val dateFormatter: DateFormatter
) {
companion object {
private const val IMG_SCALE_FACTOR = 2.1f
private const val HW_RATIO = 0.75f
}
class WriterResults {
var didPDFFailCompletely = false
var didPDFFailTooManyColumns = false
var didCSVFailCompletely = false
var didZIPFailCompletely = false
var didMemoryErrorOccure = false
val files: Array<File?> = arrayOfNulls(EmailOptions.values().size)
}
fun write(trip: Trip, receiptsList: List<Receipt>, distancesList: List<Distance>, options: EnumSet<EmailOptions>): WriterResults {
Logger.info(this, "Generating the following report types {}.", options)
val results = WriterResults()
// Make our trip output directory exists in a good state
var dir = trip.directory
if (!dir.exists()) {
dir = storageManager.getFile(trip.name)
if (!dir.exists()) {
dir = storageManager.mkdir(trip.name)
}
}
if (options.contains(EmailOptions.PDF_FULL)) {
generateFullPdf(trip, results)
}
if (options.contains(EmailOptions.PDF_IMAGES_ONLY) && receiptsList.isNotEmpty()) {
generateImagesPdf(trip, results)
}
if (options.contains(EmailOptions.ZIP) && receiptsList.isNotEmpty()) {
generateZip(trip, receiptsList, dir, results)
}
val csvColumns by lazy { databaseHelper.csvTable.get().blockingGet() }
if (options.contains(EmailOptions.CSV)) {
generateCsv(trip, receiptsList, distancesList, csvColumns, dir, results)
}
if (options.contains(EmailOptions.ZIP_WITH_METADATA) && receiptsList.isNotEmpty()) {
generateZipWithMetadata(trip, receiptsList, csvColumns, dir, options.contains(EmailOptions.ZIP), results)
}
return results
}
private fun generateFullPdf(trip: Trip, results: WriterResults) {
val pdfFullReport: Report =
PdfBoxFullPdfReport(reportResourcesManager, databaseHelper, preferenceManager, storageManager, purchaseWallet, dateFormatter)
try {
results.files[EmailOptions.PDF_FULL.index] = pdfFullReport.generate(trip)
} catch (e: ReportGenerationException) {
if (e.cause is TooManyColumnsException) {
results.didPDFFailTooManyColumns = true
}
results.didPDFFailCompletely = true
}
}
private fun generateImagesPdf(trip: Trip, results: WriterResults) {
val pdfImagesReport: Report =
PdfBoxImagesOnlyReport(reportResourcesManager, databaseHelper, preferenceManager, storageManager, dateFormatter)
try {
results.files[EmailOptions.PDF_IMAGES_ONLY.index] = pdfImagesReport.generate(trip)
} catch (e: ReportGenerationException) {
results.didPDFFailCompletely = true
}
}
private fun generateCsv(
trip: Trip, receiptsList: List<Receipt>, distancesList: List<Distance>, csvColumns: List<Column<Receipt>>, dir: File,
results: WriterResults
) {
val printFooters: Boolean = preferenceManager.get(UserPreference.ReportOutput.ShowTotalOnCSV)
try {
storageManager.delete(dir, dir.name + ".csv")
val csvTableGenerator =
CsvTableGenerator(reportResourcesManager, csvColumns, true, printFooters, LegacyReceiptFilter(preferenceManager))
val receipts: MutableList<Receipt> = ArrayList(receiptsList)
val distances: MutableList<Distance> = ArrayList(distancesList)
// Receipts table
if (preferenceManager.get(UserPreference.Distance.PrintDistanceAsDailyReceiptInReports)) {
receipts.addAll(DistanceToReceiptsConverter(context, dateFormatter).convert(distances))
Collections.sort(receipts, ReceiptDateComparator())
}
var data = csvTableGenerator.generate(receipts)
// Distance table
if (preferenceManager.get(UserPreference.Distance.PrintDistanceTableInReports)) {
if (distances.isNotEmpty()) {
distances.reverse() // Reverse the list, so we print the most recent one first
// CSVs cannot print special characters
val distanceColumnDefinitions: ColumnDefinitions<Distance> =
DistanceColumnDefinitions(reportResourcesManager, preferenceManager, dateFormatter, true)
val distanceColumns = distanceColumnDefinitions.allColumns
data += "\n\n"
data += CsvTableGenerator(
reportResourcesManager, distanceColumns,
true, printFooters
).generate(distances)
}
}
// Categorical summation table
if (preferenceManager.get(UserPreference.PlusSubscription.CategoricalSummationInReports)) {
val sumCategoryGroupingResults = GroupingController(databaseHelper, context, preferenceManager)
.getSummationByCategory(trip)
.toList()
.blockingGet()
var isMultiCurrency = false
for (sumCategoryGroupingResult in sumCategoryGroupingResults) {
if (sumCategoryGroupingResult.isMultiCurrency) {
isMultiCurrency = true
break
}
}
val taxEnabled: Boolean = preferenceManager.get(UserPreference.Receipts.IncludeTaxField)
val categoryColumns = CategoryColumnDefinitions(reportResourcesManager, isMultiCurrency, taxEnabled)
.allColumns
data += "\n\n"
data += CsvTableGenerator(
reportResourcesManager, categoryColumns,
true, printFooters
).generate(sumCategoryGroupingResults)
}
// Separated tables for each category
if (preferenceManager.get(UserPreference.PlusSubscription.SeparateByCategoryInReports)) {
val groupingResults = GroupingController(databaseHelper, context, preferenceManager)
.getReceiptsGroupedByCategory(trip)
.toList()
.blockingGet()
for (groupingResult in groupingResults) {
data += "\n\n" + groupingResult.category.name + "\n";
data += CsvTableGenerator(reportResourcesManager, csvColumns, true, printFooters).generate(groupingResult.receipts)
}
}
val csvFile = File(dir, dir.name + ".csv")
results.files[EmailOptions.CSV.index] = csvFile
CsvReportWriter(csvFile).write(data)
} catch (e: IOException) {
Logger.error(this, "Failed to write the csv file", e)
results.didCSVFailCompletely = true;
}
}
private fun generateZip(trip: Trip, receiptsList: List<Receipt>, directory: File, results: WriterResults) {
var dir = directory
storageManager.delete(dir, dir.name + ".zip")
dir = storageManager.mkdir(trip.directory, trip.name)
for (i in receiptsList.indices) {
val receipt = receiptsList[i]
if (!filterOutReceipt(preferenceManager, receipt) && receipt.file != null && receipt.file.exists()) {
val data = storageManager.read(receipt.file)
if (data != null) storageManager.write(dir, receipt.file.name, data)
}
}
val zip: File = storageManager.zipBuffered(dir, 2048)
storageManager.deleteRecursively(dir)
results.files[EmailOptions.ZIP.index] = zip
}
private fun generateZipWithMetadata(
trip: Trip, receiptsList: List<Receipt>, csvColumns: List<Column<Receipt>>,
dir: File, isZipGenerationIncluded: Boolean, results: WriterResults
) {
val zipDir = if (isZipGenerationIncluded) {
storageManager.delete(dir, dir.name + "_stamped" + ".zip")
storageManager.mkdir(trip.directory, trip.name + "_stamped")
} else {
storageManager.delete(dir, dir.name + ".zip")
storageManager.mkdir(trip.directory, trip.name)
}
for (i in receiptsList.indices) {
val receipt = receiptsList[i]
if (!filterOutReceipt(preferenceManager, receipt)) {
if (receipt.hasImage()) {
val userCommentBuilder = StringBuilder()
for (col in csvColumns) {
userCommentBuilder.append(reportResourcesManager.getFlexString(col.headerStringResId))
userCommentBuilder.append(": ")
userCommentBuilder.append(col.getValue(receipt))
userCommentBuilder.append("\n")
}
val userComment = userCommentBuilder.toString()
try {
val b: Bitmap? = stampImage(trip, receipt, Bitmap.Config.ARGB_8888)
if (b != null) {
storageManager.writeBitmap(zipDir, b, receipt.file!!.name, CompressFormat.JPEG, 85, userComment)
b.recycle()
}
} catch (e: OutOfMemoryError) {
Logger.error(this, "Trying to recover from OOM", e)
System.gc()
try {
val b: Bitmap? = stampImage(trip, receipt, Bitmap.Config.RGB_565)
if (b != null) {
storageManager.writeBitmap(zipDir, b, receipt.file!!.name, CompressFormat.JPEG, 85, userComment)
b.recycle()
}
} catch (e2: OutOfMemoryError) {
Logger.error(this, "Failed to recover from OOM", e2)
results.didZIPFailCompletely = true
results.didMemoryErrorOccure = true
break
}
}
} else if (receipt.hasPDF()) {
val data = storageManager.read(receipt.file)
if (data != null) storageManager.write(zipDir, receipt.file!!.name, data)
}
}
}
val zipWithMetadata: File = storageManager.zipBuffered(zipDir, 2048)
storageManager.deleteRecursively(zipDir)
results.files[EmailOptions.ZIP_WITH_METADATA.index] = zipWithMetadata
}
/**
* Applies a particular filter to determine whether or not this receipt should be
* generated for this report
*
* @param preferences - User preferences
* @param receipt - The particular receipt
* @return true if if should be filtered out, false otherwise
*/
private fun filterOutReceipt(preferences: UserPreferenceManager, receipt: Receipt): Boolean {
return if (preferences.get(UserPreference.Receipts.OnlyIncludeReimbursable) && !receipt.isReimbursable) {
true
} else receipt.price.priceAsFloat < preferences.get(UserPreference.Receipts.MinimumReceiptPrice)
}
private fun stampImage(trip: Trip, receipt: Receipt, config: Bitmap.Config): Bitmap? {
if (!receipt.hasImage()) {
return null
}
var foreground: Bitmap? = storageManager.getMutableMemoryEfficientBitmap(receipt.file)
return if (foreground != null) { // It can be null if file not found
// Size the image
var foreWidth = foreground.width
var foreHeight = foreground.height
if (foreHeight > foreWidth) {
foreWidth = (foreHeight * HW_RATIO).toInt()
} else {
foreHeight = (foreWidth / HW_RATIO).toInt()
}
// Set up the padding
val xPad = (foreWidth / IMG_SCALE_FACTOR).toInt()
val yPad = (foreHeight / IMG_SCALE_FACTOR).toInt()
// Set up an all white background for our canvas
val background = Bitmap.createBitmap(foreWidth + xPad, foreHeight + yPad, config)
val canvas = Canvas(background)
canvas.drawARGB(0xFF, 0xFF, 0xFF, 0xFF) //This represents White color
// Set up the paint
val dither = Paint()
dither.isDither = true
dither.isFilterBitmap = false
canvas.drawBitmap(
foreground,
(background.width - foreground.width) / 2.toFloat(),
(background.height - foreground.height) / 2.toFloat(),
dither
)
val brush = Paint()
brush.isAntiAlias = true
brush.typeface = Typeface.SANS_SERIF
brush.color = Color.BLACK
brush.style = Paint.Style.FILL
brush.textAlign = Align.LEFT
// Set up the number of items to draw
var num = 5
if (preferenceManager.get(UserPreference.Receipts.IncludeTaxField)) {
num++
}
if (receipt.hasExtraEditText1()) {
num++
}
if (receipt.hasExtraEditText2()) {
num++
}
if (receipt.hasExtraEditText3()) {
num++
}
val spacing: Float = getOptimalSpacing(num, yPad / 2, brush)
var y = spacing * 4
canvas.drawText(trip.name, xPad / 2.toFloat(), y, brush)
y += spacing
canvas.drawText(
dateFormatter.getFormattedDate(trip.startDisplayableDate) + " -- " + dateFormatter.getFormattedDate(trip.endDisplayableDate),
xPad / 2.toFloat(),
y,
brush
)
y = background.height - yPad / 2 + spacing * 2
canvas.drawText(
reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_NAME) + ": " + receipt.name,
xPad / 2.toFloat(),
y,
brush
)
y += spacing
canvas.drawText(
reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_PRICE) + ": " + receipt.price.decimalFormattedPrice + " " + receipt.price.currencyCode,
xPad / 2.toFloat(),
y,
brush
)
y += spacing
if (preferenceManager.get(UserPreference.Receipts.IncludeTaxField)) {
val totalTax = PriceBuilderFactory(receipt.tax).setPrice(receipt.tax.price.add(receipt.tax2.price)).build()
canvas.drawText(
reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_TAX) + ": " + totalTax.decimalFormattedPrice + " " + receipt.price.currencyCode,
xPad / 2.toFloat(),
y,
brush
)
y += spacing
}
canvas.drawText(
reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_DATE) + ": " + dateFormatter.getFormattedDate(
receipt.date,
receipt.timeZone
), xPad / 2.toFloat(), y, brush
)
y += spacing
canvas.drawText(
reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_CATEGORY) + ": " + receipt.category.name,
xPad / 2.toFloat(),
y,
brush
)
y += spacing
canvas.drawText(
reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_COMMENT) + ": " + receipt.comment,
xPad / 2.toFloat(),
y,
brush
)
y += spacing
if (receipt.hasExtraEditText1()) {
canvas.drawText(
reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_EXTRA_EDITTEXT_1) + ": " + receipt.extraEditText1,
xPad / 2.toFloat(),
y,
brush
)
y += spacing
}
if (receipt.hasExtraEditText2()) {
canvas.drawText(
reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_EXTRA_EDITTEXT_2) + ": " + receipt.extraEditText2,
xPad / 2.toFloat(),
y,
brush
)
y += spacing
}
if (receipt.hasExtraEditText3()) {
canvas.drawText(
reportResourcesManager.getFlexString(R.string.RECEIPTMENU_FIELD_EXTRA_EDITTEXT_3) + ": " + receipt.extraEditText3,
xPad / 2.toFloat(),
y,
brush
)
}
// Clear out the dead data here
foreground.recycle()
// And return
background
} else {
null
}
}
private fun getOptimalSpacing(count: Int, space: Int, brush: Paint): Float {
var fontSize = 8f //Seed
brush.textSize = fontSize
while (space > (count + 2) * brush.fontSpacing) {
brush.textSize = ++fontSize
}
brush.textSize = --fontSize
return brush.fontSpacing
}
} | agpl-3.0 | e1930b91fffd723f27f171f106667892 | 42.857456 | 167 | 0.59611 | 5.257098 | false | false | false | false |
elpassion/mainframer-intellij-plugin | src/main/kotlin/com/elpassion/mainframerplugin/util/ui.kt | 1 | 1460 | package com.elpassion.mainframerplugin.util
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.wm.WindowManager
import com.intellij.ui.awt.RelativePoint
import javax.swing.SwingUtilities
import javax.swing.event.HyperlinkEvent
fun showInfo(project: Project, message: String, hyperlinkListener: ((HyperlinkEvent) -> Unit)? = null) {
showBalloon(project, message, MessageType.INFO, hyperlinkListener)
}
fun showError(project: Project, message: String, hyperlinkListener: ((HyperlinkEvent) -> Unit)? = null) {
showBalloon(project, message, MessageType.ERROR, hyperlinkListener)
}
private fun showBalloon(project: Project, message: String, messageType: MessageType,
hyperlinkListener: ((HyperlinkEvent) -> Unit)?) = invokeOnUi {
val statusBar = WindowManager.getInstance().getStatusBar(project)
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(message, messageType, hyperlinkListener)
.setFadeoutTime(5000)
.createBalloon()
.show(RelativePoint.getCenterOf(statusBar.component), Balloon.Position.above)
}
private fun invokeOnUi(action: () -> Unit) =
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeAndWait(action)
} else {
action()
} | apache-2.0 | 499c1152d449db8864d0fbd929145256 | 40.742857 | 105 | 0.733562 | 4.771242 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/util/reference/PackageNameReferenceProvider.kt | 1 | 6071 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util.reference
import com.demonwav.mcdev.util.manipulator
import com.demonwav.mcdev.util.packageName
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.util.TextRange
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult
import com.intellij.psi.PsiPackage
import com.intellij.psi.PsiQualifiedNamedElement
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiReferenceProvider
import com.intellij.psi.ResolveResult
import com.intellij.util.IncorrectOperationException
import com.intellij.util.PlatformIcons
import com.intellij.util.ProcessingContext
abstract class PackageNameReferenceProvider : PsiReferenceProvider() {
protected open val description
get() = "package '%s'"
protected open fun getBasePackage(element: PsiElement): String? = null
protected open fun canBindTo(element: PsiElement) = element is PsiPackage
protected open fun resolve(
qualifiedName: String,
element: PsiElement,
facade: JavaPsiFacade
): Array<ResolveResult> {
facade.findPackage(qualifiedName)?.let { return arrayOf(PsiElementResolveResult(it)) }
return ResolveResult.EMPTY_ARRAY
}
protected abstract fun collectVariants(element: PsiElement, context: PsiElement?): Array<Any>
protected fun collectSubpackages(context: PsiPackage, classes: Iterable<PsiClass>): Array<Any> {
return collectPackageChildren(context, classes) {}
}
protected inline fun collectPackageChildren(
context: PsiPackage,
classes: Iterable<PsiClass>,
classFunc: (PsiClass) -> Any?
): Array<Any> {
val parentPackage = context.qualifiedName
val subPackageStart = parentPackage.length + 1
val packages = HashSet<String>()
val list = ArrayList<Any>()
for (psiClass in classes) {
val packageName = psiClass.packageName ?: continue
if (!packageName.startsWith(parentPackage)) {
continue
}
if (packageName.length < subPackageStart) {
classFunc(psiClass)?.let { list.add(it) }
continue
}
val end = packageName.indexOf('.', subPackageStart)
val nextName =
if (end == -1) packageName.substring(subPackageStart) else packageName.substring(subPackageStart, end)
if (packages.add(nextName)) {
list.add(LookupElementBuilder.create(nextName).withIcon(PlatformIcons.PACKAGE_ICON))
}
}
return list.toArray()
}
fun resolve(element: PsiElement): PsiElement? {
val range = element.manipulator!!.getRangeInElement(element)
return Reference(element, range, range.startOffset, null).multiResolve(false).firstOrNull()?.element
}
final override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
val baseRange = element.manipulator!!.getRangeInElement(element)
val text = element.text!!
val start = baseRange.startOffset
val end = baseRange.endOffset
var pos = start
var current: Reference? = null
val list = ArrayList<PsiReference>()
while (true) {
val separatorPos = text.indexOf('.', pos)
if (separatorPos == -1) {
list.add(Reference(element, TextRange(pos, end), start, current))
break
}
if (separatorPos >= end) {
break
}
current = Reference(element, TextRange(pos, separatorPos), start, current)
list.add(current)
pos = separatorPos + 1
if (pos == end) {
list.add(Reference(element, TextRange(end, end), start, current))
break
}
}
return list.toTypedArray()
}
private inner class Reference(element: PsiElement, range: TextRange, start: Int, val previous: Reference?) :
PsiReferenceBase.Poly<PsiElement>(element, range, false), InspectionReference {
override val description: String
get() = [email protected]
private val qualifiedRange = TextRange(start, range.endOffset)
private val qualifiedName: String
get() {
val name = qualifiedRange.substring(element.text)
return getBasePackage(element)?.let { it + '.' + name } ?: name
}
override val unresolved: Boolean
get() = multiResolve(false).isEmpty()
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
return resolve(qualifiedName, element, JavaPsiFacade.getInstance(element.project))
}
override fun getVariants(): Array<Any> {
return collectVariants(element, previous?.multiResolve(false)?.firstOrNull()?.element)
}
private fun getNewName(newTarget: PsiQualifiedNamedElement): String {
val newName = newTarget.qualifiedName!!
return getBasePackage(element)?.let { newName.removePrefix(it + '.') } ?: newName
}
override fun bindToElement(newTarget: PsiElement): PsiElement? {
if (!canBindTo(newTarget)) {
throw IncorrectOperationException("Cannot bind to $newTarget")
}
if (super.isReferenceTo(newTarget)) {
return element
}
val newName = getNewName(newTarget as PsiQualifiedNamedElement)
return element.manipulator?.handleContentChange(element, qualifiedRange, newName)
}
override fun isReferenceTo(element: PsiElement) = canBindTo(element) && super.isReferenceTo(element)
}
}
| mit | 2d06c53b6100e461bf8f13a71b2cf9f9 | 33.890805 | 118 | 0.652775 | 5.149279 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/translations/TranslationConstants.kt | 1 | 841 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations
object TranslationConstants {
const val DEFAULT_LOCALE = "en_us"
const val I18N_CLIENT_CLASS = "net.minecraft.client.resources.I18n"
const val I18N_COMMON_CLASS = "net.minecraft.util.text.translation.I18n"
const val CONSTRUCTOR = "<init>"
const val TRANSLATION_COMPONENT_CLASS = "net.minecraft.util.text.TextComponentTranslation"
const val COMMAND_EXCEPTION_CLASS = "net.minecraft.command.CommandException"
const val FORMAT = "func_135052_a"
const val TRANSLATE_TO_LOCAL = "func_74838_a"
const val TRANSLATE_TO_LOCAL_FORMATTED = "func_74837_a"
const val SET_BLOCK_NAME = "func_149663_c"
const val SET_ITEM_NAME = "func_77655_b"
}
| mit | a02d4b576363f3b0d8983b08951af528 | 32.64 | 94 | 0.717004 | 3.391129 | false | false | false | false |
paplorinc/intellij-community | python/src/com/jetbrains/python/testing/PyTestsShared.kt | 2 | 34039 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.testing
import com.intellij.execution.ExecutionException
import com.intellij.execution.Location
import com.intellij.execution.PsiLocation
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.execution.configurations.*
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.testframework.AbstractTestProxy
import com.intellij.execution.testframework.sm.runner.SMTestLocator
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.JDOMExternalizerUtil.readField
import com.intellij.openapi.util.JDOMExternalizerUtil.writeField
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.QualifiedName
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.remote.PathMappingProvider
import com.intellij.remote.RemoteSdkAdditionalData
import com.intellij.util.ThreeState
import com.jetbrains.extensions.*
import com.jetbrains.extenstions.ModuleBasedContextAnchor
import com.jetbrains.extenstions.QNameResolveContext
import com.jetbrains.extenstions.getElementAndResolvableName
import com.jetbrains.extenstions.resolveToElement
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PyNames
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyFunction
import com.jetbrains.python.psi.PyQualifiedNameOwner
import com.jetbrains.python.psi.types.TypeEvalContext
import com.jetbrains.python.run.*
import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant
import com.jetbrains.python.run.targetBasedConfiguration.TargetWithVariant
import com.jetbrains.python.run.targetBasedConfiguration.createRefactoringListenerIfPossible
import com.jetbrains.python.run.targetBasedConfiguration.targetAsPsiElement
import com.jetbrains.python.sdk.PySdkUtil
import com.jetbrains.reflection.DelegationProperty
import com.jetbrains.reflection.Properties
import com.jetbrains.reflection.Property
import com.jetbrains.reflection.getProperties
import jetbrains.buildServer.messages.serviceMessages.ServiceMessage
import jetbrains.buildServer.messages.serviceMessages.TestStdErr
import jetbrains.buildServer.messages.serviceMessages.TestStdOut
import java.util.regex.Matcher
/**
* New configuration factories
*/
internal val pythonFactories: Array<PythonConfigurationFactoryBase> = arrayOf(
PyUnitTestFactory,
PyTestFactory,
PyNoseTestFactory,
PyTrialTestFactory)
/**
* Accepts text that may be wrapped in TC message. Unwarps it and removes TC escape code.
* Regular text is unchanged
*/
fun processTCMessage(text: String): String {
val parsedMessage = ServiceMessage.parse(text.trim()) ?: return text // Not a TC message
return when (parsedMessage) {
is TestStdOut -> parsedMessage.stdOut // TC with stdout
is TestStdErr -> parsedMessage.stdErr // TC with stderr
else -> "" // TC with out of any output
}
}
internal fun getAdditionalArgumentsPropertyName() = com.jetbrains.python.testing.PyAbstractTestConfiguration::additionalArguments.name
/**
* If runner name is here that means test runner only can run inheritors for TestCase
*/
val RunnersThatRequireTestCaseClass: Set<String> = setOf<String>(PythonTestConfigurationsModel.PYTHONS_UNITTEST_NAME,
PyTestFrameworkService.getSdkReadableNameByFramework(PyNames.TRIAL_TEST))
/**
* Checks if element could be test target
* @param testCaseClassRequired see [PythonUnitTestUtil] docs
*/
fun isTestElement(element: PsiElement, testCaseClassRequired: ThreeState, typeEvalContext: TypeEvalContext): Boolean = when (element) {
is PyFile -> PythonUnitTestUtil.isTestFile(element, testCaseClassRequired, typeEvalContext)
is com.intellij.psi.PsiDirectory -> element.name.contains("test", true) || element.children.any {
it is PyFile && PythonUnitTestUtil.isTestFile(it, testCaseClassRequired, typeEvalContext)
}
is PyFunction -> PythonUnitTestUtil.isTestFunction(element,
testCaseClassRequired, typeEvalContext)
is com.jetbrains.python.psi.PyClass -> {
PythonUnitTestUtil.isTestClass(element, testCaseClassRequired, typeEvalContext)
}
else -> false
}
/**
* Since runners report names of tests as qualified name, no need to convert it to PSI and back to string.
* We just save its name and provide it again to rerun
* @param metainfo additional info provided by test runner, in case of pytest it is test name that could be used as "-k" argument
*/
private class PyTargetBasedPsiLocation(val target: ConfigurationTarget,
element: PsiElement,
val metainfo: String?) : PsiLocation<PsiElement>(element) {
override fun equals(other: Any?): Boolean {
if (other is PyTargetBasedPsiLocation) {
return target == other.target && metainfo == other.metainfo
}
return false
}
override fun hashCode(): Int {
return target.hashCode()
}
}
/**
* @return factory chosen by user in "test runner" settings
*/
private fun findConfigurationFactoryFromSettings(module: Module): ConfigurationFactory {
val name = TestRunnerService.getInstance(module).projectConfiguration
val factories = PythonTestConfigurationType.getInstance().configurationFactories
val configurationFactory = factories.find { it.name == name }
return configurationFactory ?: factories.first()
}
// folder provided by python side. Resolve test names versus it
private val PATH_URL = java.util.regex.Pattern.compile("^python<([^<>]+)>$")
/**
* Resolves url into element
*/
fun getElementByUrl(url: String,
module: Module,
evalContext: TypeEvalContext): Location<out PsiElement>? {
val protocol = VirtualFileManager.extractProtocol(url) ?: return null
return getElementByUrl(protocol,
VirtualFileManager.extractPath(url),
module,
evalContext)
}
private fun Sdk.getMapping(project: Project) = (sdkAdditionalData as? RemoteSdkAdditionalData<*>)?.let { data ->
PathMappingProvider.getSuitableMappingProviders(data).flatMap { it.getPathMappingSettings(project, data).pathMappings }
} ?: emptyList()
private fun getFolderFromMatcher(matcher: Matcher, module: Module): String? {
if (!matcher.matches()) {
return null
}
val folder = matcher.group(1)
val sdk = module.getSdk()
if (sdk != null && PySdkUtil.isRemote(sdk)) {
return sdk.getMapping(module.project).find { it.canReplaceRemote(folder) }?.mapToLocal(folder)
}
else {
return folder
}
}
private fun getElementByUrl(protocol: String,
path: String,
module: Module,
evalContext: TypeEvalContext,
matcher: Matcher = PATH_URL.matcher(protocol),
metainfo: String? = null): Location<out PsiElement>? {
val folder = getFolderFromMatcher(matcher, module)?.let { LocalFileSystem.getInstance().findFileByPath(it) }
val qualifiedName = QualifiedName.fromDottedString(path)
// Assume qname id good and resolve it directly
val element = qualifiedName.resolveToElement(QNameResolveContext(ModuleBasedContextAnchor(module),
evalContext = evalContext,
folderToStart = folder,
allowInaccurateResult = true))
return if (element != null) {
// Path is qualified name of python test according to runners protocol
// Parentheses are part of generators / parametrized tests
// Until https://github.com/JetBrains/teamcity-messages/issues/121 they are disabled,
// so we cut them out of path not to provide unsupported targets to runners
val pathNoParentheses = QualifiedName.fromComponents(
qualifiedName.components.filter { !it.contains('(') }).toString()
PyTargetBasedPsiLocation(ConfigurationTarget(pathNoParentheses, PyRunTargetVariant.PYTHON), element, metainfo)
}
else {
null
}
}
object PyTestsLocator : SMTestLocator {
override fun getLocation(protocol: String,
path: String,
metainfo: String?,
project: Project,
scope: GlobalSearchScope): List<Location<out PsiElement>> = getLocationInternal(protocol, path, project,
metainfo, scope)
override fun getLocation(protocol: String, path: String, project: Project, scope: GlobalSearchScope): List<Location<out PsiElement>> {
return getLocationInternal(protocol, path, project, null, scope)
}
private fun getLocationInternal(protocol: String,
path: String,
project: Project,
metainfo: String?,
scope: GlobalSearchScope): List<Location<out PsiElement>> {
if (scope !is ModuleWithDependenciesScope) {
return listOf()
}
val matcher = PATH_URL.matcher(protocol)
if (!matcher.matches()) {
// special case: setup.py runner uses unittest configuration but different (old) protocol
// delegate to old protocol locator until setup.py moved to separate configuration
val oldLocation = PythonUnitTestTestIdUrlProvider.INSTANCE.getLocation(protocol, path, project, scope)
if (oldLocation.isNotEmpty()) {
return oldLocation
}
}
return getElementByUrl(protocol, path, scope.module, TypeEvalContext.codeAnalysis(project, null), matcher, metainfo)?.let {
listOf(it)
} ?: listOf()
}
}
abstract class PyTestExecutionEnvironment<T : PyAbstractTestConfiguration>(configuration: T,
environment: ExecutionEnvironment)
: PythonTestCommandLineStateBase<T>(configuration, environment) {
override fun getTestLocator(): SMTestLocator = PyTestsLocator
override fun getTestSpecs(): MutableList<String> = java.util.ArrayList(configuration.getTestSpec())
override fun generateCommandLine(): GeneralCommandLine {
val line = super.generateCommandLine()
line.workDirectory = java.io.File(configuration.workingDirectorySafe)
return line
}
}
abstract class PyAbstractTestSettingsEditor(private val sharedForm: PyTestSharedForm)
: SettingsEditor<PyAbstractTestConfiguration>() {
override fun resetEditorFrom(s: PyAbstractTestConfiguration) {
// usePojoProperties is true because we know that Form is java-based
AbstractPythonRunConfiguration.copyParams(s, sharedForm.optionsForm)
s.copyTo(getProperties(sharedForm, usePojoProperties = true))
}
override fun applyEditorTo(s: PyAbstractTestConfiguration) {
AbstractPythonRunConfiguration.copyParams(sharedForm.optionsForm, s)
s.copyFrom(getProperties(sharedForm, usePojoProperties = true))
}
override fun createEditor(): javax.swing.JComponent = sharedForm.panel
}
/**
* Default target path (run all tests ion project folder)
*/
private const val DEFAULT_PATH = ""
/**
* Target depends on target type. It could be path to file/folder or python target
*/
data class ConfigurationTarget(@ConfigField override var target: String,
@ConfigField override var targetType: PyRunTargetVariant) : TargetWithVariant {
fun copyTo(dst: ConfigurationTarget) {
// TODO: do we have such method it in Kotlin?
dst.target = target
dst.targetType = targetType
}
/**
* Validates configuration and throws exception if target is invalid
*/
fun checkValid() {
if (targetType != PyRunTargetVariant.CUSTOM && target.isEmpty()) {
throw RuntimeConfigurationWarning("Target not provided")
}
if (targetType == PyRunTargetVariant.PYTHON && !isWellFormed()) {
throw RuntimeConfigurationError("Provide a qualified name of function, class or a module")
}
}
fun asPsiElement(configuration: PyAbstractTestConfiguration): PsiElement? =
asPsiElement(configuration, configuration.getWorkingDirectoryAsVirtual())
fun generateArgumentsLine(configuration: PyAbstractTestConfiguration): List<String> =
when (targetType) {
PyRunTargetVariant.CUSTOM -> emptyList()
PyRunTargetVariant.PYTHON -> getArgumentsForPythonTarget(configuration)
PyRunTargetVariant.PATH -> listOf("--path", target.trim())
}
private fun getArgumentsForPythonTarget(configuration: PyAbstractTestConfiguration): List<String> {
val element = asPsiElement(configuration) ?: throw ExecutionException(
"Can't resolve $target. Try to remove configuration and generate it again")
if (element is PsiDirectory) {
// Directory is special case: we can't run it as package for now, so we run it as path
return listOf("--path", element.virtualFile.path)
}
val context = TypeEvalContext.userInitiated(configuration.project, null)
val qNameResolveContext = QNameResolveContext(
contextAnchor = ModuleBasedContextAnchor(configuration.module!!),
evalContext = context,
folderToStart = LocalFileSystem.getInstance().findFileByPath(configuration.workingDirectorySafe),
allowInaccurateResult = true
)
val qualifiedNameParts = QualifiedName.fromDottedString(target.trim()).tryResolveAndSplit(qNameResolveContext)
?: throw ExecutionException("Can't find file where $target declared. " +
"Make sure it is in project root")
// We can't provide element qname here: it may point to parent class in case of inherited functions,
// so we make fix file part, but obey element(symbol) part of qname
if (!configuration.shouldSeparateTargetPath()) {
// Here generate qname instead of file/path::element_name
// Try to set path relative to work dir (better than path from closest root)
// If we can resolve element by this path relative to working directory then use it
val qNameInsideOfDirectory = qualifiedNameParts.getElementNamePrependingFile()
val elementAndName = qNameInsideOfDirectory.getElementAndResolvableName(qNameResolveContext.copy(allowInaccurateResult = false))
if (elementAndName != null) {
// qNameInsideOfDirectory may contain redundant elements like subtests so we use name that was really resolved
// element.qname can't be used because inherited test resolves to parent
return listOf("--target", elementAndName.name.toString())
}
// Use "full" (path from closest root) otherwise
val name = (element.containingFile as? PyFile)?.getQName()?.append(qualifiedNameParts.elementName) ?: throw ExecutionException(
"Can't get importable name for ${element.containingFile}. Is it a python file in project?")
return listOf("--target", name.toString())
}
else {
// Here generate file/path::element_name
val pyTarget = qualifiedNameParts.elementName
val elementFile = element.containingFile.virtualFile
val workingDir = elementFile.fileSystem.findFileByPath(configuration.workingDirectorySafe)
val fileSystemPartOfTarget = (if (workingDir != null) VfsUtil.getRelativePath(elementFile, workingDir)
else null)
?: elementFile.path
if (pyTarget.componentCount == 0) {
// If python part is empty we are launching file. To prevent junk like "foo.py::" we run it as file instead
return listOf("--path", fileSystemPartOfTarget)
}
return listOf("--target", "$fileSystemPartOfTarget::$pyTarget")
}
}
/**
* @return directory which target is situated
*/
fun getElementDirectory(configuration: PyAbstractTestConfiguration): VirtualFile? {
if (target == DEFAULT_PATH) {
//This means "current directory", so we do not know where is it
// getting vitualfile for it may return PyCharm working directory which is not what we want
return null
}
val fileOrDir = asVirtualFile() ?: asPsiElement(configuration)?.containingFile?.virtualFile ?: return null
return if (fileOrDir.isDirectory) fileOrDir else fileOrDir.parent
}
}
/**
* To prevent legacy configuration options from clashing with new names, we add prefix
* to use for writing/reading xml
*/
private val Property.prefixedName: String
get() = "_new_" + this.getName()
/**
* Parent of all new test configurations.
* All config-specific fields are implemented as properties. They are saved/restored automatically and passed to GUI form.
*
*/
abstract class PyAbstractTestConfiguration(project: Project,
configurationFactory: ConfigurationFactory,
private val runnerName: String)
: AbstractPythonTestRunConfiguration<PyAbstractTestConfiguration>(project, configurationFactory), PyRerunAwareConfiguration,
RefactoringListenerProvider {
/**
* Args after it passed to test runner itself
*/
protected val rawArgumentsSeparator = "--"
@DelegationProperty
val target: ConfigurationTarget = ConfigurationTarget(DEFAULT_PATH, PyRunTargetVariant.PATH)
@ConfigField
var additionalArguments: String = ""
val testFrameworkName: String = configurationFactory.name
/**
* @see [RunnersThatRequireTestCaseClass]
*/
fun isTestClassRequired(): ThreeState = if (RunnersThatRequireTestCaseClass.contains(runnerName)) {
ThreeState.YES
}
else {
ThreeState.NO
}
@Suppress("LeakingThis") // Legacy adapter is used to support legacy configs. Leak is ok here since everything takes place in one thread
@DelegationProperty
val legacyConfigurationAdapter: PyTestLegacyConfigurationAdapter<PyAbstractTestConfiguration> = PyTestLegacyConfigurationAdapter(this)
/**
* For real launch use [getWorkingDirectorySafe] instead
*/
internal fun getWorkingDirectoryAsVirtual(): VirtualFile? {
if (!workingDirectory.isNullOrEmpty()) {
return LocalFileSystem.getInstance().findFileByPath(workingDirectory)
}
return null
}
override fun getWorkingDirectorySafe(): String {
val dirProvidedByUser = super.getWorkingDirectory()
if (!dirProvidedByUser.isNullOrEmpty()) {
return dirProvidedByUser
}
return target.getElementDirectory(this)?.path ?: super.getWorkingDirectorySafe()
}
override fun getRefactoringElementListener(element: PsiElement?): RefactoringElementListener? {
if (element == null) return null
var renamer = CompositeRefactoringElementListener(PyWorkingDirectoryRenamer(getWorkingDirectoryAsVirtual(), this))
createRefactoringListenerIfPossible(element, target.asPsiElement(this), target.asVirtualFile(), { target.target = it })?.let {
renamer = renamer.plus(it)
}
return renamer
}
override fun checkConfiguration() {
super.checkConfiguration()
if (!isFrameworkInstalled()) {
throw RuntimeConfigurationWarning(
PyBundle.message("runcfg.testing.no.test.framework", testFrameworkName))
}
target.checkValid()
}
/**
* Check if framework is available on SDK
*/
abstract fun isFrameworkInstalled(): Boolean
override fun isIdTestBased(): Boolean = true
private fun getPythonTestSpecByLocation(location: Location<*>): List<String> {
if (location is PyTargetBasedPsiLocation) {
return location.target.generateArgumentsLine(this)
}
if (location !is PsiLocation) {
return emptyList()
}
if (location.psiElement !is PyQualifiedNameOwner) {
return emptyList()
}
val qualifiedName = (location.psiElement as PyQualifiedNameOwner).qualifiedName ?: return emptyList()
// Resolve name as python qname as last resort
return ConfigurationTarget(qualifiedName, PyRunTargetVariant.PYTHON).generateArgumentsLine(this)
}
override fun getTestSpec(location: Location<*>,
failedTest: com.intellij.execution.testframework.AbstractTestProxy): String? {
val list = getPythonTestSpecByLocation(location)
if (list.isEmpty()) {
return null
}
else {
return list.joinToString(" ")
}
}
override fun getTestSpecsForRerun(scope: com.intellij.psi.search.GlobalSearchScope,
locations: MutableList<Pair<Location<*>, AbstractTestProxy>>): List<String> {
val result = java.util.ArrayList<String>()
// Set used to remove duplicate targets
locations.map { it.first }.distinctBy { it.psiElement }.map { getPythonTestSpecByLocation(it) }.forEach {
result.addAll(it)
}
return result + generateRawArguments(true)
}
fun getTestSpec(): List<String> {
return target.generateArgumentsLine(this) + generateRawArguments()
}
/**
* raw arguments to be added after "--" and passed to runner directly
*/
private fun generateRawArguments(forRerun: Boolean = false): List<String> {
val rawArguments = additionalArguments + " " + getCustomRawArgumentsString(forRerun)
if (rawArguments.isNotBlank()) {
return listOf(rawArgumentsSeparator) + com.intellij.util.execution.ParametersListUtil.parse(rawArguments, false, true)
}
return emptyList()
}
override fun suggestedName(): String =
when (target.targetType) {
PyRunTargetVariant.PATH -> {
val name = target.asVirtualFile()?.name
"$testFrameworkName in " + (name ?: target.target)
}
PyRunTargetVariant.PYTHON -> {
"$testFrameworkName for " + target.target
}
else -> {
testFrameworkName
}
}
/**
* @return configuration-specific arguments
*/
protected open fun getCustomRawArgumentsString(forRerun: Boolean = false): String = ""
fun reset() {
target.target = DEFAULT_PATH
target.targetType = PyRunTargetVariant.PATH
additionalArguments = ""
}
fun copyFrom(src: Properties) {
src.copyTo(getConfigFields())
}
fun copyTo(dst: Properties) {
getConfigFields().copyTo(dst)
}
override fun writeExternal(element: org.jdom.Element) {
// Write legacy config to preserve it
legacyConfigurationAdapter.writeExternal(element)
// Super is called after to overwrite legacy settings with new one
super.writeExternal(element)
val gson = com.google.gson.Gson()
getConfigFields().properties.forEach {
val value = it.get()
if (value != null) {
// No need to write null since null is default value
writeField(element, it.prefixedName, gson.toJson(value))
}
}
}
override fun readExternal(element: org.jdom.Element) {
super.readExternal(element)
val gson = com.google.gson.Gson()
getConfigFields().properties.forEach {
val fromJson: Any? = gson.fromJson(readField(element, it.prefixedName), it.getType())
if (fromJson != null) {
it.set(fromJson)
}
}
legacyConfigurationAdapter.readExternal(element)
}
private fun getConfigFields() = getProperties(this, ConfigField::class.java)
/**
* Checks if element could be test target for this config.
* Function is used to create tests by context.
*
* If yes, and element is [PsiElement] then it is [PyRunTargetVariant.PYTHON].
* If file then [PyRunTargetVariant.PATH]
*/
fun couldBeTestTarget(element: PsiElement): Boolean {
// TODO: PythonUnitTestUtil logic is weak. We should give user ability to launch test on symbol since user knows better if folder
// contains tests etc
val context = TypeEvalContext.userInitiated(element.project, element.containingFile)
return isTestElement(element, isTestClassRequired(), context)
}
/**
* There are 2 ways to provide target to runner:
* * As full qname (package1.module1.Class1.test_foo)
* * As filesystem path (package1/module1.py::Class1.test_foo) full or relative to working directory
*
* Second approach is prefered if this flag is set. It is generally better because filesystem path does not need __init__.py
*/
internal open fun shouldSeparateTargetPath(): Boolean = true
/**
* @param metaInfo String "metainfo" field provided by test runner
*/
open fun setMetaInfo(metaInfo: String) {
}
/**
* @return Boolean if metainfo and target produces same configuration
*/
open fun isSameAsLocation(target: ConfigurationTarget, metainfo: String?): Boolean = target == this.target
}
abstract class PyAbstractTestFactory<out CONF_T : PyAbstractTestConfiguration> : PythonConfigurationFactoryBase(
PythonTestConfigurationType.getInstance()) {
abstract override fun createTemplateConfiguration(project: Project): CONF_T
}
/**
* Only one producer is registered with EP, but it uses factory configured by user to produce different configs
*/
internal class PyTestsConfigurationProducer : AbstractPythonTestConfigurationProducer<PyAbstractTestConfiguration>() {
companion object {
/**
* Creates [ConfigurationTarget] to make configuration work with provided element.
* Also reports working dir what should be set to configuration to work correctly
* @return [target, workingDirectory]
*/
internal fun getTargetForConfig(configuration: PyAbstractTestConfiguration,
baseElement: PsiElement): Pair<ConfigurationTarget, String?>? {
var element = baseElement
// Go up until we reach top of the file
// asking configuration about each element if it is supported or not
// If element is supported -- set it as configuration target
do {
if (configuration.couldBeTestTarget(element)) {
when (element) {
is PyQualifiedNameOwner -> { // Function, class, method
val module = configuration.module ?: return null
val elementFile = element.containingFile as? PyFile ?: return null
val workingDirectory = getDirectoryForFileToBeImportedFrom(elementFile) ?: return null
val context = QNameResolveContext(ModuleBasedContextAnchor(module),
evalContext = TypeEvalContext.userInitiated(configuration.project,
null),
folderToStart = workingDirectory.virtualFile)
val parts = element.tryResolveAndSplit(context) ?: return null
val qualifiedName = parts.getElementNamePrependingFile(workingDirectory)
return Pair(ConfigurationTarget(qualifiedName.toString(), PyRunTargetVariant.PYTHON),
workingDirectory.virtualFile.path)
}
is PsiFileSystemItem -> {
val virtualFile = element.virtualFile
val path = virtualFile
val workingDirectory = when (element) {
is PyFile -> getDirectoryForFileToBeImportedFrom(element)
is PsiDirectory -> element
else -> return null
}?.virtualFile?.path ?: return null
return Pair(ConfigurationTarget(path.path, PyRunTargetVariant.PATH), workingDirectory)
}
}
}
element = element.parent ?: break
}
while (element !is PsiDirectory) // if parent is folder, then we are at file level
return null
}
/**
* Inspects file relative imports, finds farthest and returns folder with imported file
*/
private fun getDirectoryForFileToBeImportedFrom(file: PyFile): PsiDirectory? {
val maxRelativeLevel = file.fromImports.map { it.relativeLevel }.max() ?: 0
var elementFolder = file.parent ?: return null
for (i in 1..maxRelativeLevel) {
elementFolder = elementFolder.parent ?: return null
}
return elementFolder
}
}
init {
if (!isNewTestsModeEnabled()) {
throw ExtensionNotApplicableException.INSTANCE
}
}
override fun getConfigurationFactory() = PythonTestConfigurationType.getInstance().configurationFactories[0]
override val configurationClass: Class<PyAbstractTestConfiguration> = PyAbstractTestConfiguration::class.java
override fun createLightConfiguration(context: ConfigurationContext): RunConfiguration? {
val module = context.module ?: return null
val project = context.project ?: return null
val configuration =
findConfigurationFactoryFromSettings(module).createTemplateConfiguration(project) as? PyAbstractTestConfiguration
?: return null
if (!setupConfigurationFromContext(configuration, context, Ref(context.psiLocation))) return null
return configuration
}
override fun cloneTemplateConfiguration(context: ConfigurationContext): RunnerAndConfigurationSettings {
return cloneTemplateConfigurationStatic(context, findConfigurationFactoryFromSettings(context.module))
}
override fun createConfigurationFromContext(context: ConfigurationContext?): ConfigurationFromContext? {
// Since we need module, no need to even try to create config with out of it
context?.module ?: return null
return super.createConfigurationFromContext(context)
}
override fun findOrCreateConfigurationFromContext(context: ConfigurationContext?): ConfigurationFromContext? {
if (!isNewTestsModeEnabled()) {
return null
}
return super.findOrCreateConfigurationFromContext(context)
}
// test configuration is always prefered over regular one
override fun shouldReplace(self: ConfigurationFromContext,
other: ConfigurationFromContext): Boolean = other.configuration is PythonRunConfiguration
override fun isPreferredConfiguration(self: ConfigurationFromContext?,
other: ConfigurationFromContext): Boolean = other.configuration is PythonRunConfiguration
override fun setupConfigurationFromContext(configuration: PyAbstractTestConfiguration?,
context: ConfigurationContext?,
sourceElement: Ref<PsiElement>?): Boolean {
if (sourceElement == null || configuration == null) {
return false
}
val element = sourceElement.get() ?: return false
if (element.containingFile !is PyFile && element !is PsiDirectory) {
return false
}
val location = context?.location
configuration.module = context?.module
configuration.isUseModuleSdk = true
if (location is PyTargetBasedPsiLocation) {
location.target.copyTo(configuration.target)
location.metainfo?.let { configuration.setMetaInfo(it) }
}
else {
val targetForConfig = PyTestsConfigurationProducer.getTargetForConfig(configuration,
element) ?: return false
targetForConfig.first.copyTo(configuration.target)
// Directory may be set in Default configuration. In that case no need to rewrite it.
if (configuration.workingDirectory.isNullOrEmpty()) {
configuration.workingDirectory = targetForConfig.second
}
}
configuration.setGeneratedName()
return true
}
override fun isConfigurationFromContext(configuration: PyAbstractTestConfiguration, context: ConfigurationContext?): Boolean {
if (context != null && PyTestConfigurationSelector.EP.extensionList.find { it.isFromContext(configuration, context) } != null) {
return true
}
val location = context?.location
if (location is PyTargetBasedPsiLocation) {
// With derived classes several configurations for same element may exist
return configuration.isSameAsLocation(location.target, location.metainfo)
}
val psiElement = context?.psiLocation ?: return false
val targetForConfig = PyTestsConfigurationProducer.getTargetForConfig(configuration, psiElement) ?: return false
if (configuration.target != targetForConfig.first) {
return false
}
//Even of both configurations have same targets, it could be that both have same qname which is resolved
// to different elements due to different working folders.
// Resolve them and check files
if (configuration.target.targetType != PyRunTargetVariant.PYTHON) return true
val targetPsi = targetAsPsiElement(configuration.target.targetType, configuration.target.target, configuration,
configuration.getWorkingDirectoryAsVirtual()) ?: return true
return targetPsi.containingFile == psiElement.containingFile
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
/**
* Mark run configuration field with it to enable saving, resotring and form iteraction
*/
annotation class ConfigField
| apache-2.0 | 05e8264de8cc18444a1e7d34d9771389 | 40.209443 | 140 | 0.70572 | 5.46197 | false | true | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/references/GrExplicitMethodCallReference.kt | 2 | 2119 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.references
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrReferenceExpressionImpl
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.resolveKinds
import org.jetbrains.plugins.groovy.lang.resolve.GrReferenceResolveRunner
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyCachingReference
import org.jetbrains.plugins.groovy.lang.resolve.impl.filterByArgumentsCount
import org.jetbrains.plugins.groovy.lang.resolve.impl.filterBySignature
import org.jetbrains.plugins.groovy.lang.resolve.impl.getArguments
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyRValueProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.MethodProcessor
class GrExplicitMethodCallReference(ref: GrReferenceExpressionImpl) : GroovyCachingReference<GrReferenceExpressionImpl>(ref) {
override fun doResolve(incomplete: Boolean): Collection<GroovyResolveResult> {
require(!incomplete)
val ref = element
val name = ref.referenceName ?: return emptyList()
val methodCall = ref.parent as GrMethodCall
val arguments = methodCall.getArguments()
val methodProcessor = MethodProcessor(name, ref, arguments, ref.typeArguments)
GrReferenceResolveRunner(ref, methodProcessor).resolveReferenceExpression()
methodProcessor.applicableCandidates?.let {
return it
}
val propertyProcessor = GroovyRValueProcessor(name, ref, ref.resolveKinds())
GrReferenceResolveRunner(ref, propertyProcessor).resolveReferenceExpression()
val properties = propertyProcessor.results
if (properties.size == 1) {
return properties
}
val methods = filterBySignature(filterByArgumentsCount(methodProcessor.allCandidates, arguments))
return methods + properties
}
}
| apache-2.0 | ee1431d187723a106679e66dcfa25e26 | 51.975 | 140 | 0.815007 | 4.626638 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MoveVariableDeclarationIntoWhenInspection.kt | 2 | 6268 | // 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.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.base.psi.isOneLiner
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.countUsages
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.previousStatement
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor
class MoveVariableDeclarationIntoWhenInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
whenExpressionVisitor(fun(expression: KtWhenExpression) {
val subjectExpression = expression.subjectExpression ?: return
val property = expression.findDeclarationNear() ?: return
val identifier = property.nameIdentifier ?: return
val initializer = property.initializer ?: return
if (!initializer.isOneLiner()) return
if (initializer.anyDescendantOfType<KtExpression> {
it is KtThrowExpression || it is KtReturnExpression || it is KtBreakExpression || it is KtContinueExpression
}) return
val action = property.action(expression)
if (action == Action.NOTHING) return
if (action == Action.MOVE && !property.isOneLiner()) return
holder.registerProblem(
property,
TextRange.from(identifier.startOffsetInParent, identifier.textLength),
action.description,
action.createFix(subjectExpression.createSmartPointer())
)
})
}
private enum class Action {
NOTHING,
MOVE,
INLINE;
val description: String
get() = when (this) {
MOVE -> KotlinBundle.message("variable.declaration.could.be.moved.into.when")
INLINE -> KotlinBundle.message("variable.declaration.could.be.inlined")
NOTHING -> KotlinBundle.message("nothing.to.do")
}
fun createFix(subjectExpressionPointer: SmartPsiElementPointer<KtExpression>): VariableDeclarationIntoWhenFix = when (this) {
MOVE -> VariableDeclarationIntoWhenFix(KotlinBundle.message("move.variable.declaration.into.when"), subjectExpressionPointer) { it }
INLINE -> VariableDeclarationIntoWhenFix(KotlinBundle.message("inline.variable"), subjectExpressionPointer) { it.initializer }
else -> error("Illegal action")
}
}
private fun KtProperty.action(element: KtElement): Action = when (val elementUsages = countUsages(element)) {
countUsages() -> if (elementUsages == 1) Action.INLINE else Action.MOVE
else -> Action.NOTHING
}
private fun KtWhenExpression.findDeclarationNear(): KtProperty? {
val previousProperty = previousStatement() as? KtProperty
?: previousPropertyFromParent()
?: return null
return previousProperty.takeIf { !it.isVar && it.hasInitializer() && it.nameIdentifier?.text == subjectExpression?.text }
}
private tailrec fun KtExpression.previousPropertyFromParent(): KtProperty? {
val parentExpression = parent as? KtExpression ?: return null
if (this != when (parentExpression) {
is KtProperty -> parentExpression.initializer
is KtReturnExpression -> parentExpression.returnedExpression
is KtBinaryExpression -> parentExpression.left
is KtUnaryExpression -> parentExpression.baseExpression
else -> null
}
) return null
return parentExpression.previousStatement() as? KtProperty ?: parentExpression.previousPropertyFromParent()
}
private class VariableDeclarationIntoWhenFix(
@Nls private val actionName: String,
private val subjectExpressionPointer: SmartPsiElementPointer<KtExpression>,
private val transform: (KtProperty) -> KtExpression?
) : LocalQuickFix {
override fun getName() = actionName
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val property = descriptor.psiElement as? KtProperty ?: return
val subjectExpression = subjectExpressionPointer.element ?: return
val newElement = property.copy() as? KtProperty ?: return
val toReplace = transform(newElement) ?: return
val tailComments = newElement.allChildren.toList().takeLastWhile { it is PsiWhiteSpace || it is PsiComment }
if (tailComments.isNotEmpty()) {
val leftBrace = subjectExpression.siblings(withItself = false).firstOrNull { it.node.elementType == KtTokens.LBRACE }
if (leftBrace != null) {
tailComments.reversed().forEach {
subjectExpression.parent.addAfter(it, leftBrace)
it.delete()
}
}
}
val docComment = newElement.docComment
if (docComment != null) {
val whenExpression = subjectExpression.parent
whenExpression.parent.addBefore(docComment, whenExpression)
docComment.delete()
}
val resultElement = subjectExpression.replace(toReplace)
property.delete()
val editor = resultElement.findExistingEditor() ?: return
editor.moveCaret((resultElement as? KtProperty)?.nameIdentifier?.startOffset ?: resultElement.startOffset)
}
}
| apache-2.0 | 1fd5a25ec08bdc058c5e916a77ea1489 | 45.088235 | 158 | 0.716656 | 5.527337 | false | false | false | false |
ronocod/BeerSignal | android/app/src/main/kotlin/com/starstorm/beer/activity/LoginActivity.kt | 1 | 1773 | package com.starstorm.beer.activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.ActionBarActivity
import android.view.View
import android.widget.ProgressBar
import com.novoda.notils.caster.Views
import com.parse.ParseFacebookUtils
import com.parse.ParseUser
import com.starstorm.beer.R
import com.starstorm.beer.fragment.LoginFragment
public class LoginActivity : ActionBarActivity() {
private var loginFragment: LoginFragment? = null
private var loginProgress: ProgressBar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
loginProgress = Views.findById<ProgressBar>(this, R.id.login_progress)
if (savedInstanceState == null) {
loginFragment = LoginFragment.newInstance()
getFragmentManager().beginTransaction().add(R.id.container, loginFragment).hide(loginFragment).commit()
}
}
override fun onResume() {
super.onResume()
if (ParseUser.getCurrentUser() != null) {
// logged in, go to main page
val intent = Intent(this, javaClass<MainActivity>())
startActivity(intent)
overridePendingTransition(0, 0)
finish()
return
}
// hide progress indicator
loginProgress!!.setVisibility(View.GONE)
// show login fragment
getFragmentManager().beginTransaction().show(loginFragment).commit()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data)
}
}
| gpl-2.0 | b3f88c6ae38a7b1b4a3b170104e25c59 | 30.660714 | 115 | 0.69656 | 4.952514 | false | false | false | false |
NeatoRobotics/neato-sdk-android | Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/robotservices/housecleaning/HouseCleaningBasic1Service.kt | 1 | 711 | /*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.robotservices.housecleaning
class HouseCleaningBasic1Service : HouseCleaningService() {
override val isMultipleZonesCleaningSupported: Boolean
get() = false
override val isEcoModeSupported: Boolean
get() = true
override val isTurboModeSupported: Boolean
get() = true
override val isExtraCareModeSupported: Boolean
get() = false
override val isCleaningAreaSupported: Boolean
get() = false
override val isCleaningFrequencySupported: Boolean
get() = false
companion object {
private const val TAG = "HouseCleaningBasic1"
}
}
| mit | 7ecb7c348fcd16ac33d2c825b8568ab8 | 21.21875 | 65 | 0.690577 | 4.708609 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/model/psi/impl/PsiElementDeclarationSearcher.kt | 2 | 3056 | // 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.model.psi.impl
import com.intellij.codeInsight.daemon.impl.IdentifierUtil
import com.intellij.codeInsight.highlighting.HighlightUsagesHandler
import com.intellij.model.psi.PsiSymbolDeclaration
import com.intellij.model.psi.PsiSymbolService
import com.intellij.model.search.PsiSymbolDeclarationSearchParameters
import com.intellij.model.search.PsiSymbolDeclarationSearcher
import com.intellij.openapi.util.TextRange
import com.intellij.pom.PomTargetPsiElement
import com.intellij.pom.PsiDeclaredTarget
import com.intellij.psi.ExternallyAnnotated
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiTarget
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.util.PsiUtilBase
import com.intellij.util.ArrayQuery
import com.intellij.util.Query
class PsiElementDeclarationSearcher : PsiSymbolDeclarationSearcher {
override fun collectSearchRequests(parameters: PsiSymbolDeclarationSearchParameters): Collection<Query<out PsiSymbolDeclaration>> {
val psi = PsiSymbolService.getInstance().extractElementFromSymbol(parameters.symbol) ?: return emptyList()
val declaration = getDeclaration(psi, parameters.searchScope) ?: return emptyList()
return listOf(ArrayQuery(declaration))
}
private fun getDeclaration(psi: PsiElement, searchScope: SearchScope): PsiSymbolDeclaration? {
if (searchScope is LocalSearchScope) {
return inLocalScope(psi, searchScope)
}
else {
return inGlobalScope(psi, searchScope as GlobalSearchScope)
}
}
private fun inLocalScope(psi: PsiElement, searchScope: LocalSearchScope): PsiSymbolDeclaration? {
for (scopeElement in searchScope.scope) {
val scopeFile = scopeElement.containingFile ?: continue
val declarationRange = HighlightUsagesHandler.getNameIdentifierRangeInCurrentRoot(scopeFile, psi) ?: continue // call old implementation as is
return PsiElement2Declaration(psi, scopeFile, declarationRange.getSecond())
}
return null
}
private fun inGlobalScope(psi: PsiElement, searchScope: GlobalSearchScope): PsiSymbolDeclaration? {
val containingFile = psi.containingFile ?: return null
val virtualFile = containingFile.virtualFile ?: return null
if (!searchScope.contains(virtualFile)) {
return null
}
return when (psi) {
is PsiFile -> null // files don't have declarations inside PSI
is PomTargetPsiElement -> fromPomTargetElement(psi)
else -> PsiElement2Declaration.createFromTargetPsiElement(psi)
}
}
private fun fromPomTargetElement(psi: PomTargetPsiElement): PsiSymbolDeclaration? {
val target = psi.target as? PsiTarget ?: return null
val navigationElement = target.navigationElement
return PsiElement2Declaration.createFromPom(target, navigationElement)
}
}
| apache-2.0 | 8a07cf88574a1d820135e3e7112a155b | 43.941176 | 148 | 0.794175 | 4.897436 | false | false | false | false |
fluidsonic/fluid-json | basic/sources-jvm/JsonWriter.kt | 1 | 28454 | @file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
package io.fluidsonic.json
import java.io.*
import kotlin.contracts.*
import kotlin.internal.*
public interface JsonWriter : Closeable, Flushable {
public val depth: JsonDepth
public val isErrored: Boolean
public val isInValueIsolation: Boolean
public val path: JsonPath
public fun beginValueIsolation(): JsonDepth
public fun endValueIsolation(depth: JsonDepth)
public fun markAsErrored()
public fun terminate()
public fun writeBoolean(value: Boolean)
public fun writeDouble(value: Double)
public fun writeListEnd()
public fun writeListStart()
public fun writeLong(value: Long)
public fun writeMapEnd()
public fun writeMapStart()
public fun writeNull()
public fun writeString(value: String)
public fun writeByte(value: Byte) {
writeLong(value.toLong())
}
public fun writeChar(value: Char) {
writeString(value.toString())
}
public fun writeFloat(value: Float) {
writeDouble(value.toDouble())
}
public fun writeInt(value: Int) {
writeLong(value.toLong())
}
public fun writeMapKey(value: String) {
writeString(value)
}
public fun writeNumber(value: Number) {
return when (value) {
is Byte -> writeByte(value)
is Float -> writeFloat(value)
is Int -> writeInt(value)
is Long -> writeLong(value)
is Short -> writeShort(value)
else -> writeDouble(value.toDouble())
}
}
public fun writeShort(value: Short) {
writeLong(value.toLong())
}
public fun writeValue(value: Any) {
when (value) {
is Array<*> -> writeList(value)
is Boolean -> writeBoolean(value)
is BooleanArray -> writeList(value)
is Byte -> writeByte(value)
is ByteArray -> writeList(value)
is Char -> writeChar(value)
is CharArray -> writeList(value)
is DoubleArray -> writeList(value)
is Float -> writeFloat(value)
is FloatArray -> writeList(value)
is Int -> writeInt(value)
is IntArray -> writeList(value)
is Iterable<*> -> writeList(value)
is Long -> writeLong(value)
is LongArray -> writeList(value)
is Map<*, *> -> writeMap(value)
is Sequence<*> -> writeList(value)
is Short -> writeShort(value)
is ShortArray -> writeList(value)
is String -> writeString(value)
is Number -> writeNumber(value) // after subclasses
else -> throw JsonException.Serialization(
message = "Cannot write JSON value of ${value::class}: $value",
path = path
)
}
}
public companion object {
public fun build(destination: Writer): JsonWriter =
StandardWriter(destination)
}
}
public inline fun <Writer : JsonWriter> Writer.isolateValueWrite(crossinline write: Writer.() -> Unit) {
val depth = beginValueIsolation()
val value = write()
endValueIsolation(depth = depth)
return value
}
public inline fun <Writer : JsonWriter?, Result> Writer.use(withTermination: Boolean = true, block: (Writer) -> Result): Result {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
var exception: Throwable? = null
try {
return block(this)
}
catch (e: Throwable) {
exception = e
throw e
}
finally {
val finalException = exception
when {
this == null ->
Unit
finalException == null ->
if (withTermination)
terminate()
else
close()
else ->
try {
close()
}
catch (closeException: Throwable) {
finalException.addSuppressed(closeException)
}
}
}
}
public inline fun <Writer : JsonWriter, Result> Writer.withTermination(withTermination: Boolean = true, block: Writer.() -> Result): Result {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return if (withTermination)
use { it.block() }
else
block()
}
public inline fun <Writer : JsonWriter, ReturnValue> Writer.withErrorChecking(block: Writer.() -> ReturnValue): ReturnValue {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
if (isErrored) {
throw JsonException.Serialization(
message = "Cannot operate on an errored JsonWriter",
path = path
)
}
return try {
block()
}
catch (e: Throwable) {
markAsErrored()
throw e
}
}
public fun JsonWriter.writeBooleanOrNull(value: Boolean?) {
writeOrNull(value, JsonWriter::writeBoolean)
}
public fun JsonWriter.writeByteOrNull(value: Byte?) {
writeOrNull(value, JsonWriter::writeByte)
}
public fun JsonWriter.writeCharOrNull(value: Char?) {
writeOrNull(value, JsonWriter::writeChar)
}
public fun JsonWriter.writeDoubleOrNull(value: Double?) {
writeOrNull(value, JsonWriter::writeDouble)
}
public fun JsonWriter.writeFloatOrNull(value: Float?) {
writeOrNull(value, JsonWriter::writeFloat)
}
public fun JsonWriter.writeIntOrNull(value: Int?) {
writeOrNull(value, JsonWriter::writeInt)
}
public inline fun <Writer : JsonWriter> Writer.writeIntoList(crossinline writeContent: Writer.() -> Unit) {
contract {
callsInPlace(writeContent, InvocationKind.EXACTLY_ONCE)
}
isolateValueWrite {
writeListStart()
writeContent()
writeListEnd()
}
}
public inline fun <Writer : JsonWriter> Writer.writeIntoMap(crossinline writeContent: Writer.() -> Unit) {
contract {
callsInPlace(writeContent, InvocationKind.EXACTLY_ONCE)
}
isolateValueWrite {
writeMapStart()
writeContent()
writeMapEnd()
}
}
public fun JsonWriter.writeList(value: BooleanArray) {
writeListByElement(value) { writeBoolean(it) }
}
public fun JsonWriter.writeList(value: ByteArray) {
writeListByElement(value) { writeByte(it) }
}
public fun JsonWriter.writeList(value: CharArray) {
writeListByElement(value) { writeChar(it) }
}
public fun JsonWriter.writeList(value: DoubleArray) {
writeListByElement(value) { writeDouble(it) }
}
public fun JsonWriter.writeList(value: FloatArray) {
writeListByElement(value) { writeFloat(it) }
}
public fun JsonWriter.writeList(value: IntArray) {
writeListByElement(value) { writeInt(it) }
}
public fun JsonWriter.writeList(value: LongArray) {
writeListByElement(value) { writeLong(it) }
}
public fun JsonWriter.writeList(value: ShortArray) {
writeListByElement(value) { writeShort(it) }
}
public fun JsonWriter.writeList(value: Array<*>) {
writeListByElement(value) { writeValueOrNull(it) }
}
public fun JsonWriter.writeList(value: Iterable<*>) {
writeListByElement(value) { writeValueOrNull(it) }
}
public fun JsonWriter.writeList(value: Sequence<*>) {
writeListByElement(value) { writeValueOrNull(it) }
}
public inline fun <Writer : JsonWriter> Writer.writeListByElement(
value: BooleanArray,
crossinline writeElement: Writer.(element: Boolean) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public inline fun <Writer : JsonWriter> Writer.writeListByElement(
value: ByteArray,
crossinline writeElement: Writer.(element: Byte) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public inline fun <Writer : JsonWriter> Writer.writeListByElement(
value: CharArray,
crossinline writeElement: Writer.(element: Char) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public inline fun <Writer : JsonWriter> Writer.writeListByElement(
value: DoubleArray,
crossinline writeElement: Writer.(element: Double) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public inline fun <Writer : JsonWriter> Writer.writeListByElement(
value: FloatArray,
crossinline writeElement: Writer.(element: Float) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public inline fun <Writer : JsonWriter> Writer.writeListByElement(
value: IntArray,
crossinline writeElement: Writer.(element: Int) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public inline fun <Writer : JsonWriter> Writer.writeListByElement(
value: LongArray,
crossinline writeElement: Writer.(element: Long) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public inline fun <Writer : JsonWriter> Writer.writeListByElement(
value: ShortArray,
crossinline writeElement: Writer.(element: Short) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public inline fun <Writer : JsonWriter, Element> Writer.writeListByElement(
value: Array<Element>,
crossinline writeElement: Writer.(element: Element) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public inline fun <Writer : JsonWriter, Element> Writer.writeListByElement(
value: Iterable<Element>,
crossinline writeElement: Writer.(element: Element) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public inline fun <Writer : JsonWriter, Element> Writer.writeListByElement(
value: Sequence<Element>,
crossinline writeElement: Writer.(element: Element) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoList {
for (element in value) {
isolateValueWrite {
writeElement(element)
}
}
}
}
public fun JsonWriter.writeListOrNull(value: BooleanArray?) {
writeOrNull(value, JsonWriter::writeList)
}
public fun JsonWriter.writeListOrNull(value: ByteArray?) {
writeOrNull(value, JsonWriter::writeList)
}
public fun JsonWriter.writeListOrNull(value: CharArray?) {
writeOrNull(value, JsonWriter::writeList)
}
public fun JsonWriter.writeListOrNull(value: DoubleArray?) {
writeOrNull(value, JsonWriter::writeList)
}
public fun JsonWriter.writeListOrNull(value: FloatArray?) {
writeOrNull(value, JsonWriter::writeList)
}
public fun JsonWriter.writeListOrNull(value: IntArray?) {
writeOrNull(value, JsonWriter::writeList)
}
public fun JsonWriter.writeListOrNull(value: LongArray?) {
writeOrNull(value, JsonWriter::writeList)
}
public fun JsonWriter.writeListOrNull(value: ShortArray?) {
writeOrNull(value, JsonWriter::writeList)
}
public fun JsonWriter.writeListOrNull(value: Array<*>?) {
writeOrNull(value, JsonWriter::writeList)
}
public fun JsonWriter.writeListOrNull(value: Iterable<*>?) {
writeOrNull(value, JsonWriter::writeList)
}
public fun JsonWriter.writeListOrNull(value: Sequence<*>?) {
writeOrNull(value, JsonWriter::writeList)
}
public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement(
value: BooleanArray?,
crossinline writeElement: Writer.(element: Boolean) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement(
value: ByteArray?,
crossinline writeElement: Writer.(element: Byte) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement(
value: CharArray?,
crossinline writeElement: Writer.(element: Char) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement(
value: DoubleArray?,
crossinline writeElement: Writer.(element: Double) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement(
value: FloatArray?,
crossinline writeElement: Writer.(element: Float) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement(
value: IntArray?,
crossinline writeElement: Writer.(element: Int) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement(
value: LongArray?,
crossinline writeElement: Writer.(element: Long) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter> Writer.writeListOrNullByElement(
value: ShortArray?,
crossinline writeElement: Writer.(element: Short) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter, Element> Writer.writeListOrNullByElement(
value: Array<Element>?,
crossinline writeElement: Writer.(element: Element) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter, Element> Writer.writeListOrNullByElement(
value: Iterable<Element>?,
crossinline writeElement: Writer.(element: Element) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter, Element> Writer.writeListOrNullByElement(
value: Sequence<Element>?,
crossinline writeElement: Writer.(element: Element) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeListByElement(it, writeElement) }
}
public fun JsonWriter.writeLongOrNull(value: Long?) {
writeOrNull(value, JsonWriter::writeLong)
}
public fun JsonWriter.writeMap(value: Map<*, *>) {
writeMapByElementValue(value) { writeValueOrNull(it) }
}
public inline fun <Writer : JsonWriter, ElementKey, ElementValue> Writer.writeMapByElement(
value: Map<ElementKey, ElementValue>,
crossinline writeElement: Writer.(key: ElementKey, value: ElementValue) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeIntoMap {
for ((elementKey, elementValue) in value)
writeElement(elementKey, elementValue)
}
}
public inline fun <Writer : JsonWriter, ElementValue> Writer.writeMapByElementValue(
value: Map<*, ElementValue>,
crossinline writeElementValue: Writer.(value: ElementValue) -> Unit,
) {
contract {
callsInPlace(writeElementValue, InvocationKind.UNKNOWN)
}
writeMapByElement(value) { elementKey, elementValue ->
writeValueOrNull(elementKey)
isolateValueWrite {
writeElementValue(elementValue)
}
}
}
public fun JsonWriter.writeMapOrNull(value: Map<*, *>?) {
writeOrNull(value, JsonWriter::writeMap)
}
public inline fun <Writer : JsonWriter, ElementKey, ElementValue> Writer.writeMapOrNullByElement(
value: Map<ElementKey, ElementValue>?,
crossinline writeElement: Writer.(key: ElementKey, value: ElementValue) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeMapByElement(it, writeElement) }
}
public inline fun <Writer : JsonWriter, ElementValue> Writer.writeMapOrNullByElementValue(
value: Map<*, ElementValue>?,
crossinline writeElementValue: Writer.(value: ElementValue) -> Unit,
) {
contract {
callsInPlace(writeElementValue, InvocationKind.UNKNOWN)
}
writeOrNull(value) { writeMapByElementValue(it, writeElementValue) }
}
public fun JsonWriter.writeMapElement(key: String, boolean: Boolean) {
writeMapKey(key)
writeBoolean(boolean)
}
public fun JsonWriter.writeMapElement(key: String, boolean: Boolean?, skipIfNull: Boolean = false) {
if (boolean != null)
writeMapElement(key, boolean)
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
public fun JsonWriter.writeMapElement(key: String, byte: Byte) {
writeMapKey(key)
writeByte(byte)
}
public fun JsonWriter.writeMapElement(key: String, byte: Byte?, skipIfNull: Boolean = false) {
if (byte != null)
writeMapElement(key, byte)
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
public fun JsonWriter.writeMapElement(key: String, char: Char) {
writeMapKey(key)
writeChar(char)
}
public fun JsonWriter.writeMapElement(key: String, char: Char?, skipIfNull: Boolean = false) {
if (char != null)
writeMapElement(key, char)
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
public fun JsonWriter.writeMapElement(key: String, double: Double) {
writeMapKey(key)
writeDouble(double)
}
public fun JsonWriter.writeMapElement(key: String, double: Double?, skipIfNull: Boolean = false) {
if (double != null)
writeMapElement(key, double)
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
public fun JsonWriter.writeMapElement(key: String, float: Float) {
writeMapKey(key)
writeFloat(float)
}
public fun JsonWriter.writeMapElement(key: String, float: Float?, skipIfNull: Boolean = false) {
if (float != null)
writeMapElement(key, float)
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
public fun JsonWriter.writeMapElement(key: String, int: Int) {
writeMapKey(key)
writeInt(int)
}
public fun JsonWriter.writeMapElement(key: String, int: Int?, skipIfNull: Boolean = false) {
if (int != null)
writeMapElement(key, int)
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: Array<*>?, skipIfNull: Boolean = false) {
writeMapElement(key, list = list, skipIfNull = skipIfNull) { writeValueOrNull(it) }
}
public inline fun <Writer : JsonWriter, Element> Writer.writeMapElement(
key: String,
list: Array<Element>?,
skipIfNull: Boolean = false,
crossinline writeElement: Writer.(element: Element) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
if (list != null) {
writeMapKey(key)
writeListByElement(list, writeElement)
}
else if (!skipIfNull)
writeMapNullElement(key)
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: BooleanArray?, skipIfNull: Boolean = false) {
if (list != null) {
writeMapKey(key)
writeList(list)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: ByteArray?, skipIfNull: Boolean = false) {
if (list != null) {
writeMapKey(key)
writeList(list)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: CharArray?, skipIfNull: Boolean = false) {
if (list != null) {
writeMapKey(key)
writeList(list)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: DoubleArray?, skipIfNull: Boolean = false) {
if (list != null) {
writeMapKey(key)
writeList(list)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: FloatArray?, skipIfNull: Boolean = false) {
if (list != null) {
writeMapKey(key)
writeList(list)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: IntArray?, skipIfNull: Boolean = false) {
if (list != null) {
writeMapKey(key)
writeList(list)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: Iterable<*>?, skipIfNull: Boolean = false) {
writeMapElement(key, list = list, skipIfNull = skipIfNull) { writeValueOrNull(it) }
}
public inline fun <Writer : JsonWriter, Element> Writer.writeMapElement(
key: String,
list: Iterable<Element>?,
skipIfNull: Boolean = false,
crossinline writeElement: Writer.(element: Element) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
if (list != null) {
writeMapKey(key)
writeListByElement(list, writeElement)
}
else if (!skipIfNull)
writeMapNullElement(key)
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: LongArray?, skipIfNull: Boolean = false) {
if (list != null) {
writeMapKey(key)
writeList(list)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: Sequence<*>?, skipIfNull: Boolean = false) {
writeMapElement(key, list = list, skipIfNull = skipIfNull) { writeValueOrNull(it) }
}
public inline fun <Writer : JsonWriter, Element> Writer.writeMapElement(
key: String,
list: Sequence<Element>?,
skipIfNull: Boolean = false,
crossinline writeElement: Writer.(element: Element) -> Unit,
) {
contract {
callsInPlace(writeElement, InvocationKind.UNKNOWN)
}
if (list != null) {
writeMapKey(key)
writeListByElement(list, writeElement)
}
else if (!skipIfNull)
writeMapNullElement(key)
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = list, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, list: ShortArray?, skipIfNull: Boolean = false) {
if (list != null) {
writeMapKey(key)
writeList(list)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
public fun JsonWriter.writeMapElement(key: String, long: Long) {
writeMapKey(key)
writeLong(long)
}
public fun JsonWriter.writeMapElement(key: String, long: Long?, skipIfNull: Boolean = false) {
if (long != null)
writeMapElement(key, long)
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
@Deprecated(
message = "Dangerous overload. Use 'Any' overload so that codecs are properly applied.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(expression = "writeMapElement(key, value = map, skipIfNull = skipIfNull)")
)
@LowPriorityInOverloadResolution
public fun JsonWriter.writeMapElement(key: String, map: Map<*, *>?, skipIfNull: Boolean = false) {
writeMapElement(key, map = map, skipIfNull = skipIfNull) { writeValueOrNull(it) }
}
public inline fun <Writer : JsonWriter, Child> Writer.writeMapElement(
key: String,
map: Map<*, Child>?,
skipIfNull: Boolean = false,
crossinline writeChild: Writer.(value: Child) -> Unit,
) {
if (map != null) {
writeMapKey(key)
writeMapByElementValue(map, writeChild)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
public fun JsonWriter.writeMapElement(key: String, number: Number?, skipIfNull: Boolean = false) {
if (number != null) {
writeMapKey(key)
writeNumber(number)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
public fun JsonWriter.writeMapElement(key: String, short: Short) {
writeMapKey(key)
writeShort(short)
}
public fun JsonWriter.writeMapElement(key: String, short: Short?, skipIfNull: Boolean = false) {
if (short != null)
writeMapElement(key, short)
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
public fun JsonWriter.writeMapElement(key: String, string: String?, skipIfNull: Boolean = false) {
if (string != null) {
writeMapKey(key)
writeString(string)
}
else if (!skipIfNull)
writeMapNullElement(key)
else
Unit
}
public fun JsonWriter.writeMapElement(key: String, value: Any?, skipIfNull: Boolean = false) {
writeMapElement(key, value, skipIfNull) { writeValue(it) }
}
public inline fun <Writer : JsonWriter, Value : Any> Writer.writeMapElement(
key: String,
value: Value?,
skipIfNull: Boolean = false,
crossinline writeCustomValue: Writer.(value: Value) -> Unit,
) {
contract {
callsInPlace(writeCustomValue, InvocationKind.AT_MOST_ONCE)
}
if (value != null) {
writeMapKey(key)
isolateValueWrite {
writeCustomValue(value)
}
}
else if (!skipIfNull)
writeMapNullElement(key)
}
public inline fun <Writer : JsonWriter> Writer.writeMapElement(
key: String,
crossinline writeValue: Writer.() -> Unit,
) {
contract {
callsInPlace(writeValue, InvocationKind.EXACTLY_ONCE)
}
writeMapKey(key)
isolateValueWrite {
writeValue()
}
}
public fun JsonWriter.writeMapNullElement(key: String) {
writeMapKey(key)
writeNull()
}
public fun JsonWriter.writeNumberOrNull(value: Number?) {
writeOrNull(value, JsonWriter::writeNumber)
}
public inline fun <Writer : JsonWriter, Value : Any> Writer.writeOrNull(value: Value?, crossinline write: Writer.(value: Value) -> Unit) {
contract {
callsInPlace(write, InvocationKind.AT_MOST_ONCE)
}
if (value != null)
isolateValueWrite { write(value) }
else
writeNull()
}
public fun JsonWriter.writeShortOrNull(value: Short?) {
writeOrNull(value, JsonWriter::writeShort)
}
public fun JsonWriter.writeStringOrNull(value: String?) {
writeOrNull(value, JsonWriter::writeString)
}
public fun JsonWriter.writeValueOrNull(value: Any?) {
writeOrNull(value, JsonWriter::writeValue)
}
| apache-2.0 | f812c1554c56f42949bd809f2482189e | 21.745004 | 141 | 0.736698 | 3.867609 | false | false | false | false |
ttomsu/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CancelStageHandlerTest.kt | 1 | 5830 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.google.common.util.concurrent.MoreExecutors
import com.netflix.spinnaker.orca.DefaultStageResolver
import com.netflix.spinnaker.orca.TaskResolver
import com.netflix.spinnaker.orca.api.pipeline.CancellableStage
import com.netflix.spinnaker.orca.api.pipeline.graph.StageDefinitionBuilder
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.api.simplestage.SimpleStage
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.util.StageNavigator
import com.netflix.spinnaker.orca.q.CancelStage
import com.netflix.spinnaker.orca.q.singleTaskStage
import com.netflix.spinnaker.q.Queue
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
object CancelStageHandlerTest : SubjectSpek<CancelStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val executor = MoreExecutors.directExecutor()
val taskResolver: TaskResolver = TaskResolver(emptyList())
val stageNavigator: StageNavigator = mock()
val cancellableStage: CancelableStageDefinitionBuilder = mock()
val stageResolver = DefaultStageResolver(listOf(singleTaskStage, cancellableStage), emptyList<SimpleStage<Object>>())
subject(GROUP) {
CancelStageHandler(
queue,
repository,
DefaultStageDefinitionBuilderFactory(stageResolver),
stageNavigator,
executor,
taskResolver
)
}
fun resetMocks() = reset(queue, repository, cancellableStage)
describe("cancelling a stage") {
val pipeline = pipeline {
application = "whatever"
stage {
type = "cancellable"
refId = "1"
status = SUCCEEDED
}
stage {
type = "cancellable"
refId = "2a"
requisiteStageRefIds = listOf("1")
status = CANCELED
}
stage {
type = singleTaskStage.type
refId = "2b"
requisiteStageRefIds = listOf("1")
status = CANCELED
}
stage {
type = "cancellable"
refId = "2c"
requisiteStageRefIds = listOf("1")
status = TERMINAL
}
stage {
type = "cancellable"
refId = "3"
requisiteStageRefIds = listOf("2a", "2b", "2c")
status = NOT_STARTED
}
}
mapOf(
"2a" to "a cancellable stage that was canceled",
"2c" to "a cancellable stage that failed"
).forEach { refId, description ->
context(description) {
val message = CancelStage(PIPELINE, pipeline.id, pipeline.application, pipeline.stageByRef(refId).id)
beforeGroup {
whenever(cancellableStage.type) doReturn "cancellable"
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("invokes the cancel routine for the stage") {
verify(cancellableStage).cancel(pipeline.stageByRef(refId))
}
it("should not push any messages to the queue") {
verifyZeroInteractions(queue)
}
}
}
mapOf(
"1" to "a cancellable stage that completed already",
"2b" to "a running non-cancellable stage",
"3" to "a cancellable stage that did not start yet"
).forEach { refId, description ->
context(description) {
val message = CancelStage(PIPELINE, pipeline.id, pipeline.application, pipeline.stageByRef(refId).id)
beforeGroup {
whenever(cancellableStage.type) doReturn "cancellable"
whenever(repository.retrieve(pipeline.type, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("does not run any cancel routine") {
verify(cancellableStage, never()).cancel(any())
}
it("should not push any messages to the queue") {
verifyZeroInteractions(queue)
}
}
}
}
})
interface CancelableStageDefinitionBuilder : StageDefinitionBuilder, CancellableStage
| apache-2.0 | 147a512afed366ad0735b818bcd962ae | 33.702381 | 119 | 0.712178 | 4.522886 | false | false | false | false |
allotria/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab2.kt | 2 | 13809 | // 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.xdebugger.impl.ui
import com.intellij.debugger.ui.DebuggerContentInfo
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.ui.layout.LayoutAttractionPolicy
import com.intellij.execution.ui.layout.PlaceInGrid
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.TabListAction
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.ui.PersistentThreeComponentSplitter
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ToolWindowType
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.JBColor
import com.intellij.ui.content.ContentManagerEvent
import com.intellij.ui.content.ContentManagerListener
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.xdebugger.*
import com.intellij.xdebugger.impl.XDebugSessionImpl
import com.intellij.xdebugger.impl.actions.XDebuggerActions
import com.intellij.xdebugger.impl.frame.*
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree
import com.intellij.xdebugger.impl.ui.tree.nodes.XDebuggerTreeNode
import java.awt.Component
import java.awt.Container
import javax.swing.Icon
import javax.swing.LayoutFocusTraversalPolicy
import javax.swing.event.AncestorEvent
import javax.swing.event.AncestorListener
class XDebugSessionTab2(
session: XDebugSessionImpl,
icon: Icon?,
environment: ExecutionEnvironment?
) : XDebugSessionTab(session, icon, environment, false) {
companion object {
private const val threadsIsVisibleKey = "threadsIsVisibleKey"
private const val debuggerContentId = "DebuggerView"
}
private val project = session.project
private var threadsIsVisible
get() = PropertiesComponent.getInstance(project).getBoolean(threadsIsVisibleKey, true)
set(value) = PropertiesComponent.getInstance(project).setValue(threadsIsVisibleKey, value, true)
private val lifetime = Disposer.newDisposable()
private val splitter = PersistentThreeComponentSplitter(false, true, "DebuggerViewTab", lifetime, project, 0.35f, 0.3f)
private val xThreadsFramesView = XThreadsFramesView(myProject)
private var variables: XVariablesView? = null
private val toolWindow get() = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.DEBUG)
private val focusTraversalPolicy = MyFocusTraversalPolicy()
init {
// value from com.intellij.execution.ui.layout.impl.GridImpl
splitter.setMinSize(48)
splitter.isFocusCycleRoot = true
splitter.isFocusTraversalPolicyProvider = true
splitter.focusTraversalPolicy = focusTraversalPolicy
session.addSessionListener(object : XDebugSessionListener {
override fun sessionStopped() {
UIUtil.invokeLaterIfNeeded {
splitter.saveProportions()
Disposer.dispose(lifetime)
}
}
})
project.messageBus.connect(lifetime).subscribe(XDebuggerManager.TOPIC, object : XDebuggerManagerListener {
override fun processStarted(debugProcess: XDebugProcess) {
UIUtil.invokeLaterIfNeeded {
if (debugProcess.session != null && debugProcess.session != session) {
splitter.saveProportions()
}
}
}
override fun currentSessionChanged(previousSession: XDebugSession?, currentSession: XDebugSession?) {
UIUtil.invokeLaterIfNeeded {
if (previousSession == session) {
splitter.saveProportions()
xThreadsFramesView.saveUiState()
}
else if (currentSession == session)
splitter.restoreProportions()
}
}
override fun processStopped(debugProcess: XDebugProcess) {
UIUtil.invokeLaterIfNeeded {
splitter.saveProportions()
xThreadsFramesView.saveUiState()
if (debugProcess.session == session)
Disposer.dispose(lifetime)
}
}
})
val ancestorListener = object : AncestorListener {
override fun ancestorAdded(event: AncestorEvent?) {
if (XDebuggerManager.getInstance(project).currentSession == session) {
splitter.restoreProportions()
}
}
override fun ancestorRemoved(event: AncestorEvent?) {
if (XDebuggerManager.getInstance(project).currentSession == session) {
splitter.saveProportions()
xThreadsFramesView.saveUiState()
}
}
override fun ancestorMoved(event: AncestorEvent?) {
}
}
toolWindow?.component?.addAncestorListener(ancestorListener)
Disposer.register(lifetime, Disposable {
toolWindow?.component?.removeAncestorListener(ancestorListener)
})
var oldToolWindowType: ToolWindowType? = null
project.messageBus.connect(lifetime).subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
if (oldToolWindowType == toolWindow?.type) return
setHeaderState()
oldToolWindowType = toolWindow?.type
}
})
}
override fun getWatchesContentId() = debuggerContentId
override fun getFramesContentId() = debuggerContentId
override fun addVariablesAndWatches(session: XDebugSessionImpl) {
val variablesView: XVariablesView?
val watchesView: XVariablesView?
val layoutDisposable = Disposer.newDisposable(ui.contentManager, "debugger layout disposable")
if (isWatchesInVariables) {
variablesView = XWatchesViewImpl2(session, true, true, layoutDisposable)
registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView)
variables = variablesView
watchesView = null
myWatchesView = variablesView
} else {
variablesView = XVariablesView(session)
registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView)
variables = variablesView
watchesView = XWatchesViewImpl2(session, false, true, layoutDisposable)
registerView(DebuggerContentInfo.WATCHES_CONTENT, watchesView)
myWatchesView = watchesView
}
splitter.apply {
innerComponent = variablesView.panel
lastComponent = watchesView?.panel
}
UIUtil.removeScrollBorder(splitter)
splitter.revalidate()
splitter.repaint()
updateTraversalPolicy()
}
private fun updateTraversalPolicy() {
focusTraversalPolicy.components = getComponents().asSequence().toList()
}
override fun initDebuggerTab(session: XDebugSessionImpl) {
val framesView = xThreadsFramesView
registerView(DebuggerContentInfo.FRAME_CONTENT, framesView)
framesView.setThreadsVisible(threadsIsVisible)
splitter.firstComponent = xThreadsFramesView.mainPanel
addVariablesAndWatches(session)
val name = debuggerContentId
val content = myUi.createContent(name, splitter, XDebuggerBundle.message("xdebugger.debugger.tab.title"), AllIcons.Toolwindows.ToolWindowDebugger, framesView.defaultFocusedComponent).apply {
isCloseable = false
}
myUi.addContent(content, 0, PlaceInGrid.left, false)
ui.defaults.initContentAttraction(debuggerContentId, XDebuggerUIConstants.LAYOUT_VIEW_BREAKPOINT_CONDITION, LayoutAttractionPolicy.FocusOnce())
toolWindow?.let {
val contentManager = it.contentManager
val listener = object : ContentManagerListener {
override fun contentAdded(event: ContentManagerEvent) {
setHeaderState()
}
override fun contentRemoved(event: ContentManagerEvent) {
setHeaderState()
}
}
contentManager.addContentManagerListener(listener)
Disposer.register(lifetime, Disposable {
contentManager.removeContentManagerListener(listener)
})
}
setHeaderState()
}
private fun getComponents(): Iterator<Component> {
return iterator {
if (threadsIsVisible)
yield(xThreadsFramesView.threads)
yield(xThreadsFramesView.frames)
val vars = variables ?: return@iterator
yield(vars.defaultFocusedComponent)
if (!isWatchesInVariables)
yield(myWatchesView.defaultFocusedComponent)
}
}
private fun setHeaderState() {
toolWindow?.let { toolWindow ->
if (toolWindow !is ToolWindowEx) return@let
val singleContent = toolWindow.contentManager.contents.singleOrNull()
val headerVisible = toolWindow.isHeaderVisible
val topRightToolbar = DefaultActionGroup().apply {
if (headerVisible) return@apply
addAll(toolWindow.decorator.headerToolbar.actions.filter { it != null && it !is TabListAction })
}
myUi.options.setTopRightToolbar(topRightToolbar, ActionPlaces.DEBUGGER_TOOLBAR)
val topMiddleToolbar = DefaultActionGroup().apply {
if (singleContent == null || headerVisible) return@apply
add(object : AnAction(XDebuggerBundle.message("session.tab.close.debug.session"), null, AllIcons.Actions.Close) {
override fun actionPerformed(e: AnActionEvent) {
toolWindow.contentManager.removeContent(singleContent, true)
}
})
addSeparator()
}
myUi.options.setTopMiddleToolbar(topMiddleToolbar, ActionPlaces.DEBUGGER_TOOLBAR)
toolWindow.decorator.isHeaderVisible = headerVisible
if (toolWindow.decorator.isHeaderVisible) {
toolWindow.component.border = null
toolWindow.component.invalidate()
toolWindow.component.repaint()
} else if (toolWindow.component.border == null) {
UIUtil.addBorder(toolWindow.component, JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0))
}
}
}
private val ToolWindowEx.isHeaderVisible get() = (type != ToolWindowType.DOCKED) || contentManager.contents.singleOrNull() == null
override fun registerAdditionalActions(leftToolbar: DefaultActionGroup, topLeftToolbar: DefaultActionGroup, settings: DefaultActionGroup) {
leftToolbar.apply {
val constraints = Constraints(Anchor.BEFORE, XDebuggerActions.VIEW_BREAKPOINTS)
add(object : ToggleAction() {
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (threadsIsVisible != state) {
threadsIsVisible = state
updateTraversalPolicy()
}
xThreadsFramesView.setThreadsVisible(state)
Toggleable.setSelected(e.presentation, state)
}
override fun isSelected(e: AnActionEvent) = threadsIsVisible
override fun update(e: AnActionEvent) {
e.presentation.icon = AllIcons.Actions.SplitVertically
if (threadsIsVisible) {
e.presentation.text = XDebuggerBundle.message("session.tab.hide.threads.view")
}
else {
e.presentation.text = XDebuggerBundle.message("session.tab.show.threads.view")
}
setSelected(e, threadsIsVisible)
}
}, constraints)
add(ActionManager.getInstance().getAction(XDebuggerActions.FRAMES_TOP_TOOLBAR_GROUP), constraints)
add(Separator.getInstance(), constraints)
}
super.registerAdditionalActions(leftToolbar, settings, topLeftToolbar)
}
override fun dispose() {
Disposer.dispose(lifetime)
super.dispose()
}
class MyFocusTraversalPolicy : LayoutFocusTraversalPolicy() {
var components: List<Component> = listOf()
override fun getLastComponent(aContainer: Container?): Component {
if (components.isNotEmpty())
return components.last().prepare()
return super.getLastComponent(aContainer)
}
override fun getFirstComponent(aContainer: Container?): Component {
if (components.isNotEmpty())
return components.first().prepare()
return super.getFirstComponent(aContainer)
}
override fun getComponentAfter(aContainer: Container?, aComponent: Component?): Component {
if (aComponent == null)
return super.getComponentAfter(aContainer, aComponent)
val index = components.indexOf(aComponent)
if (index < 0 || index > components.lastIndex)
return super.getComponentAfter(aContainer, aComponent)
for (i in components.indices) {
val component = components[(index + i + 1) % components.size]
if (isEmpty(component)) continue
return component.prepare()
}
return components[index + 1].prepare()
}
override fun getComponentBefore(aContainer: Container?, aComponent: Component?): Component {
if (aComponent == null)
return super.getComponentBefore(aContainer, aComponent)
val index = components.indexOf(aComponent)
if (index < 0 || index > components.lastIndex)
return super.getComponentBefore(aContainer, aComponent)
for (i in components.indices) {
val component = components[(components.size + index - i - 1) % components.size]
if (isEmpty(component)) continue
return component.prepare()
}
return components[index - 1].prepare()
}
private fun Component.prepare(): Component {
if (this is XDebuggerTree && this.selectionCount == 0){
val child = root.children.firstOrNull() as? XDebuggerTreeNode ?: return this
selectionPath = child.path
}
return this
}
private fun isEmpty(component: Component): Boolean {
return when (component) {
is XDebuggerThreadsList -> component.isEmpty
is XDebuggerFramesList -> component.isEmpty
is XDebuggerTree -> component.isEmpty
else -> false;
}
}
}
} | apache-2.0 | 6250d2a04a3ba44f50617b94c8fc571f | 34.684755 | 194 | 0.718155 | 5.228701 | false | false | false | false |
zdary/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/EntityStorageSerializationTest.kt | 2 | 7007 | // 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.workspaceModel.storage
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryTableId
import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryEntity
import com.intellij.workspaceModel.storage.entities.MySource
import com.intellij.workspaceModel.storage.entities.addSampleEntity
import com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageBuilderImpl
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl
import junit.framework.Assert.*
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
class EntityStorageSerializationTest {
@Test
fun `simple model serialization`() {
val builder = createEmptyBuilder()
builder.addSampleEntity("MyEntity")
SerializationRoundTripChecker.verifyPSerializationRoundTrip(builder.toStorage(), VirtualFileUrlManagerImpl())
}
@Test
fun `serialization with version changing`() {
val builder = createEmptyBuilder()
builder.addSampleEntity("MyEntity")
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl())
val deserializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl())
.also { it.serializerDataFormatVersion = "XYZ" }
val stream = ByteArrayOutputStream()
serializer.serializeCache(stream, builder.toStorage())
val byteArray = stream.toByteArray()
val deserialized = (deserializer.deserializeCache(ByteArrayInputStream(byteArray)) as? WorkspaceEntityStorageBuilderImpl)?.toStorage()
assertNull(deserialized)
}
@Test
fun `serializer version`() {
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl())
val kryo = serializer.createKryo()
val registration = (10..1_000).mapNotNull { kryo.getRegistration(it) }.joinToString(separator = "\n")
assertEquals("Have you changed kryo registration? Update the version number! (And this test)", expectedKryoRegistration, registration)
}
@Test
fun `serialize empty lists`() {
val virtualFileManager = VirtualFileUrlManagerImpl()
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager)
val builder = createEmptyBuilder()
// Do not replace ArrayList() with emptyList(). This must be a new object for this test
builder.addLibraryEntity("myName", LibraryTableId.ProjectLibraryTableId, ArrayList(), ArrayList(), MySource)
val stream = ByteArrayOutputStream()
serializer.serializeCache(stream, builder.toStorage())
}
@Test
fun `serialize abstract`() {
val virtualFileManager = VirtualFileUrlManagerImpl()
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager)
val builder = createEmptyBuilder()
builder.addSampleEntity("myString")
val stream = ByteArrayOutputStream()
val result = serializer.serializeCache(stream, builder.toStorage())
assertTrue(result is SerializationResult.Success)
}
@Test
fun `read broken cache`() {
val virtualFileManager = VirtualFileUrlManagerImpl()
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), virtualFileManager)
val builder = createEmptyBuilder()
builder.addSampleEntity("myString")
val stream = ByteArrayOutputStream()
serializer.serializeCache(stream, builder.toStorage())
// Remove random byte from a serialised store
val inputStream = stream.toByteArray().filterIndexed { i, _ -> i != 3 }.toByteArray().inputStream()
val result = serializer.deserializeCache(inputStream)
assertNull(result)
}
}
// Kotlin tip: Use the ugly ${'$'} to insert the $ into the multiline string
private val expectedKryoRegistration = """
[10, com.intellij.workspaceModel.storage.impl.EntityId]
[11, com.google.common.collect.HashMultimap]
[12, com.intellij.workspaceModel.storage.impl.ConnectionId]
[13, com.intellij.workspaceModel.storage.impl.ImmutableEntitiesBarrel]
[14, com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl${'$'}TypeInfo]
[15, java.util.ArrayList]
[16, java.util.HashMap]
[17, com.intellij.util.SmartList]
[18, java.util.LinkedHashMap]
[19, com.intellij.workspaceModel.storage.impl.containers.BidirectionalMap]
[20, com.intellij.workspaceModel.storage.impl.containers.BidirectionalSetMap]
[21, java.util.HashSet]
[22, com.intellij.util.containers.BidirectionalMultiMap]
[23, com.google.common.collect.HashBiMap]
[24, com.intellij.workspaceModel.storage.impl.containers.LinkedBidirectionalMap]
[25, it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap]
[26, it.unimi.dsi.fastutil.objects.ObjectOpenHashSet]
[27, it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap]
[28, java.util.Arrays${'$'}ArrayList]
[29, byte[]]
[30, com.intellij.workspaceModel.storage.impl.ImmutableEntityFamily]
[31, com.intellij.workspaceModel.storage.impl.RefsTable]
[32, com.intellij.workspaceModel.storage.impl.containers.ImmutableNonNegativeIntIntBiMap]
[33, com.intellij.workspaceModel.storage.impl.containers.ImmutableIntIntUniqueBiMap]
[34, com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex]
[35, com.intellij.workspaceModel.storage.impl.indices.EntityStorageInternalIndex]
[36, com.intellij.workspaceModel.storage.impl.containers.ImmutableNonNegativeIntIntMultiMap${'$'}ByList]
[37, int[]]
[38, kotlin.Pair]
[39, com.intellij.workspaceModel.storage.impl.indices.MultimapStorageIndex]
[40, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}AddEntity]
[41, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}RemoveEntity]
[42, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}ReplaceEntity]
[43, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}ChangeEntitySource]
[44, com.intellij.workspaceModel.storage.impl.ChangeEntry${'$'}ReplaceAndChangeSource]
[45, java.util.LinkedHashSet]
[46, java.util.Collections${'$'}UnmodifiableCollection]
[47, java.util.Collections${'$'}UnmodifiableSet]
[48, java.util.Collections${'$'}UnmodifiableRandomAccessList]
[49, java.util.Collections${'$'}UnmodifiableMap]
[50, java.util.Collections${'$'}EmptyList]
[51, java.util.Collections${'$'}EmptyMap]
[52, java.util.Collections${'$'}EmptySet]
[53, java.util.Collections${'$'}SingletonList]
[54, java.util.Collections${'$'}SingletonMap]
[55, java.util.Collections${'$'}SingletonSet]
[56, com.intellij.util.containers.ContainerUtilRt${'$'}EmptyList]
[57, com.intellij.util.containers.MostlySingularMultiMap${'$'}EmptyMap]
[58, com.intellij.util.containers.MultiMap${'$'}EmptyMap]
[59, kotlin.collections.EmptyMap]
[60, kotlin.collections.EmptyList]
[61, kotlin.collections.EmptySet]
""".trimIndent()
| apache-2.0 | 956e6c568eb9f302a716dc450e9dddda | 43.348101 | 140 | 0.773798 | 4.715343 | false | true | false | false |
zdary/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/issue/UnresolvedDependencyIssue.kt | 3 | 4811 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.issue
import com.intellij.build.BuildView
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.externalSystem.issue.quickfix.ReimportQuickFix.Companion.requestImport
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.runAsync
@ApiStatus.Internal
abstract class UnresolvedDependencyIssue(dependencyName: String) : BuildIssue {
override val title: String = "Could not resolve $dependencyName"
override fun getNavigatable(project: Project): Navigatable? = null
fun buildDescription(failureMessage: String?, isOfflineMode: Boolean, offlineModeQuickFixText: String): String {
val issueDescription = StringBuilder(failureMessage?.trim())
val noRepositoriesDefined = failureMessage?.contains("no repositories are defined") ?: false
issueDescription.append("\n\nPossible solution:\n")
when {
isOfflineMode && !noRepositoriesDefined -> issueDescription.append(
" - <a href=\"$offlineQuickFixId\">$offlineModeQuickFixText</a>\n")
else -> issueDescription.append(
" - Declare repository providing the artifact, see the documentation at $declaringRepositoriesLink\n")
}
return issueDescription.toString()
}
companion object {
internal const val offlineQuickFixId = "disable_offline_mode"
private const val declaringRepositoriesLink = "https://docs.gradle.org/current/userguide/declaring_repositories.html"
}
}
@ApiStatus.Experimental
class UnresolvedDependencySyncIssue(dependencyName: String,
failureMessage: String?,
projectPath: String,
isOfflineMode: Boolean) : UnresolvedDependencyIssue(dependencyName) {
override val quickFixes = if (isOfflineMode) listOf<BuildIssueQuickFix>(DisableOfflineAndReimport(projectPath)) else emptyList()
override val description: String = buildDescription(failureMessage, isOfflineMode, "Disable offline mode and reload the project")
inner class DisableOfflineAndReimport(private val projectPath: String) : BuildIssueQuickFix {
override val id = offlineQuickFixId
override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> {
GradleSettings.getInstance(project).isOfflineWork = false
return tryRerun(dataContext) ?: requestImport(project, projectPath, GradleConstants.SYSTEM_ID)
}
}
}
@ApiStatus.Experimental
class UnresolvedDependencyBuildIssue(dependencyName: String,
failureMessage: String?,
isOfflineMode: Boolean) : UnresolvedDependencyIssue(dependencyName) {
override val quickFixes = if (isOfflineMode) listOf<BuildIssueQuickFix>(DisableOfflineAndRerun()) else emptyList()
override val description: String = buildDescription(failureMessage, isOfflineMode, "Disable offline mode and rerun the build")
inner class DisableOfflineAndRerun : BuildIssueQuickFix {
override val id = offlineQuickFixId
override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> {
GradleSettings.getInstance(project).isOfflineWork = false
return tryRerun(dataContext) ?: CompletableFuture.completedFuture(null)
}
}
}
private fun tryRerun(dataContext: DataContext): CompletableFuture<*>? {
val environment = LangDataKeys.EXECUTION_ENVIRONMENT.getData(dataContext)
if (environment != null) {
return runAsync { ExecutionUtil.restart(environment) }
}
val restartActions = BuildView.RESTART_ACTIONS.getData(dataContext)
val reimportActionText = ExternalSystemBundle.message("action.refresh.project.text", GradleConstants.SYSTEM_ID.readableName)
restartActions?.find { it.templateText == reimportActionText }?.let { action ->
val actionEvent = AnActionEvent.createFromAnAction(action, null, "BuildView", dataContext)
action.update(actionEvent)
if (actionEvent.presentation.isEnabledAndVisible) {
return runAsync { action.actionPerformed(actionEvent) }
}
}
return null
} | apache-2.0 | 56d4561185a95ee40a95be370b6cdba4 | 50.191489 | 140 | 0.766784 | 5.162017 | false | false | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/utils/BlockPosUtils.kt | 1 | 1911 | package net.ndrei.teslacorelib.utils
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.BlockPos
/**
* Created by CF on 2017-07-06.
*/
object BlockPosUtils {
fun getCube(entityPos: BlockPos, facing: EnumFacing?, radius: Int, height: Int): BlockCube {
val pos1: BlockPos
var pos2: BlockPos
if (facing != null) {
if (facing == EnumFacing.UP) {
pos1 = entityPos
.offset(EnumFacing.EAST, radius)
.offset(EnumFacing.SOUTH, radius)
.up(1)
pos2 = entityPos
.offset(EnumFacing.WEST, radius)
.offset(EnumFacing.NORTH, radius)
.up(height)
} else if (facing == EnumFacing.DOWN) {
pos1 = entityPos
.offset(EnumFacing.EAST, radius)
.offset(EnumFacing.SOUTH, radius)
.down(1)
pos2 = entityPos
.offset(EnumFacing.WEST, radius)
.offset(EnumFacing.NORTH, radius)
.down(height)
} else {
// assume horizontal facing
val left = facing.rotateYCCW()
val right = facing.rotateY()
pos1 = entityPos
.offset(left, radius)
.offset(facing, 1)
pos2 = entityPos
.offset(right, radius)
.offset(facing, radius * 2 + 1)
}
} else {
pos1 = BlockPos(entityPos.x - radius, entityPos.y, entityPos.z - radius)
pos2 = BlockPos(entityPos.x + radius, entityPos.y, entityPos.z + radius)
}
pos2 = pos2.offset(EnumFacing.UP, height - 1)
return BlockCube(pos1, pos2)
}
} | mit | 0739d38d0e076a4543f0ba863cb0d614 | 35.769231 | 96 | 0.47933 | 4.765586 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/jvmStatic/propertyAccessorsCompanion.kt | 2 | 393 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
var result = "fail 2"
class Foo {
val b = { a }
val c = Runnable { result = a }
companion object {
@JvmStatic
private val a = "OK"
}
}
fun box(): String {
if (Foo().b() != "OK") return "fail 1"
Foo().c.run()
return result
}
| apache-2.0 | 2624b5f1cc883475d8cfcae5f9cb4c7d | 16.086957 | 72 | 0.562341 | 3.417391 | false | false | false | false |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesFilterComponent.kt | 1 | 4333 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.committed
import com.intellij.openapi.Disposable
import com.intellij.openapi.ui.ComponentValidator
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList
import com.intellij.ui.FilterComponent
import com.intellij.ui.LightColors
import com.intellij.ui.components.JBCheckBox
import com.intellij.util.containers.ContainerUtil.createLockFreeCopyOnWriteList
import com.intellij.util.ui.UIUtil.getTextFieldBackground
import java.awt.BorderLayout
import java.awt.event.ItemListener
import java.util.function.Supplier
import java.util.regex.PatternSyntaxException
import javax.swing.JComponent
import javax.swing.event.ChangeEvent
import javax.swing.event.ChangeListener
private typealias CommittedChangeListPredicate = (CommittedChangeList) -> Boolean
private val TEXT_FILTER_KEY = CommittedChangesFilterKey("text", CommittedChangesFilterPriority.TEXT)
class CommittedChangesFilterComponent :
FilterComponent("COMMITTED_CHANGES_FILTER_HISTORY", 20),
ChangeListFilteringStrategy,
Disposable {
private val listeners = createLockFreeCopyOnWriteList<ChangeListener>()
private val regexCheckBox = JBCheckBox(message("committed.changes.regex.title")).apply {
model.addItemListener(ItemListener { filter() })
}
private val regexValidator = ComponentValidator(this)
.withValidator(Supplier { validateRegex() })
.installOn(textEditor)
private var regex: Regex? = null
init {
add(regexCheckBox, BorderLayout.EAST)
}
private fun hasValidationErrors(): Boolean = regexValidator.validationInfo != null
private fun validateRegex(): ValidationInfo? {
if (!regexCheckBox.isSelected) return null
regex = null
val value = filter.takeUnless { it.isNullOrEmpty() } ?: return null
return try {
regex = Regex(value)
null
}
catch (e: PatternSyntaxException) {
ValidationInfo("Please enter a valid regex", textEditor)
}
}
override fun filter() {
regexValidator.revalidate()
val event = ChangeEvent(this)
listeners.forEach { it.stateChanged(event) }
}
override fun getKey(): CommittedChangesFilterKey = TEXT_FILTER_KEY
override fun getFilterUI(): JComponent? = null
override fun addChangeListener(listener: ChangeListener) {
listeners += listener
}
override fun removeChangeListener(listener: ChangeListener) {
listeners -= listener
}
override fun setFilterBase(changeLists: List<CommittedChangeList>) = Unit
override fun resetFilterBase() = Unit
override fun appendFilterBase(changeLists: List<CommittedChangeList>) = Unit
override fun filterChangeLists(changeLists: List<CommittedChangeList>): List<CommittedChangeList> {
val result = doFilter(changeLists)
textEditor.background = if (result.isEmpty() && changeLists.isNotEmpty()) LightColors.RED else getTextFieldBackground()
return result
}
private fun doFilter(changeLists: List<CommittedChangeList>): List<CommittedChangeList> {
if (hasValidationErrors()) return emptyList()
val predicate = createFilterPredicate() ?: return changeLists
return changeLists.filter(predicate)
}
private fun createFilterPredicate(): CommittedChangeListPredicate? =
if (regexCheckBox.isSelected) regex?.let { RegexPredicate(it) }
else filter.takeUnless { it.isNullOrBlank() }?.let { WordPredicate(it) }
}
private class RegexPredicate(private val regex: Regex) : CommittedChangeListPredicate {
override fun invoke(changeList: CommittedChangeList): Boolean =
regex.containsMatchIn(changeList.comment.orEmpty()) ||
regex.containsMatchIn(changeList.committerName.orEmpty()) ||
regex.containsMatchIn(changeList.number.toString())
}
private class WordPredicate(filter: String) : CommittedChangeListPredicate {
private val filterWords = filter.split(" ")
override fun invoke(changeList: CommittedChangeList): Boolean =
filterWords.any { word ->
changeList.comment.orEmpty().contains(word, true) ||
changeList.committerName.orEmpty().contains(word, true) ||
changeList.number.toString().contains(word)
}
} | apache-2.0 | fe52709f26e87b42fe3bf351c945a0aa | 34.818182 | 140 | 0.770367 | 4.782561 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt | 1 | 19109 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator
import org.jetbrains.kotlin.idea.core.isVisible
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
class DestructureInspection : IntentionBasedInspection<KtDeclaration>(
DestructureIntention::class,
{ element, _ ->
val usagesToRemove = DestructureIntention.collectUsagesToRemove(element)?.data
if (element is KtParameter) {
usagesToRemove != null &&
(usagesToRemove.any { it.declarationToDrop is KtDestructuringDeclaration } ||
usagesToRemove.filter { it.usagesToReplace.isNotEmpty() }.size > usagesToRemove.size / 2)
} else {
usagesToRemove?.any { it.declarationToDrop is KtDestructuringDeclaration } ?: false
}
}
)
class DestructureIntention : SelfTargetingRangeIntention<KtDeclaration>(
KtDeclaration::class.java,
KotlinBundle.lazyMessage("use.destructuring.declaration")
) {
override fun applyTo(element: KtDeclaration, editor: Editor?) {
val (usagesToRemove, removeSelectorInLoopRange) = collectUsagesToRemove(element) ?: return
val factory = KtPsiFactory(element)
val parent = element.parent
val (container, anchor) = if (parent is KtParameterList) parent.parent to null else parent to element
val validator = NewDeclarationNameValidator(
container = container, anchor = anchor, target = NewDeclarationNameValidator.Target.VARIABLES,
excludedDeclarations = usagesToRemove.map {
(it.declarationToDrop as? KtDestructuringDeclaration)?.entries ?: listOfNotNull(it.declarationToDrop)
}.flatten()
)
val names = ArrayList<String>()
val underscoreSupported = element.languageVersionSettings.supportsFeature(LanguageFeature.SingleUnderscoreForParameterName)
// For all unused we generate normal names, not underscores
val allUnused = usagesToRemove.all { (_, usagesToReplace, variableToDrop) ->
usagesToReplace.isEmpty() && variableToDrop == null
}
usagesToRemove.forEach { (descriptor, usagesToReplace, variableToDrop, name) ->
val suggestedName =
if (usagesToReplace.isEmpty() && variableToDrop == null && underscoreSupported && !allUnused) {
"_"
} else {
KotlinNameSuggester.suggestNameByName(name ?: descriptor.name.asString(), validator)
}
runWriteAction {
variableToDrop?.delete()
usagesToReplace.forEach {
it.replace(factory.createExpression(suggestedName))
}
}
names.add(suggestedName)
}
val joinedNames = names.joinToString()
when (element) {
is KtParameter -> {
val loopRange = (element.parent as? KtForExpression)?.loopRange
runWriteAction {
val type = element.typeReference?.let { ": ${it.text}" } ?: ""
element.replace(factory.createDestructuringParameter("($joinedNames)$type"))
if (removeSelectorInLoopRange && loopRange is KtDotQualifiedExpression) {
loopRange.replace(loopRange.receiverExpression)
}
}
}
is KtFunctionLiteral -> {
val lambda = element.parent as KtLambdaExpression
SpecifyExplicitLambdaSignatureIntention().applyTo(lambda, editor)
runWriteAction {
lambda.functionLiteral.valueParameters.singleOrNull()?.replace(
factory.createDestructuringParameter("($joinedNames)")
)
}
}
is KtVariableDeclaration -> {
val rangeAfterEq = PsiChildRange(element.initializer, element.lastChild)
val modifierList = element.modifierList
runWriteAction {
if (modifierList == null) {
element.replace(
factory.createDestructuringDeclarationByPattern(
"val ($joinedNames) = $0", rangeAfterEq
)
)
} else {
val rangeBeforeVal = PsiChildRange(element.firstChild, modifierList)
element.replace(
factory.createDestructuringDeclarationByPattern(
"$0:'@xyz' val ($joinedNames) = $1", rangeBeforeVal, rangeAfterEq
)
)
}
}
}
}
}
override fun applicabilityRange(element: KtDeclaration): TextRange? {
if (!element.isSuitableDeclaration()) return null
val usagesToRemove = collectUsagesToRemove(element)?.data ?: return null
if (usagesToRemove.isEmpty()) return null
return when (element) {
is KtFunctionLiteral -> element.lBrace.textRange
is KtNamedDeclaration -> element.nameIdentifier?.textRange
else -> null
}
}
companion object {
internal fun KtDeclaration.isSuitableDeclaration() = getUsageScopeElement() != null
private fun KtDeclaration.getUsageScopeElement(): PsiElement? {
val lambdaSupported = languageVersionSettings.supportsFeature(LanguageFeature.DestructuringLambdaParameters)
return when (this) {
is KtParameter -> {
val parent = parent
when {
parent is KtForExpression -> parent
parent.parent is KtFunctionLiteral -> if (lambdaSupported) parent.parent else null
else -> null
}
}
is KtProperty -> parent.takeIf { isLocal }
is KtFunctionLiteral -> if (!hasParameterSpecification() && lambdaSupported) this else null
else -> null
}
}
internal data class UsagesToRemove(val data: List<UsageData>, val removeSelectorInLoopRange: Boolean)
internal fun collectUsagesToRemove(declaration: KtDeclaration): UsagesToRemove? {
val context = declaration.analyze()
val variableDescriptor = when (declaration) {
is KtParameter -> context.get(BindingContext.VALUE_PARAMETER, declaration)
is KtFunctionLiteral -> context.get(BindingContext.FUNCTION, declaration)?.valueParameters?.singleOrNull()
is KtVariableDeclaration -> context.get(BindingContext.VARIABLE, declaration)
else -> null
} ?: return null
val variableType = variableDescriptor.type
if (variableType.isMarkedNullable) return null
val classDescriptor = variableType.constructor.declarationDescriptor as? ClassDescriptor ?: return null
val mapEntryClassDescriptor = classDescriptor.builtIns.mapEntry
val usageScopeElement = declaration.getUsageScopeElement() ?: return null
val nameToSearch = when (declaration) {
is KtParameter -> declaration.nameAsName
is KtVariableDeclaration -> declaration.nameAsName
else -> Name.identifier("it")
} ?: return null
// Note: list should contains properties in order to create destructuring declaration
val usagesToRemove = mutableListOf<UsageData>()
var noBadUsages = true
var removeSelectorInLoopRange = false
when {
DescriptorUtils.isSubclass(classDescriptor, mapEntryClassDescriptor) -> {
val forLoop = declaration.parent as? KtForExpression
if (forLoop != null) {
val loopRangeDescriptor = forLoop.loopRange.getResolvedCall(context)?.resultingDescriptor
if (loopRangeDescriptor != null) {
val loopRangeDescriptorOwner = loopRangeDescriptor.containingDeclaration
val mapClassDescriptor = classDescriptor.builtIns.map
if (loopRangeDescriptorOwner is ClassDescriptor &&
DescriptorUtils.isSubclass(loopRangeDescriptorOwner, mapClassDescriptor)
) {
removeSelectorInLoopRange = loopRangeDescriptor.name.asString().let { it == "entries" || it == "entrySet" }
}
}
}
listOf("key", "value").mapTo(usagesToRemove) {
UsageData(
descriptor = mapEntryClassDescriptor.unsubstitutedMemberScope.getContributedVariables(
Name.identifier(it), NoLookupLocation.FROM_BUILTINS
).single()
)
}
usageScopeElement.iterateOverMapEntryPropertiesUsages(
context,
nameToSearch,
variableDescriptor,
{ index, usageData -> noBadUsages = usagesToRemove[index].add(usageData, index) && noBadUsages },
{ noBadUsages = false }
)
}
classDescriptor.isData -> {
val valueParameters = classDescriptor.unsubstitutedPrimaryConstructor?.valueParameters ?: return null
valueParameters.mapTo(usagesToRemove) { UsageData(descriptor = it) }
val constructorParameterNameMap = mutableMapOf<Name, ValueParameterDescriptor>()
valueParameters.forEach { constructorParameterNameMap[it.name] = it }
usageScopeElement.iterateOverDataClassPropertiesUsagesWithIndex(
context,
nameToSearch,
variableDescriptor,
constructorParameterNameMap,
{ index, usageData -> noBadUsages = usagesToRemove[index].add(usageData, index) && noBadUsages },
{ noBadUsages = false }
)
}
else -> return null
}
if (!noBadUsages) return null
val droppedLastUnused = usagesToRemove.dropLastWhile { it.usagesToReplace.isEmpty() && it.declarationToDrop == null }
return if (droppedLastUnused.isEmpty()) {
UsagesToRemove(usagesToRemove, removeSelectorInLoopRange)
} else {
UsagesToRemove(droppedLastUnused, removeSelectorInLoopRange)
}
}
private fun PsiElement.iterateOverMapEntryPropertiesUsages(
context: BindingContext,
parameterName: Name,
variableDescriptor: VariableDescriptor,
process: (Int, SingleUsageData) -> Unit,
cancel: () -> Unit
) {
anyDescendantOfType<KtNameReferenceExpression> {
when {
it.getReferencedNameAsName() != parameterName -> false
it.getResolvedCall(context)?.resultingDescriptor != variableDescriptor -> false
else -> {
val applicableUsage = getDataIfUsageIsApplicable(it, context)
if (applicableUsage != null) {
val usageDescriptor = applicableUsage.descriptor
if (usageDescriptor == null) {
process(0, applicableUsage)
process(1, applicableUsage)
return@anyDescendantOfType false
}
when (usageDescriptor.name.asString()) {
"key", "getKey" -> {
process(0, applicableUsage)
return@anyDescendantOfType false
}
"value", "getValue" -> {
process(1, applicableUsage)
return@anyDescendantOfType false
}
}
}
cancel()
true
}
}
}
}
private fun PsiElement.iterateOverDataClassPropertiesUsagesWithIndex(
context: BindingContext,
parameterName: Name,
variableDescriptor: VariableDescriptor,
constructorParameterNameMap: Map<Name, ValueParameterDescriptor>,
process: (Int, SingleUsageData) -> Unit,
cancel: () -> Unit
) {
anyDescendantOfType<KtNameReferenceExpression> {
when {
it.getReferencedNameAsName() != parameterName -> false
it.getResolvedCall(context)?.resultingDescriptor != variableDescriptor -> false
else -> {
val applicableUsage = getDataIfUsageIsApplicable(it, context)
if (applicableUsage != null) {
val usageDescriptor = applicableUsage.descriptor
if (usageDescriptor == null) {
for (parameter in constructorParameterNameMap.values) {
process(parameter.index, applicableUsage)
}
return@anyDescendantOfType false
}
val parameter = constructorParameterNameMap[usageDescriptor.name]
if (parameter != null) {
process(parameter.index, applicableUsage)
return@anyDescendantOfType false
}
}
cancel()
true
}
}
}
}
private fun getDataIfUsageIsApplicable(dataClassUsage: KtReferenceExpression, context: BindingContext): SingleUsageData? {
val destructuringDecl = dataClassUsage.parent as? KtDestructuringDeclaration
if (destructuringDecl != null && destructuringDecl.initializer == dataClassUsage) {
return SingleUsageData(descriptor = null, usageToReplace = null, declarationToDrop = destructuringDecl)
}
val qualifiedExpression = dataClassUsage.getQualifiedExpressionForReceiver() ?: return null
val parent = qualifiedExpression.parent
when (parent) {
is KtBinaryExpression -> {
if (parent.operationToken in KtTokens.ALL_ASSIGNMENTS && parent.left == qualifiedExpression) return null
}
is KtUnaryExpression -> {
if (parent.operationToken == KtTokens.PLUSPLUS || parent.operationToken == KtTokens.MINUSMINUS) return null
}
}
val property = parent as? KtProperty // val x = d.y
if (property != null && property.isVar) return null
val descriptor = qualifiedExpression.getResolvedCall(context)?.resultingDescriptor ?: return null
if (!descriptor.isVisible(
dataClassUsage, qualifiedExpression.receiverExpression,
context, dataClassUsage.containingKtFile.getResolutionFacade()
)
) {
return null
}
return SingleUsageData(descriptor = descriptor, usageToReplace = qualifiedExpression, declarationToDrop = property)
}
internal data class SingleUsageData(
val descriptor: CallableDescriptor?,
val usageToReplace: KtExpression?,
val declarationToDrop: KtDeclaration?
)
internal data class UsageData(
val descriptor: CallableDescriptor,
val usagesToReplace: MutableList<KtExpression> = mutableListOf(),
var declarationToDrop: KtDeclaration? = null,
var name: String? = null
) {
// Returns true if data is successfully added, false otherwise
fun add(newData: SingleUsageData, componentIndex: Int): Boolean {
if (newData.declarationToDrop is KtDestructuringDeclaration) {
val destructuringEntries = newData.declarationToDrop.entries
if (componentIndex < destructuringEntries.size) {
if (declarationToDrop != null) return false
name = destructuringEntries[componentIndex].name ?: return false
declarationToDrop = newData.declarationToDrop
}
} else {
name = name ?: newData.declarationToDrop?.name
declarationToDrop = declarationToDrop ?: newData.declarationToDrop
}
newData.usageToReplace?.let { usagesToReplace.add(it) }
return true
}
}
}
} | apache-2.0 | 371aad8b30e623263fd4d9f2bb5b6474 | 47.625954 | 158 | 0.578837 | 6.764248 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/proxy/mirror/debugMetadata.kt | 1 | 4848 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine.proxy.mirror
import com.sun.jdi.ArrayReference
import com.sun.jdi.ObjectReference
import com.sun.jdi.StringReference
import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger
import org.jetbrains.kotlin.idea.debugger.evaluate.DefaultExecutionContext
class DebugMetadata private constructor(context: DefaultExecutionContext) :
BaseMirror<ObjectReference, MirrorOfDebugProbesImpl>("kotlin.coroutines.jvm.internal.DebugMetadataKt", context) {
private val getStackTraceElementMethod by MethodMirrorDelegate("getStackTraceElement", StackTraceElement(context))
private val getSpilledVariableFieldMappingMethod by MethodDelegate<ArrayReference>("getSpilledVariableFieldMapping",
"(Lkotlin/coroutines/jvm/internal/BaseContinuationImpl;)[Ljava/lang/String;")
val baseContinuationImpl = BaseContinuationImpl(context, this)
override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfDebugProbesImpl? =
throw IllegalStateException("Not meant to be mirrored.")
fun fetchContinuationStack(continuation: ObjectReference, context: DefaultExecutionContext): MirrorOfContinuationStack {
val coroutineStack = mutableListOf<MirrorOfStackFrame>()
var loopContinuation: ObjectReference? = continuation
while (loopContinuation != null) {
val continuationMirror = baseContinuationImpl.mirror(loopContinuation, context) ?: break
coroutineStack.add(MirrorOfStackFrame(loopContinuation, continuationMirror))
loopContinuation = continuationMirror.nextContinuation
}
return MirrorOfContinuationStack(continuation, coroutineStack)
}
fun getStackTraceElement(value: ObjectReference, context: DefaultExecutionContext) =
getStackTraceElementMethod.mirror(value, context)
fun getSpilledVariableFieldMapping(value: ObjectReference, context: DefaultExecutionContext) =
getSpilledVariableFieldMappingMethod.value(value, context)
companion object {
val log by logger
fun instance(context: DefaultExecutionContext): DebugMetadata? {
try {
return DebugMetadata(context)
}
catch (e: IllegalStateException) {
log.debug("Attempt to access DebugMetadata but none found.", e)
}
return null
}
}
}
class BaseContinuationImpl(context: DefaultExecutionContext, private val debugMetadata: DebugMetadata) :
BaseMirror<ObjectReference, MirrorOfBaseContinuationImpl>("kotlin.coroutines.jvm.internal.BaseContinuationImpl", context) {
private val getCompletion by MethodMirrorDelegate("getCompletion", this, "()Lkotlin/coroutines/Continuation;")
override fun fetchMirror(value: ObjectReference, context: DefaultExecutionContext): MirrorOfBaseContinuationImpl? {
val stackTraceElementMirror = debugMetadata.getStackTraceElement(value, context)
val fieldVariables = getSpilledVariableFieldMapping(value, context)
val completionValue = getCompletion.value(value, context)
val completion = if (completionValue != null && getCompletion.isCompatible(completionValue)) completionValue else null
val coroutineOwner =
if (completionValue != null && DebugProbesImplCoroutineOwner.instanceOf(completionValue)) completionValue else null
return MirrorOfBaseContinuationImpl(value, stackTraceElementMirror, fieldVariables, completion, coroutineOwner)
}
private fun getSpilledVariableFieldMapping(value: ObjectReference, context: DefaultExecutionContext): List<FieldVariable> {
val getSpilledVariableFieldMappingReference =
debugMetadata.getSpilledVariableFieldMapping(value, context) ?: return emptyList()
val length = getSpilledVariableFieldMappingReference.length() / 2
val fieldVariables = ArrayList<FieldVariable>()
for (index in 0 until length) {
val fieldVariable = getFieldVariableName(getSpilledVariableFieldMappingReference, index) ?: continue
fieldVariables.add(fieldVariable)
}
return fieldVariables
}
private fun getFieldVariableName(rawSpilledVariables: ArrayReference, index: Int): FieldVariable? {
val fieldName = (rawSpilledVariables.getValue(2 * index) as? StringReference)?.value() ?: return null
val variableName = (rawSpilledVariables.getValue(2 * index + 1) as? StringReference)?.value() ?: return null
return FieldVariable(fieldName, variableName)
}
}
| apache-2.0 | 0fb5ccad755f3bae2ad3daf4e2c40a82 | 54.090909 | 164 | 0.738861 | 5.933905 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/adapters/viewholders/DownvoterViewHolder.kt | 1 | 1403 | package io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders
import android.view.View
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Downvoter
import io.github.feelfreelinux.wykopmobilny.utils.toPrettyDate
import kotlinx.android.synthetic.main.downvoters_list_item.view.*
class DownvoterViewHolder(val view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) {
companion object {
const val BURY_REASON_DUPLICATE = 1
const val BURY_REASON_SPAM = 2
const val BURY_REASON_FAKE_INFO = 3
const val BURY_REASON_WRONG_CONTENT = 4
const val BURY_REASON_UNSUITABLE_CONTENT = 5
}
fun bindView(downvoter: Downvoter) {
view.authorHeaderView.setAuthorData(downvoter.author, downvoter.date.toPrettyDate())
view.reason_textview.text = when (downvoter.reason) {
BURY_REASON_DUPLICATE -> view.resources.getString(R.string.reason_duplicate)
BURY_REASON_SPAM -> view.resources.getString(R.string.reason_spam)
BURY_REASON_FAKE_INFO -> view.resources.getString(R.string.reason_fake_info)
BURY_REASON_WRONG_CONTENT -> view.resources.getString(R.string.reason_wrong_content)
BURY_REASON_UNSUITABLE_CONTENT -> view.resources.getString(R.string.reason_unsuitable_content)
else -> ""
}
}
} | mit | 606aa2a958d94ea0261dd61e4e1402a7 | 45.8 | 106 | 0.72345 | 3.997151 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/configuration/gradleModuleBuilderUtils.kt | 1 | 6155 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.configuration
import com.intellij.framework.addSupport.FrameworkSupportInModuleConfigurable
import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel
import com.intellij.openapi.externalSystem.model.project.ProjectId
import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalModuleBuilder
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCoreUtil
import com.intellij.openapi.roots.ModifiableModelsProvider
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.idea.extensions.gradle.GradleBuildScriptSupport
import org.jetbrains.kotlin.idea.extensions.gradle.RepositoryDescription
import org.jetbrains.kotlin.idea.extensions.gradle.SettingsScriptBuilder
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.UserDataProperty
import org.jetbrains.plugins.gradle.frameworkSupport.GradleFrameworkSupportProvider
import org.jetbrains.plugins.gradle.service.project.wizard.AbstractGradleModuleBuilder
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
internal var Module.gradleModuleBuilder: AbstractExternalModuleBuilder<*>? by UserDataProperty(Key.create("GRADLE_MODULE_BUILDER"))
private var Module.settingsScriptBuilder: SettingsScriptBuilder<out PsiFile>? by UserDataProperty(Key.create("SETTINGS_SCRIPT_BUILDER"))
internal fun findSettingsGradleFile(module: Module): VirtualFile? {
val contentEntryPath = module.gradleModuleBuilder?.contentEntryPath ?: return null
if (contentEntryPath.isEmpty()) return null
val contentRootDir = File(contentEntryPath)
val modelContentRootDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(contentRootDir) ?: return null
return modelContentRootDir.findChild(GradleConstants.SETTINGS_FILE_NAME)
?: modelContentRootDir.findChild(GradleConstants.KOTLIN_DSL_SETTINGS_FILE_NAME)
?: module.project.baseDir.findChild(GradleConstants.SETTINGS_FILE_NAME)
?: module.project.baseDir.findChild(GradleConstants.KOTLIN_DSL_SETTINGS_FILE_NAME)
}
class KotlinSettingsScriptBuilder(scriptFile: KtFile): SettingsScriptBuilder<KtFile>(scriptFile) {
override fun addPluginRepository(repository: RepositoryDescription) {
addPluginRepositoryExpression(repository.toKotlinRepositorySnippet())
}
override fun buildPsiFile(project: Project): KtFile {
return KtPsiFactory(project).createFile(build())
}
}
// Circumvent write actions and modify the file directly
// TODO: Get rid of this hack when IDEA API allows manipulation of settings script similarly to the main script itself
internal fun updateSettingsScript(module: Module, updater: (SettingsScriptBuilder<out PsiFile>) -> Unit) {
fun createScriptBuilder(module: Module): SettingsScriptBuilder<*>? {
val settingsGradleFile = findSettingsGradleFile(module)?.toPsiFile(module.project) ?: return null
for (extension in GradleBuildScriptSupport.EP_NAME.extensionList) {
return extension.createScriptBuilder(settingsGradleFile) ?: continue
}
return null
}
val storedSettingsBuilder = module.settingsScriptBuilder
val settingsBuilder = storedSettingsBuilder ?: createScriptBuilder(module) ?: return
if (storedSettingsBuilder == null) {
module.settingsScriptBuilder = settingsBuilder
}
updater(settingsBuilder)
}
internal fun flushSettingsGradleCopy(module: Module) {
try {
val settingsFile = findSettingsGradleFile(module)
val settingsScriptBuilder = module.settingsScriptBuilder
if (settingsScriptBuilder != null && settingsFile != null) {
// The module.project is not opened yet.
// Due to optimization in ASTDelegatePsiElement.getManager() and relevant ones,
// we have to take theOnlyOpenProject() for manipulations with tmp file
// (otherwise file will have one parent project and its elements will have other parent project,
// and we will get KT-29333 problem).
// TODO: get rid of file manipulations until project is opened
val project = ProjectCoreUtil.theOnlyOpenProject() ?: module.project
val tmpFile = settingsScriptBuilder.buildPsiFile(project)
CodeStyleManager.getInstance(project).reformat(tmpFile)
VfsUtil.saveText(settingsFile, tmpFile.text)
}
} finally {
module.gradleModuleBuilder = null
module.settingsScriptBuilder = null
}
}
class KotlinGradleFrameworkSupportInModuleConfigurable(
private val model: FrameworkSupportModel,
private val supportProvider: GradleFrameworkSupportProvider
) : FrameworkSupportInModuleConfigurable() {
override fun createComponent() = supportProvider.createComponent()
override fun addSupport(
module: Module,
rootModel: ModifiableRootModel,
modifiableModelsProvider: ModifiableModelsProvider
) {
val buildScriptData = AbstractGradleModuleBuilder.getBuildScriptData(module)
if (buildScriptData != null) {
val builder = model.moduleBuilder
val projectId = (builder as? AbstractGradleModuleBuilder)?.projectId ?: ProjectId(null, module.name, null)
try {
module.gradleModuleBuilder = builder as? AbstractExternalModuleBuilder<*>
supportProvider.addSupport(projectId, module, rootModel, modifiableModelsProvider, buildScriptData)
} finally {
flushSettingsGradleCopy(module)
}
}
}
} | apache-2.0 | 4137713c6dada1e5626710f51f405e50 | 49.876033 | 158 | 0.767994 | 5.238298 | false | false | false | false |
siosio/intellij-community | python/python-features-trainer/src/com/jetbrains/python/ift/lesson/run/PythonRunLessonsUtils.kt | 2 | 1261 | // 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.jetbrains.python.ift.lesson.run
import training.dsl.parseLessonSample
object PythonRunLessonsUtils {
const val demoConfigurationName = "sandbox"
val demoSample = parseLessonSample("""
def find_average(value):
check_input(value)
result = 0
for s in value:
<caret>result += <select id=1>validate_number(extract_number(remove_quotes(s)))</select>
<caret id=3/>return result
def prepare_values():
return ["'apple 1'", "orange 2", "'tomato 3'"]
def extract_number(s):
return int(<select id=2>s.split()[0]</select>)
def check_input(value):
if (value is None) or (len(value) == 0):
raise ValueError(value)
def remove_quotes(s):
if len(s) > 1 and s[0] == "'" and s[-1] == "'":
return s[1:-1]
return s
def validate_number(number):
if number < 0:
raise ValueError(number)
return number
average = find_average(prepare_values())
print("The average is ", average)
""".trimIndent())
}
| apache-2.0 | f6bda34d329453a973b7acd8f5124942 | 26.413043 | 140 | 0.587629 | 4.028754 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/countFilter/oneLambdaParameter.kt | 4 | 257 | val p0: () -> Int = { 31 }
val p1: (Int) -> Int = <warning descr="SSR">{ x -> x }</warning>
val p1b: (Int) -> Int = <warning descr="SSR">{ it }</warning>
val p2: (Int, Int) -> Int = { x, y -> x + y }
val p3: (Int, Int, Int) -> Int = { x, y, z -> x + y + z } | apache-2.0 | dcdc7bce6482c1bf98c58d9c8997ede6 | 50.6 | 64 | 0.474708 | 2.424528 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/asJava/methods/FirLightAccessorMethodForSymbol.kt | 2 | 7661 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.asJava
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightParameterListBuilder
import org.jetbrains.kotlin.asJava.builder.LightMemberOrigin
import org.jetbrains.kotlin.asJava.classes.METHOD_INDEX_FOR_GETTER
import org.jetbrains.kotlin.asJava.classes.METHOD_INDEX_FOR_SETTER
import org.jetbrains.kotlin.asJava.classes.lazyPub
import org.jetbrains.kotlin.asJava.elements.FirLightIdentifier
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.idea.asJava.parameters.FirLightSetterParameterForSymbol
import org.jetbrains.kotlin.idea.frontend.api.isValid
import org.jetbrains.kotlin.idea.frontend.api.symbols.*
import org.jetbrains.kotlin.idea.util.ifTrue
import org.jetbrains.kotlin.load.java.JvmAbi.getterName
import org.jetbrains.kotlin.load.java.JvmAbi.setterName
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtParameter
internal class FirLightAccessorMethodForSymbol(
private val propertyAccessorSymbol: KtPropertyAccessorSymbol,
private val containingPropertySymbol: KtPropertySymbol,
lightMemberOrigin: LightMemberOrigin?,
containingClass: FirLightClassBase,
private val isTopLevel: Boolean,
) : FirLightMethod(
lightMemberOrigin,
containingClass,
if (propertyAccessorSymbol is KtPropertyGetterSymbol) METHOD_INDEX_FOR_GETTER else METHOD_INDEX_FOR_SETTER
) {
private val isGetter: Boolean get() = propertyAccessorSymbol is KtPropertyGetterSymbol
private fun String.abiName() =
if (isGetter) getterName(this) else setterName(this)
private val _name: String by lazyPub {
propertyAccessorSymbol.getJvmNameFromAnnotation() ?: run {
val defaultName = containingPropertySymbol.name.identifier.let {
if (containingClass.isAnnotationType) it else it.abiName()
}
containingPropertySymbol.computeJvmMethodName(defaultName, containingClass, accessorSite)
}
}
override fun getName(): String = _name
override fun hasTypeParameters(): Boolean = false
override fun getTypeParameterList(): PsiTypeParameterList? = null
override fun getTypeParameters(): Array<PsiTypeParameter> = PsiTypeParameter.EMPTY_ARRAY
override fun isVarArgs(): Boolean = false
override val kotlinOrigin: KtDeclaration? =
(propertyAccessorSymbol.psi ?: containingPropertySymbol.psi) as? KtDeclaration
private val accessorSite
get() =
if (propertyAccessorSymbol is KtPropertyGetterSymbol) AnnotationUseSiteTarget.PROPERTY_GETTER
else AnnotationUseSiteTarget.PROPERTY_SETTER
//TODO Fix it when KtFirConstructorValueParameterSymbol be ready
private val isParameter: Boolean get() = containingPropertySymbol.psi.let { it == null || it is KtParameter }
private fun computeAnnotations(isPrivate: Boolean): List<PsiAnnotation> {
val nullabilityApplicable = isGetter &&
!isPrivate &&
!(isParameter && (containingClass.isAnnotationType || containingClass.isEnum))
val nullabilityType = if (nullabilityApplicable) containingPropertySymbol.annotatedType.type
.getTypeNullability(containingPropertySymbol, FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE)
else NullabilityType.Unknown
val annotationsFromProperty = containingPropertySymbol.computeAnnotations(
parent = this,
nullability = nullabilityType,
annotationUseSiteTarget = accessorSite,
)
val annotationsFromAccessor = propertyAccessorSymbol.computeAnnotations(
parent = this,
nullability = NullabilityType.Unknown,
annotationUseSiteTarget = null,
)
return annotationsFromProperty + annotationsFromAccessor
}
private fun computeModifiers(): Set<String> {
val isOverrideMethod = propertyAccessorSymbol.isOverride || containingPropertySymbol.isOverride
val isInterfaceMethod = containingClass.isInterface
val modifiers = mutableSetOf<String>()
containingPropertySymbol.computeModalityForMethod(
isTopLevel = isTopLevel,
suppressFinal = isOverrideMethod || isInterfaceMethod,
result = modifiers
)
val visibility = isOverrideMethod.ifTrue {
(containingClass as? FirLightClassForSymbol)
?.tryGetEffectiveVisibility(containingPropertySymbol)
?.toPsiVisibilityForMember(isTopLevel)
} ?: propertyAccessorSymbol.toPsiVisibilityForMember(isTopLevel)
modifiers.add(visibility)
if (containingPropertySymbol.hasJvmStaticAnnotation(accessorSite)) {
modifiers.add(PsiModifier.STATIC)
}
if (isInterfaceMethod) {
modifiers.add(PsiModifier.ABSTRACT)
}
return modifiers
}
private val _modifierList: PsiModifierList by lazyPub {
val modifiers = computeModifiers()
val annotations = computeAnnotations(modifiers.contains(PsiModifier.PRIVATE))
FirLightClassModifierList(this, modifiers, annotations)
}
override fun getModifierList(): PsiModifierList = _modifierList
override fun isConstructor(): Boolean = false
private val _isDeprecated: Boolean by lazyPub {
containingPropertySymbol.hasDeprecatedAnnotation(accessorSite)
}
override fun isDeprecated(): Boolean = _isDeprecated
private val _identifier: PsiIdentifier by lazyPub {
FirLightIdentifier(this, containingPropertySymbol)
}
override fun getNameIdentifier(): PsiIdentifier = _identifier
private val _returnedType: PsiType? by lazyPub {
if (!isGetter) return@lazyPub PsiType.VOID
return@lazyPub containingPropertySymbol.annotatedType.asPsiType(
context = containingPropertySymbol,
parent = this@FirLightAccessorMethodForSymbol,
phase = FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE
)
}
override fun getReturnType(): PsiType? = _returnedType
override fun equals(other: Any?): Boolean =
this === other ||
(other is FirLightAccessorMethodForSymbol &&
isGetter == other.isGetter &&
kotlinOrigin == other.kotlinOrigin &&
propertyAccessorSymbol == other.propertyAccessorSymbol)
override fun hashCode(): Int = kotlinOrigin.hashCode()
private val _parametersList by lazyPub {
val builder = LightParameterListBuilder(manager, language)
FirLightParameterForReceiver.tryGet(containingPropertySymbol, this)?.let {
builder.addParameter(it)
}
val propertyParameter = (propertyAccessorSymbol as? KtPropertySetterSymbol)?.parameter
if (propertyParameter != null) {
builder.addParameter(
FirLightSetterParameterForSymbol(
parameterSymbol = propertyParameter,
containingPropertySymbol = containingPropertySymbol,
containingMethod = this@FirLightAccessorMethodForSymbol
)
)
}
builder
}
override fun getParameterList(): PsiParameterList = _parametersList
override fun isValid(): Boolean = super.isValid() && propertyAccessorSymbol.isValid()
} | apache-2.0 | 1eb8393f5802f3cde1caf6e25ac7b980 | 38.90625 | 115 | 0.715833 | 5.799394 | false | false | false | false |
jwren/intellij-community | plugins/evaluation-plugin/core/src/com/intellij/cce/core/TokenProperties.kt | 1 | 4050 | package com.intellij.cce.core
import com.google.gson.*
import java.lang.reflect.Type
interface TokenProperties {
val tokenType: TypeProperty
val location: SymbolLocation
fun additionalProperty(name: String): String?
fun describe(): String
fun hasFeature(feature: String): Boolean
fun withFeatures(features: Set<String>): TokenProperties
interface Adapter<T> {
fun adapt(props: TokenProperties): T?
}
object JsonAdapter : JsonDeserializer<TokenProperties>, JsonSerializer<TokenProperties> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): TokenProperties {
return context.deserialize(json, SimpleTokenProperties::class.java)
}
override fun serialize(src: TokenProperties, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
return context.serialize(src)
}
}
companion object {
val UNKNOWN = SimpleTokenProperties.create(TypeProperty.UNKNOWN, SymbolLocation.UNKNOWN) {}
}
}
object PropertyAdapters {
internal const val LANGUAGE_PROPERTY = "lang"
object Jvm : Base<JvmProperties>("Jvm") {
override fun build(props: TokenProperties): JvmProperties = JvmProperties(props)
}
abstract class Base<T>(internal val language: String) : TokenProperties.Adapter<T> {
final override fun adapt(props: TokenProperties): T? {
return if (props.additionalProperty(LANGUAGE_PROPERTY) != language) null else build(props)
}
abstract fun build(props: TokenProperties): T
}
}
class JvmProperties(private val props: TokenProperties) : TokenProperties by props {
companion object {
const val STATIC = "isStatic"
const val PACKAGE = "packageName"
const val CONTAINING_CLASS = "containingClass"
fun create(tokenType: TypeProperty, location: SymbolLocation, init: Builder.() -> Unit): TokenProperties {
val builder = Builder()
builder.init()
return SimpleTokenProperties.create(tokenType, location) {
builder.isStatic?.let { put(STATIC, it.toString()) }
builder.packageName?.let { put(PACKAGE, it) }
builder.declaringClass?.let { put(CONTAINING_CLASS, it) }
put(PropertyAdapters.LANGUAGE_PROPERTY, PropertyAdapters.Jvm.language)
}
}
}
val isStatic: Boolean? = props.additionalProperty(STATIC) == "true"
val packageName: String? = props.additionalProperty(PACKAGE)
val containingClass: String? = props.additionalProperty(CONTAINING_CLASS)
class Builder {
var isStatic: Boolean? = null
var packageName: String? = null
var declaringClass: String? = null
}
}
class SimpleTokenProperties private constructor(
override val tokenType: TypeProperty,
override val location: SymbolLocation,
private val features: MutableSet<String>,
private val additional: Map<String, String>
) : TokenProperties {
companion object {
fun create(tokenType: TypeProperty, location: SymbolLocation, init: MutableMap<String, String>.() -> Unit): TokenProperties {
val props = mutableMapOf<String, String>()
props.init()
return SimpleTokenProperties(tokenType, location, mutableSetOf(), props)
}
}
override fun additionalProperty(name: String): String? {
return additional[name]
}
override fun describe(): String {
return buildString {
append("tokenType=$tokenType")
append(", location=$location")
if (additional.isNotEmpty()) {
append(additional.entries.sortedBy { it.key }.joinToString(separator = ", ", prefix = " | "))
}
}
}
override fun hasFeature(feature: String): Boolean = features.contains(feature)
override fun withFeatures(features: Set<String>): TokenProperties =
SimpleTokenProperties(tokenType, location, this.features.apply { addAll(features) }, additional)
}
enum class SymbolLocation {
PROJECT, LIBRARY, UNKNOWN
}
enum class TypeProperty {
KEYWORD,
VARIABLE,
LINE,
// TODO: consider constructors separately
TYPE_REFERENCE,
METHOD_CALL,
FIELD,
ARGUMENT_NAME,
PARAMETER_MEMBER,
UNKNOWN
}
| apache-2.0 | 24866e90460c6aea895e130ae8353224 | 29 | 129 | 0.719259 | 4.676674 | false | false | false | false |
intellij-solidity/intellij-solidity | src/test/kotlin/me/serce/solidity/lang/completion/SolMemberAccessCompletionTest.kt | 1 | 2901 | package me.serce.solidity.lang.completion
class SolMemberAccessCompletionTest : SolCompletionTestBase() {
fun testEmptyCompletion() = checkCompletion(hashSetOf("doSmth"), """
contract SomeContract {
function doSmth() public {
}
}
contract Test {
function doSmth(SomeContract c) {
c./*caret*/
}
}
""")
fun testFunctionCompletion() = checkCompletion(hashSetOf("doSmth3"), """
contract SomeContract {
function doSmth() public {
}
function doSmth3() public {
}
}
contract Test {
function doSmth(SomeContract c) {
c.doS/*caret*/
}
}
""")
fun testPublicStateVarCompletion() = checkCompletion(hashSetOf("smth", "smth2"), """
contract SomeContract {
uint public smth;
uint public smth2;
}
contract Test {
function doSmth(SomeContract c) {
c.sm/*caret*/
}
}
""", strict = true)
fun testOnlyPublicStateVarCompletion() = checkCompletion(hashSetOf("smthPublic1", "smthPublic2"), """
contract SomeContract {
uint smth;
uint public smthPublic1;
uint public smthPublic2;
}
contract Test {
function doSmth(SomeContract c) {
c.sm/*caret*/
}
}
""", strict = true)
fun testOnlyPublicFunctionCompletion() = checkCompletion(hashSetOf("doSmth1", "doSmth2"), """
contract SomeContract {
function doSmthInternal() internal {
}
function doSmthPrivate() private {
}
function doSmth1() public {
}
function doSmth2() public {
}
}
contract Test {
function doFunc(SomeContract c) {
c.doS/*caret*/
}
}
""", strict = true)
fun testOverridesOnlyOnce() {
InlineFile("""
contract BaseContract {
function doSmth1() public {
}
}
contract SomeContract is BaseContract {
function doSmth1() public {
}
function doSmth2() public {
}
}
contract Test {
function doFunc(SomeContract c) {
c.doS/*caret*/
}
}
""").withCaret()
val variants = myFixture.completeBasic()
.map { it.lookupString }
.groupBy { it }
.mapValues { it.value.size }
assertEquals(variants["doSmth1"], 1)
}
}
| mit | 15f6ecd14f68a4022f13bad3c1b520c5 | 23.175 | 103 | 0.460876 | 5.813627 | false | true | false | false |
chrhsmt/Sishen | app/src/main/java/com/chrhsmt/sisheng/AudioServiceMock.kt | 1 | 2062 | package com.chrhsmt.sisheng
import android.annotation.SuppressLint
import android.app.Activity
import com.chrhsmt.sisheng.exception.AudioServiceException
import com.chrhsmt.sisheng.point.Point
import com.chrhsmt.sisheng.point.SimplePointCalculator
import com.chrhsmt.sisheng.ui.Chart
/**
* Created by hkimura on 2017/10/30.
*/
class AudioServiceMock : AudioServiceInterface {
private val TAG: String = "AudioServiceMock"
private val activity: Activity
private val chart: Chart
private var isRunning: Boolean = false
constructor(chart: Chart, activity: Activity) {
this.activity = activity
this.chart = chart
}
override fun startAudioRecord() {
// NOP
}
override fun testPlay(fileName: String, path: String?, playback: Boolean, callback: Runnable?, async: Boolean, labelName: String) {
this.isRunning = true
}
override fun debugTestPlay(fileName: String, path: String, playback: Boolean, callback: Runnable?) {
}
override fun attemptPlay(fileName: String) {
this.isRunning = true
}
override fun stop() {
this.isRunning = false
}
@Throws(AudioServiceException::class)
override fun analyze() : Point {
return analyze("")
}
@Throws(AudioServiceException::class)
override fun analyze(klassName: String) : Point {
this.isRunning = true
Thread.sleep(1000 * 2)
this.isRunning = false
//throw AudioServiceException()
return Point(
80,
5.0,
5.0,
1,
null)
}
override fun clear() {
// NOP
}
override fun clearFrequencies() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun clearTestFrequencies() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isRunning(): Boolean {
return this.isRunning
}
} | mit | a23e563289eebb67fa3cbf6baa2a90d4 | 25.113924 | 135 | 0.642095 | 4.633708 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/semantics/SemanticsSort.kt | 3 | 7050 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.semantics
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.node.LayoutNode
import androidx.compose.ui.node.NodeCoordinator
import androidx.compose.ui.node.SemanticsModifierNode
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.util.fastForEach
import androidx.compose.ui.util.fastMap
// This part is a copy from ViewGroup#addChildrenForAccessibility.
@OptIn(ExperimentalComposeUiApi::class)
internal fun LayoutNode.findOneLayerOfSemanticsWrappersSortedByBounds(
list: MutableList<SemanticsModifierNode> = mutableListOf()
): List<SemanticsModifierNode> {
fun sortWithStrategy(holders: List<NodeLocationHolder>): List<NodeLocationHolder> {
// This is gross but the least risky solution. The current comparison
// strategy breaks transitivity but produces very good results. Coming
// up with a new strategy requires time which we do not have, so ...
return try {
NodeLocationHolder.comparisonStrategy = NodeLocationHolder.ComparisonStrategy.Stripe
holders.toMutableList().apply { sort() }
} catch (iae: IllegalArgumentException) {
// Note that in practice this occurs extremely rarely in a couple
// of pathological cases.
NodeLocationHolder.comparisonStrategy = NodeLocationHolder.ComparisonStrategy.Location
holders.toMutableList().apply { sort() }
}
}
if (!isAttached) {
return list
}
val holders = ArrayList<NodeLocationHolder>()
children.fastForEach {
if (it.isAttached) holders.add(NodeLocationHolder(this, it))
}
val sortedChildren = sortWithStrategy(holders).fastMap { it.node }
sortedChildren.fastForEach { child ->
val outerSemantics = child.outerSemantics
if (outerSemantics != null) {
list.add(outerSemantics)
} else {
child.findOneLayerOfSemanticsWrappersSortedByBounds(list)
}
}
return list
}
internal class NodeLocationHolder internal constructor(
internal val subtreeRoot: LayoutNode,
internal val node: LayoutNode
) : Comparable<NodeLocationHolder> {
internal companion object {
internal var comparisonStrategy = ComparisonStrategy.Stripe
}
internal enum class ComparisonStrategy { Stripe, Location }
private val location: Rect?
private val layoutDirection = subtreeRoot.layoutDirection
init {
val subtreeRootCoordinator = subtreeRoot.innerCoordinator
val coordinator = node.findCoordinatorToGetBounds()
location = if (subtreeRootCoordinator.isAttached && coordinator.isAttached) {
subtreeRootCoordinator.localBoundingBoxOf(coordinator)
} else {
null
}
}
override fun compareTo(other: NodeLocationHolder): Int {
if (location == null) {
// put the unattached nodes at last. This probably can save accessibility services time.
return 1
}
if (other.location == null) {
return -1
}
if (comparisonStrategy == ComparisonStrategy.Stripe) {
// First is above second.
if (location.bottom - other.location.top <= 0) {
return -1
}
// First is below second.
if (location.top - other.location.bottom >= 0) {
return 1
}
}
// We are ordering left-to-right, top-to-bottom.
if (layoutDirection == LayoutDirection.Ltr) {
val leftDifference = location.left - other.location.left
if (leftDifference != 0f) {
return if (leftDifference < 0) -1 else 1
}
} else { // RTL
val rightDifference = location.right - other.location.right
if (rightDifference != 0f) {
return if (rightDifference < 0) 1 else -1
}
}
// We are ordering left-to-right, top-to-bottom.
val topDifference = location.top - other.location.top
if (topDifference != 0f) {
return if (topDifference < 0) -1 else 1
}
// Find a child of each view with different screen bounds. If we get here, node and
// other.node must be attached.
val view1Bounds = node.findCoordinatorToGetBounds().boundsInRoot()
val view2Bounds = other.node.findCoordinatorToGetBounds().boundsInRoot()
val child1 = node.findNodeByPredicateTraversal {
val wrapper = it.findCoordinatorToGetBounds()
wrapper.isAttached && view1Bounds != wrapper.boundsInRoot()
}
val child2 = other.node.findNodeByPredicateTraversal {
val wrapper = it.findCoordinatorToGetBounds()
wrapper.isAttached && view2Bounds != wrapper.boundsInRoot()
}
// Compare the children recursively
if ((child1 != null) && (child2 != null)) {
val childHolder1 = NodeLocationHolder(subtreeRoot, child1)
val childHolder2 = NodeLocationHolder(other.subtreeRoot, child2)
return childHolder1.compareTo(childHolder2)
}
// If only one has a child, use that one
if (child1 != null) {
return 1
}
if (child2 != null) {
return -1
}
val zDifference = LayoutNode.ZComparator.compare(node, other.node)
if (zDifference != 0) {
return -zDifference
}
// Break tie somehow
return node.semanticsId - other.node.semanticsId
}
}
internal fun LayoutNode.findNodeByPredicateTraversal(
predicate: (LayoutNode) -> Boolean
): LayoutNode? {
if (predicate(this)) {
return this
}
children.fastForEach {
val result = it.findNodeByPredicateTraversal(predicate)
if (result != null) {
return result
}
}
return null
}
/**
* If this node has semantics, we use the semantics wrapper to get bounds. Otherwise, we use
* innerCoordinator because it seems the bounds after padding is the effective content.
*/
@OptIn(ExperimentalComposeUiApi::class)
internal fun LayoutNode.findCoordinatorToGetBounds(): NodeCoordinator {
return (outerMergingSemantics ?: outerSemantics)?.node?.coordinator ?: innerCoordinator
}
| apache-2.0 | a7b428d591e8410fc148eed6fbe1cf01 | 35.528497 | 100 | 0.659574 | 4.936975 | false | false | false | false |
androidx/androidx | compose/compiler/compiler-hosted/integration-tests/src/test/java/androidx/compose/compiler/plugins/kotlin/AbstractControlFlowTransformTests.kt | 3 | 2319 | /*
* 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.compiler.plugins.kotlin
import org.intellij.lang.annotations.Language
abstract class AbstractControlFlowTransformTests : AbstractIrTransformTest() {
protected fun controlFlow(
@Language("kotlin")
source: String,
expectedTransformed: String,
dumpTree: Boolean = false,
) = verifyComposeIrTransform(
"""
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.key
import androidx.compose.runtime.NonRestartableComposable
$source
""".trimIndent(),
expectedTransformed,
"""
import androidx.compose.runtime.Composable
inline class InlineClass(val value: Int)
fun used(x: Any?) {}
@Composable fun A() {}
@Composable fun A(x: Int) { }
@Composable fun B(): Boolean { return true }
@Composable fun B(x: Int): Boolean { return true }
@Composable fun R(): Int { return 10 }
@Composable fun R(x: Int): Int { return 10 }
@Composable fun P(x: Int) { }
@Composable fun Int.A() { }
@Composable fun L(): List<Int> { return listOf(1, 2, 3) }
@Composable fun W(content: @Composable () -> Unit) { content() }
@Composable inline fun IW(content: @Composable () -> Unit) { content() }
fun NA() { }
fun NB(): Boolean { return true }
fun NR(): Int { return 10 }
var a = 1
var b = 2
var c = 3
""".trimIndent(),
dumpTree = dumpTree,
)
}
| apache-2.0 | df46375665405e03fe78972c0efe0519 | 35.809524 | 84 | 0.607158 | 4.665996 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUMethod.kt | 2 | 5623 | // 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.uast.kotlin
import com.intellij.lang.jvm.JvmModifier
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.elements.isGetter
import org.jetbrains.kotlin.asJava.elements.isSetter
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.resolve.annotations.JVM_STATIC_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter
@ApiStatus.Internal
open class KotlinUMethod(
psi: PsiMethod,
final override val sourcePsi: KtDeclaration?,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UMethod, UAnchorOwner, PsiMethod by psi {
constructor(
psi: KtLightMethod,
givenParent: UElement?
) : this(psi, getKotlinMemberOrigin(psi), givenParent)
override val uastParameters: List<UParameter> by lz {
fun parameterOrigin(psiParameter: PsiParameter?): KtElement? = when (psiParameter) {
is KtLightElement<*, *> -> psiParameter.kotlinOrigin
is UastKotlinPsiParameter -> psiParameter.ktParameter
else -> null
}
val lightParams = psi.parameterList.parameters
val receiver = receiverTypeReference ?: return@lz lightParams.map { KotlinUParameter(it, parameterOrigin(it), this) }
val receiverLight = lightParams.firstOrNull() ?: return@lz emptyList()
val uParameters = SmartList<UParameter>(KotlinReceiverUParameter(receiverLight, receiver, this))
lightParams.drop(1).mapTo(uParameters) { KotlinUParameter(it, parameterOrigin(it), this) }
uParameters
}
override val psi: PsiMethod = unwrap<UMethod, PsiMethod>(psi)
override val javaPsi = psi
override fun getSourceElement() = sourcePsi ?: this
private val kotlinOrigin = getKotlinMemberOrigin(psi.originalElement) ?: sourcePsi
override fun getContainingFile(): PsiFile? {
kotlinOrigin?.containingFile?.let { return it }
return unwrapFakeFileForLightClass(psi.containingFile)
}
override fun getNameIdentifier() = UastLightIdentifier(psi, kotlinOrigin)
override val uAnnotations: List<UAnnotation> by lz {
// NB: we can't use sourcePsi.annotationEntries directly due to annotation use-site targets. The given `psi` as a light element,
// which spans regular function, property accessors, etc., is already built with targeted annotation.
baseResolveProviderService.getPsiAnnotations(psi).asSequence()
.filter { if (javaPsi.hasModifier(JvmModifier.STATIC)) !isJvmStatic(it) else true }
.mapNotNull { (it as? KtLightElement<*, *>)?.kotlinOrigin as? KtAnnotationEntry }
.map { baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this) }
.toList()
}
private val receiverTypeReference by lz {
when (sourcePsi) {
is KtCallableDeclaration -> sourcePsi
is KtPropertyAccessor -> sourcePsi.property
else -> null
}?.receiverTypeReference
}
override val uastAnchor: UIdentifier? by lz {
val identifierSourcePsi = when (val sourcePsi = sourcePsi) {
is PsiNameIdentifierOwner -> sourcePsi.nameIdentifier
is KtObjectDeclaration -> sourcePsi.getObjectKeyword()
is KtPropertyAccessor -> sourcePsi.namePlaceholder
else -> sourcePsi?.navigationElement
}
KotlinUIdentifier(nameIdentifier, identifierSourcePsi, this)
}
override val uastBody: UExpression? by lz {
if (kotlinOrigin?.canAnalyze() != true) return@lz null // EA-137193
val bodyExpression = when (sourcePsi) {
is KtFunction -> sourcePsi.bodyExpression
is KtPropertyAccessor -> sourcePsi.bodyExpression
is KtProperty -> when {
psi is KtLightMethod && psi.isGetter -> sourcePsi.getter?.bodyExpression
psi is KtLightMethod && psi.isSetter -> sourcePsi.setter?.bodyExpression
else -> null
}
else -> null
} ?: return@lz null
wrapExpressionBody(this, bodyExpression)
}
override val returnTypeReference: UTypeReferenceExpression? by lz {
(sourcePsi as? KtCallableDeclaration)?.typeReference?.let {
KotlinUTypeReferenceExpression(it, this) { javaPsi.returnType ?: UastErrorType }
}
}
companion object {
fun create(
psi: KtLightMethod,
givenParent: UElement?
): UMethod {
val kotlinOrigin = psi.kotlinOrigin
return when {
kotlinOrigin is KtConstructor<*> ->
KotlinConstructorUMethod(kotlinOrigin.containingClassOrObject, psi, givenParent)
kotlinOrigin is KtParameter && kotlinOrigin.getParentOfType<KtClass>(true)?.isAnnotation() == true ->
KotlinUAnnotationMethod(psi, givenParent)
else ->
KotlinUMethod(psi, givenParent)
}
}
private fun isJvmStatic(it: PsiAnnotation): Boolean = it.hasQualifiedName(JVM_STATIC_ANNOTATION_FQ_NAME.asString())
}
}
| apache-2.0 | 145f51f378e70971b42fbdfa24ccefc5 | 42.253846 | 158 | 0.688067 | 5.427606 | false | false | false | false |
GunoH/intellij-community | python/src/com/jetbrains/python/testing/PyRerunFailedTestsAction.kt | 8 | 9062 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.testing
import com.intellij.execution.ExecutionException
import com.intellij.execution.ExecutionResult
import com.intellij.execution.Executor
import com.intellij.execution.Location
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.RunConfigurationBase
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.target.TargetEnvironment
import com.intellij.execution.target.TargetEnvironmentRequest
import com.intellij.execution.target.value.TargetEnvironmentFunction
import com.intellij.execution.testframework.AbstractTestProxy
import com.intellij.execution.testframework.actions.AbstractRerunFailedTestsAction
import com.intellij.execution.testframework.sm.runner.SMTestLocator
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComponentContainer
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.concurrency.annotations.RequiresReadLock
import com.jetbrains.python.HelperPackage
import com.jetbrains.python.PyBundle
import com.jetbrains.python.run.AbstractPythonRunConfiguration
import com.jetbrains.python.run.CommandLinePatcher
import com.jetbrains.python.run.PythonScriptExecution
import com.jetbrains.python.run.PythonScriptTargetedCommandLineBuilder
import com.jetbrains.python.run.target.HelpersAwareTargetEnvironmentRequest
import java.util.function.Function
class PyRerunFailedTestsAction(componentContainer: ComponentContainer) : AbstractRerunFailedTestsAction(componentContainer) {
override fun getRunProfile(environment: ExecutionEnvironment): MyRunProfile? {
val model = model ?: return null
return MyTestRunProfile(model.properties.configuration as AbstractPythonRunConfiguration<*>)
}
private inner class MyTestRunProfile(configuration: RunConfigurationBase<*>) : MyRunProfile(configuration) {
override fun getModules(): Array<Module> = (peer as AbstractPythonRunConfiguration<*>).modules
@Throws(ExecutionException::class)
override fun getState(executor: Executor, env: ExecutionEnvironment): RunProfileState? {
val configuration = peer as AbstractPythonTestRunConfiguration<*>
// If configuration wants to take care about rerun itself
if (configuration is TestRunConfigurationReRunResponsible) {
// TODO: Extract method
val failedTestElements = mutableSetOf<PsiElement>()
for (proxy in getFailedTests(project)) {
val location = proxy.getLocation(project, GlobalSearchScope.allScope(project))
if (location != null) {
failedTestElements.add(location.psiElement)
}
}
return (configuration as TestRunConfigurationReRunResponsible).rerunTests(executor, env, failedTestElements)
}
val state = configuration.getState(executor, env) ?: return null
return FailedPythonTestCommandLineStateBase(configuration, env, state as PythonTestCommandLineStateBase<*>)
}
}
private inner class FailedPythonTestCommandLineStateBase(configuration: AbstractPythonTestRunConfiguration<*>,
env: ExecutionEnvironment?,
private val state: PythonTestCommandLineStateBase<*>)
: PythonTestCommandLineStateBase<AbstractPythonTestRunConfiguration<*>>(configuration, env) {
private val project: Project
init {
project = configuration.project
}
override fun getRunner(): HelperPackage = state.runner
override fun getTestLocator(): SMTestLocator? = state.testLocator
@Throws(ExecutionException::class)
override fun execute(executor: Executor, processStarter: PythonProcessStarter, vararg patchers: CommandLinePatcher): ExecutionResult {
// Insane rerun tests with out of spec.
if (testSpecs.isEmpty()) {
throw ExecutionException(PyBundle.message("runcfg.tests.cant_rerun"))
}
return super.execute(executor, processStarter, *patchers)
}
@Throws(ExecutionException::class)
override fun execute(executor: Executor, converter: PythonScriptTargetedCommandLineBuilder): ExecutionResult? {
// Insane rerun tests with out of spec.
if (testSpecs.isEmpty()) {
throw ExecutionException(PyBundle.message("runcfg.tests.cant_rerun"))
}
return super.execute(executor, converter)
}
/**
* *To be deprecated. The part of the legacy implementation based on [GeneralCommandLine].*
*/
override fun getTestSpecs(): List<String> {
// Method could be called on any thread (as any method of this class), and we need read action
return ReadAction.compute(ThrowableComputable<List<String>, RuntimeException> { getTestSpecImpl() })
}
override fun getTestSpecs(request: TargetEnvironmentRequest): List<TargetEnvironmentFunction<String>> =
ReadAction.compute(ThrowableComputable<List<TargetEnvironmentFunction<String>>, RuntimeException> {
getTestSpecImpl(request)
})
@RequiresReadLock
private fun getTestSpecImpl(): List<String> {
val failedTests = getFailedTests(project)
val failedTestLocations = getTestLocations(failedTests)
val result: List<String> =
if (configuration is PyRerunAwareConfiguration) {
(configuration as PyRerunAwareConfiguration).getTestSpecsForRerun(myConsoleProperties.scope, failedTestLocations)
}
else {
failedTestLocations.mapNotNull { configuration.getTestSpec(it.first, it.second) }
}
if (result.isEmpty()) {
val locations = failedTests.map { it.locationUrl }
LOG.warn("Can't resolve specs for the following tests: ${locations.joinToString(separator = ", ")}")
}
return result
}
@RequiresReadLock
private fun getTestSpecImpl(request: TargetEnvironmentRequest): List<TargetEnvironmentFunction<String>> {
val failedTests = getFailedTests(project)
val failedTestLocations = getTestLocations(failedTests)
val result: List<TargetEnvironmentFunction<String>> =
if (configuration is PyRerunAwareConfiguration) {
(configuration as PyRerunAwareConfiguration).getTestSpecsForRerun(request, myConsoleProperties.scope, failedTestLocations)
}
else {
failedTestLocations.mapNotNull { configuration.getTestSpec(request, it.first, it.second) }
}
if (result.isEmpty()) {
val locations = failedTests.map { it.locationUrl }
LOG.warn("Can't resolve specs for the following tests: ${locations.joinToString(separator = ", ")}")
}
return result
}
private fun getTestLocations(tests: List<AbstractTestProxy>): List<Pair<Location<*>, AbstractTestProxy>> {
val testLocations = mutableListOf<Pair<Location<*>, AbstractTestProxy>>()
for (test in tests) {
if (test.isLeaf) {
val location = test.getLocation(project, myConsoleProperties.scope)
if (location != null) {
testLocations.add(Pair.create(location, test))
}
}
}
return testLocations
}
override fun addAfterParameters(cmd: GeneralCommandLine) {
state.addAfterParameters(cmd)
}
override fun addBeforeParameters(cmd: GeneralCommandLine) {
state.addBeforeParameters(cmd)
}
override fun addBeforeParameters(testScriptExecution: PythonScriptExecution) {
state.addBeforeParameters(testScriptExecution)
}
override fun addAfterParameters(targetEnvironmentRequest: TargetEnvironmentRequest,
testScriptExecution: PythonScriptExecution) {
state.addAfterParameters(targetEnvironmentRequest, testScriptExecution)
}
override fun customizeEnvironmentVars(envs: Map<String, String>, passParentEnvs: Boolean) {
super.customizeEnvironmentVars(envs, passParentEnvs)
state.customizeEnvironmentVars(envs, passParentEnvs)
}
override fun customizePythonExecutionEnvironmentVars(helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest,
envs: Map<String, Function<TargetEnvironment, String>>,
passParentEnvs: Boolean) {
super.customizePythonExecutionEnvironmentVars(helpersAwareTargetRequest, envs, passParentEnvs)
state.customizePythonExecutionEnvironmentVars(helpersAwareTargetRequest, envs, passParentEnvs)
}
}
companion object {
private val LOG = logger<PyRerunFailedTestsAction>()
}
} | apache-2.0 | 111e1c065477aea199b00ce06e62e5b1 | 45.716495 | 140 | 0.738468 | 5.406921 | false | true | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/DocumentationBrowser.kt | 7 | 5913 | // 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.lang.documentation.ide.impl
import com.intellij.lang.documentation.DocumentationTarget
import com.intellij.lang.documentation.ide.DocumentationBrowserFacade
import com.intellij.lang.documentation.ide.ui.DocumentationUI
import com.intellij.lang.documentation.ide.ui.UISnapshot
import com.intellij.lang.documentation.impl.DocumentationRequest
import com.intellij.lang.documentation.impl.InternalLinkResult
import com.intellij.model.Pointer
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderEntry
import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService
import com.intellij.util.lateinitVal
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.*
import kotlin.coroutines.EmptyCoroutineContext
internal class DocumentationBrowser private constructor(
private val project: Project,
initialPage: DocumentationPage,
) : DocumentationBrowserFacade, Disposable {
var ui: DocumentationUI by lateinitVal()
private sealed class BrowserRequest {
class Load(val request: DocumentationRequest, val reset: Boolean) : BrowserRequest()
object Reload : BrowserRequest()
class Link(val url: String) : BrowserRequest()
class Restore(val snapshot: HistorySnapshot) : BrowserRequest()
}
private val myRequestFlow: MutableSharedFlow<BrowserRequest> = MutableSharedFlow(
replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
private val cs = CoroutineScope(EmptyCoroutineContext)
init {
cs.launch(CoroutineName("DocumentationBrowser requests")) {
myRequestFlow.collectLatest {
handleBrowserRequest(it)
}
}
}
override fun dispose() {
cs.cancel("DocumentationBrowser disposal")
myHistory.clear()
}
fun resetBrowser(request: DocumentationRequest) {
load(request, reset = true)
}
private fun load(request: DocumentationRequest, reset: Boolean) {
check(myRequestFlow.tryEmit(BrowserRequest.Load(request, reset)))
}
override fun reload() {
check(myRequestFlow.tryEmit(BrowserRequest.Reload))
}
fun navigateByLink(url: String) {
check(myRequestFlow.tryEmit(BrowserRequest.Link(url)))
}
private val myPageFlow = MutableStateFlow(initialPage)
val pageFlow: SharedFlow<DocumentationPage> = myPageFlow.asSharedFlow()
private var page: DocumentationPage
get() = myPageFlow.value
set(value) {
myPageFlow.value = value
}
override val targetPointer: Pointer<out DocumentationTarget> get() = page.request.targetPointer
private suspend fun handleBrowserRequest(request: BrowserRequest): Unit = when (request) {
is BrowserRequest.Load -> handleLoadRequest(request.request, request.reset)
is BrowserRequest.Reload -> page.loadPage()
is BrowserRequest.Link -> handleLink(request.url)
is BrowserRequest.Restore -> handleRestore(request.snapshot)
}
private suspend fun handleLoadRequest(request: DocumentationRequest, reset: Boolean) {
val page = withContext(Dispatchers.EDT) {
if (reset) {
myHistory.clear()
}
else {
myHistory.nextPage()
}
DocumentationPage(request).also {
[email protected] = it
}
}
page.loadPage()
}
private suspend fun handleLink(url: String) {
val targetPointer = this.targetPointer
val internalResult = try {
handleLink(project, targetPointer, url)
}
catch (e: IndexNotReadyException) {
return // normal situation, nothing to do
}
when (internalResult) {
is OrderEntry -> withContext(Dispatchers.EDT) {
if (internalResult.isValid) {
ProjectSettingsService.getInstance(project).openLibraryOrSdkSettings(internalResult)
}
}
InternalLinkResult.InvalidTarget -> {
// TODO ? target was invalidated
}
InternalLinkResult.CannotResolve -> withContext(Dispatchers.EDT) {
@Suppress("ControlFlowWithEmptyBody")
if (!openUrl(project, targetPointer, url)) {
// TODO ? can't resolve link to target & nobody can open the link
}
}
is InternalLinkResult.Request -> {
load(internalResult.request, reset = false)
}
is InternalLinkResult.Updater -> {
page.updatePage(internalResult.updater)
}
}
}
private suspend fun handleRestore(snapshot: HistorySnapshot) {
val page = snapshot.page
val restored = page.restorePage(snapshot.ui)
this.page = page
if (!restored) {
page.loadPage()
}
}
fun currentExternalUrl(): String? {
return page.currentContent?.links?.externalUrl
}
val history: DocumentationHistory get() = myHistory
private val myHistory = DocumentationBrowserHistory(::historySnapshot, ::restore)
private class HistorySnapshot(
val page: DocumentationPage,
val ui: UISnapshot,
)
private fun historySnapshot(): HistorySnapshot {
return HistorySnapshot(page, ui.uiSnapshot())
}
private fun restore(snapshot: HistorySnapshot) {
check(myRequestFlow.tryEmit(BrowserRequest.Restore(snapshot)))
}
companion object {
fun createBrowser(project: Project, initialRequest: DocumentationRequest): DocumentationBrowser {
val browser = DocumentationBrowser(project, DocumentationPage(request = initialRequest))
browser.reload() // init loading
return browser
}
/**
* @return `true` if a loaded page has some content,
* or `false` if a loaded page is empty
*/
suspend fun DocumentationBrowser.waitForContent(): Boolean {
return pageFlow.first().waitForContent()
}
}
}
| apache-2.0 | 9e7cf200531fe0e9abd5e8c7319fd42c | 30.285714 | 120 | 0.727042 | 4.830882 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToScopeIntention.kt | 1 | 13876 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.java.refactoring.JavaRefactoringBundle
import com.intellij.openapi.editor.Editor
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.ConvertToScopeIntention.ScopeFunction.*
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.siblings
sealed class ConvertToScopeIntention(private val scopeFunction: ScopeFunction) : SelfTargetingIntention<KtExpression>(
KtExpression::class.java,
KotlinBundle.lazyMessage("convert.to.0", scopeFunction.functionName)
) {
enum class ScopeFunction(val functionName: String, val isParameterScope: Boolean) {
ALSO(functionName = "also", isParameterScope = true),
APPLY(functionName = "apply", isParameterScope = false),
RUN(functionName = "run", isParameterScope = false),
WITH(functionName = "with", isParameterScope = false);
val receiver = if (isParameterScope) "it" else "this"
}
private data class RefactoringTargetAndItsValueExpression(
val targetElement: PsiElement,
val targetElementValue: PsiElement
)
private data class ScopedFunctionCallAndBlock(
val scopeFunctionCall: KtExpression,
val block: KtBlockExpression
)
override fun isApplicableTo(element: KtExpression, caretOffset: Int) = tryApplyTo(element, dryRun = true)
override fun applyTo(element: KtExpression, editor: Editor?) {
if (!tryApplyTo(element, dryRun = false)) {
val message = RefactoringBundle.getCannotRefactorMessage(
JavaRefactoringBundle.message("refactoring.is.not.supported.in.the.current.context", text)
)
CommonRefactoringUtil.showErrorHint(element.project, editor, message, text, null)
}
}
private fun KtExpression.tryGetExpressionToApply(referenceName: String): KtExpression? {
val childOfBlock = PsiTreeUtil.findFirstParent(this) {
it.parent is KtBlockExpression
} as? KtExpression ?: return null
return if (childOfBlock is KtProperty || childOfBlock.isTarget(referenceName)) childOfBlock else null
}
private fun tryApplyTo(element: KtExpression, dryRun: Boolean): Boolean {
val invalidElementToRefactoring = when (element) {
is KtProperty -> !element.isLocal
is KtCallExpression -> false
is KtDotQualifiedExpression -> false
else -> true
}
if (invalidElementToRefactoring) return false
val (referenceElement, referenceName) = element.tryExtractReferenceName() ?: return false
val expressionToApply = element.tryGetExpressionToApply(referenceName) ?: return false
val (firstTarget, lastTarget) = expressionToApply.collectTargetElementsRange(referenceName, greedy = !dryRun) ?: return false
val refactoringTarget = tryGetFirstElementToRefactoring(expressionToApply, firstTarget) ?: return false
if (dryRun) return true
val psiFactory = KtPsiFactory(expressionToApply)
val (scopeFunctionCall, block) = createScopeFunctionCall(
psiFactory,
refactoringTarget.targetElement
) ?: return false
replaceReference(referenceElement, refactoringTarget.targetElementValue, lastTarget, psiFactory)
block.addRange(refactoringTarget.targetElementValue, lastTarget)
if (!scopeFunction.isParameterScope) {
removeRedundantThisQualifiers(block)
}
with(firstTarget) {
parent.addBefore(scopeFunctionCall, this)
parent.deleteChildRange(this, lastTarget)
}
return true
}
private fun removeRedundantThisQualifiers(block: KtBlockExpression) {
val thisDotSomethingExpressions = block.collectDescendantsOfType<KtDotQualifiedExpression> {
it.receiverExpression is KtThisExpression && it.selectorExpression !== null
}
thisDotSomethingExpressions.forEach { thisDotSomethingExpression ->
thisDotSomethingExpression.selectorExpression?.let { selector ->
thisDotSomethingExpression.replace(selector)
}
}
}
private fun tryGetFirstElementToRefactoring(expressionToApply: KtExpression, firstTarget: PsiElement)
: RefactoringTargetAndItsValueExpression? {
val property by lazy(LazyThreadSafetyMode.NONE) { expressionToApply.prevProperty() }
val propertyOrFirst = when (scopeFunction) {
ALSO, APPLY -> property
RUN, WITH -> firstTarget
} ?: return null
val isCorrectFirstOrProperty = when (scopeFunction) {
ALSO, APPLY -> propertyOrFirst is KtProperty && propertyOrFirst.name !== null && propertyOrFirst.initializer !== null
RUN -> propertyOrFirst is KtDotQualifiedExpression
WITH -> propertyOrFirst is KtDotQualifiedExpression
}
if (!isCorrectFirstOrProperty) return null
return RefactoringTargetAndItsValueExpression(propertyOrFirst, property?.nextSibling ?: firstTarget)
}
private fun replaceReference(element: PsiElement, firstTarget: PsiElement, lastTarget: PsiElement, psiFactory: KtPsiFactory) {
val replacement by lazy(LazyThreadSafetyMode.NONE) {
if (scopeFunction.isParameterScope)
psiFactory.createSimpleName(scopeFunction.receiver)
else
psiFactory.createThisExpression()
}
val searchParameters = KotlinReferencesSearchParameters(
element, element.useScope, ignoreAccessScope = false
)
val range = PsiTreeUtil.getElementsOfRange(firstTarget, lastTarget)
ReferencesSearch.search(searchParameters)
.mapNotNull { it.element as? KtNameReferenceExpression }
.filter { reference ->
range.any { rangeElement -> PsiTreeUtil.isAncestor(rangeElement, reference, /* strict = */ true) }
}
.forEach { referenceInRange ->
referenceInRange.replace(replacement)
}
}
private fun KtExpression.tryExtractReferenceName(): Pair<PsiElement, String>? {
return when (scopeFunction) {
ALSO, APPLY -> {
val property = prevProperty()
val name = property?.name
if (name !== null) property to name else null
}
RUN, WITH -> {
val receiver = (this as? KtDotQualifiedExpression)
?.let { getLeftMostReceiverExpression() } as? KtNameReferenceExpression
val declaration = receiver?.mainReference?.resolve()
val name = receiver?.getReferencedName()
if (declaration !== null && declaration !is PsiPackage && name !== null) declaration to name else null
}
}
}
private fun KtExpression.collectTargetElementsRange(referenceName: String, greedy: Boolean): Pair<PsiElement, PsiElement>? {
return when (scopeFunction) {
ALSO, APPLY -> {
val firstTarget = this as? KtProperty ?: this.prevProperty() ?: this
val lastTargetSequence = firstTarget.collectTargetElements(referenceName, forward = true)
val lastTarget = if (firstTarget === this)
if (greedy) lastTargetSequence.lastOrNull()
else lastTargetSequence.firstOrNull()
else
if (greedy) lastTargetSequence.lastWithPersistedElementOrNull(elementShouldPersist = this)
else lastTargetSequence.firstOrNull { this === it }
if (lastTarget !== null) firstTarget to lastTarget else null
}
RUN, WITH -> {
val firstTarget = collectTargetElements(referenceName, forward = false).lastOrNull() ?: this
val lastTarget =
if (greedy) collectTargetElements(referenceName, forward = true).lastOrNull() ?: this
else this
firstTarget to lastTarget
}
}
}
private fun KtExpression.collectTargetElements(referenceName: String, forward: Boolean): Sequence<PsiElement> =
siblings(forward, withItself = false)
.filter { it !is PsiWhiteSpace && it !is PsiComment && !(it is LeafPsiElement && it.elementType == KtTokens.SEMICOLON) }
.takeWhile { it.isTarget(referenceName) }
private fun PsiElement.isTarget(referenceName: String): Boolean {
when (this) {
is KtDotQualifiedExpression -> {
val callExpr = callExpression ?: return false
if (callExpr.lambdaArguments.isNotEmpty() ||
callExpr.valueArguments.any { it.text == scopeFunction.receiver }
) return false
val leftMostReceiver = getLeftMostReceiverExpression()
if (leftMostReceiver.text != referenceName) return false
if (leftMostReceiver.mainReference?.resolve() is PsiClass) return false
}
is KtCallExpression -> {
val valueArguments = this.valueArguments
if (valueArguments.none { it.getArgumentExpression()?.text == referenceName }) return false
if (lambdaArguments.isNotEmpty() || valueArguments.any { it.text == scopeFunction.receiver }) return false
}
is KtBinaryExpression -> {
val left = this.left ?: return false
val right = this.right ?: return false
if (left !is KtDotQualifiedExpression && left !is KtCallExpression
&& right !is KtDotQualifiedExpression && right !is KtCallExpression
) return false
if ((left is KtDotQualifiedExpression || left is KtCallExpression) && !left.isTarget(referenceName)) return false
if ((right is KtDotQualifiedExpression || right is KtCallExpression) && !right.isTarget(referenceName)) return false
}
else -> return false
}
return !anyDescendantOfType<KtNameReferenceExpression> { it.text == scopeFunction.receiver }
}
private fun KtExpression.prevProperty(): KtProperty? = PsiTreeUtil.findFirstParent(this) {
it.parent is KtBlockExpression
}
?.siblings(forward = false, withItself = true)
?.firstOrNull { it is KtProperty && it.isLocal } as? KtProperty
private fun createScopeFunctionCall(factory: KtPsiFactory, element: PsiElement): ScopedFunctionCallAndBlock? {
val scopeFunctionName = scopeFunction.functionName
val (scopeFunctionCall, callExpression) = when (scopeFunction) {
ALSO, APPLY -> {
if (element !is KtProperty) return null
val propertyName = element.name ?: return null
val initializer = element.initializer ?: return null
val initializerPattern = when (initializer) {
is KtDotQualifiedExpression, is KtCallExpression, is KtConstantExpression, is KtParenthesizedExpression -> initializer.text
else -> "(${initializer.text})"
}
val property = factory.createProperty(
name = propertyName,
type = element.typeReference?.text,
isVar = element.isVar,
initializer = "$initializerPattern.$scopeFunctionName {}"
)
val callExpression = (property.initializer as? KtDotQualifiedExpression)?.callExpression ?: return null
property to callExpression
}
RUN -> {
if (element !is KtDotQualifiedExpression) return null
val scopeFunctionCall = factory.createExpressionByPattern(
"$0.$scopeFunctionName {}",
element.getLeftMostReceiverExpression()
) as? KtQualifiedExpression ?: return null
val callExpression = scopeFunctionCall.callExpression ?: return null
scopeFunctionCall to callExpression
}
WITH -> {
if (element !is KtDotQualifiedExpression) return null
val scopeFunctionCall = factory.createExpressionByPattern(
"$scopeFunctionName($0) {}",
element.getLeftMostReceiverExpression()
) as? KtCallExpression ?: return null
scopeFunctionCall to scopeFunctionCall
}
}
val body = callExpression.lambdaArguments
.firstOrNull()
?.getLambdaExpression()
?.bodyExpression
?: return null
return ScopedFunctionCallAndBlock(scopeFunctionCall, body)
}
}
class ConvertToAlsoIntention : ConvertToScopeIntention(ALSO)
class ConvertToApplyIntention : ConvertToScopeIntention(APPLY)
class ConvertToRunIntention : ConvertToScopeIntention(RUN)
class ConvertToWithIntention : ConvertToScopeIntention(WITH)
| apache-2.0 | 95d27a08d6111a36731f7ce1605afe59 | 43.191083 | 158 | 0.656313 | 5.929915 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLineCommentToBlockCommentIntention.kt | 4 | 2588 | // 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.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespace
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespace
class ConvertLineCommentToBlockCommentIntention : SelfTargetingIntention<PsiComment>(
PsiComment::class.java,
KotlinBundle.lazyMessage("replace.with.block.comment")
) {
override fun isApplicableTo(element: PsiComment, caretOffset: Int): Boolean = element.isEndOfLineComment()
override fun applyTo(element: PsiComment, editor: Editor?) {
val project = element.project
var firstComment = element
while (true) {
firstComment = firstComment.prevComment() ?: break
}
val indent = (firstComment.prevSibling as? PsiWhiteSpace)?.text?.reversed()?.takeWhile { it == ' ' || it == '\t' } ?: ""
val comments = mutableListOf(firstComment)
var nextComment = firstComment
while (true) {
nextComment = nextComment.nextComment() ?: break
comments.add(nextComment)
}
val blockComment = if (comments.size == 1)
"/* ${comments.first().commentText()} */"
else
comments.joinToString(separator = "\n", prefix = "/*\n", postfix = "\n$indent*/") {
"$indent${it.commentText()}"
}
comments.drop(1).forEach {
(it.prevSibling as? PsiWhiteSpace)?.delete()
it.delete()
}
firstComment.replace(KtPsiFactory(project).createComment(blockComment))
}
}
private fun PsiElement.isEndOfLineComment() = node.elementType == KtTokens.EOL_COMMENT
private fun PsiComment.commentText() = text.substring(2).replace("/*", "/ *").replace("*/", "* /").trim()
private fun PsiComment.nextComment(): PsiComment? = (getNextSiblingIgnoringWhitespace() as? PsiComment)?.takeIf { it.isEndOfLineComment() }
private fun PsiComment.prevComment(): PsiComment? = (getPrevSiblingIgnoringWhitespace() as? PsiComment)?.takeIf { it.isEndOfLineComment() }
| apache-2.0 | 323388f23d98d379e640a5c176bd3d14 | 40.741935 | 158 | 0.702859 | 4.696915 | false | false | false | false |
smmribeiro/intellij-community | platform/testFramework/src/com/intellij/util/io/impl/FileTextMatchers.kt | 9 | 1267 | // 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.util.io.impl
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.io.FileTextMatcher
object FileTextMatchers {
val exact = object : FileTextMatcher {
override fun matches(actualText: String, expectedText: String): Boolean =
actualText == expectedText
}
val lines = object : FileTextMatcher {
override fun matches(actualText: String, expectedText: String): Boolean =
actualText.lines() == expectedText.lines()
}
val ignoreBlankLines = object : FileTextMatcher {
override fun matches(actualText: String, expectedText: String): Boolean =
actualText.lines().filter { it.isNotBlank() } == expectedText.lines().filter { it.isNotBlank() }
}
val ignoreXmlFormatting = object : FileTextMatcher {
override fun matches(actualText: String, expectedText: String): Boolean {
val trimmed = expectedText.trim()
if (trimmed.startsWith('<') && trimmed.endsWith('>')) {
return JDOMUtil.areElementsEqual(JDOMUtil.load(actualText), JDOMUtil.load(expectedText))
}
return actualText == expectedText
}
}
}
| apache-2.0 | 61e7d1808a9ef08d2cc65d20051ed455 | 38.59375 | 158 | 0.718232 | 4.641026 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/ABaseTransformer.kt | 1 | 4569 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.sinyuk.fanfou.ui
import android.support.v4.view.ViewPager.PageTransformer
import android.view.View
abstract class ABaseTransformer : PageTransformer {
/**
* Indicates if the default animations of the view pager should be used.
*
* @return
*/
protected val isPagingEnabled: Boolean
get() = false
/**
* Called each [.transformPage].
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
protected abstract fun onTransform(page: View, position: Float)
/**
* Apply a property transformation to the given page. For most use cases, this method should not be overridden.
* Instead use [.transformPage] to perform typical transformations.
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
override fun transformPage(page: View, position: Float) {
onPreTransform(page, position)
onTransform(page, position)
onPostTransform(page, position)
}
/**
* If the position offset of a fragment is less than negative one or greater than one, returning true will set the
* fragment alpha to 0f. Otherwise fragment alpha is always defaulted to 1f.
*
* @return
*/
protected fun hideOffscreenPages(): Boolean {
return true
}
/**
* Called each [.transformPage] before {[.onTransform].
*
*
* The default implementation attempts to reset all view properties. This is useful when toggling transforms that do
* not modify the same page properties. For instance changing from a transformation that applies rotation to a
* transformation that fades can inadvertently leave a fragment stuck with a rotation or with some degree of applied
* alpha.
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
protected fun onPreTransform(page: View, position: Float) {
val width = page.width.toFloat()
page.rotationX = 0f
page.rotationY = 0f
page.rotation = 0f
page.scaleX = 1f
page.scaleY = 1f
page.pivotX = 0f
page.pivotY = 0f
page.translationY = 0f
page.translationX = if (isPagingEnabled) 0f else -width * position
if (hideOffscreenPages()) {
page.alpha = if (position <= -1f || position >= 1f) 0f else 1f
page.isEnabled = false
} else {
page.isEnabled = true
page.alpha = 1f
}
}
/**
* Called each [.transformPage] after [.onTransform].
*
* @param page
* Apply the transformation to this page
* @param position
* Position of page relative to the current front-and-center position of the pager. 0 is front and
* center. 1 is one full page position to the right, and -1 is one page position to the left.
*/
protected fun onPostTransform(page: View, position: Float) {}
companion object {
/**
* Same as [Math.min] without double casting, zero closest to infinity handling, or NaN support.
*
* @param val
* @param min
* @return
*/
fun min(value: Float, min: Float) = if (value < min) min else value
}
} | mit | 7f1d646748dc8a9ceb29363f3058840d | 33.104478 | 120 | 0.643905 | 4.306315 | false | false | false | false |
RADAR-CNS/RADAR-AndroidApplication | app/src/main/java/org/radarcns/detail/SourceRowView.kt | 1 | 7214 | /*
* Copyright 2017 The Hyve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.radarcns.detail
import android.app.AlertDialog
import android.content.Context
import android.content.SharedPreferences
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import org.radarbase.android.MainActivity
import org.radarbase.android.source.BaseSourceState
import org.radarbase.android.source.SourceProvider
import org.radarbase.android.source.SourceServiceConnection
import org.radarbase.android.source.SourceStatusListener
import org.radarbase.android.util.Boast
import org.radarbase.android.util.ChangeRunner
import org.radarcns.detail.MainActivityViewImpl.Companion.truncate
import org.slf4j.LoggerFactory
/**
* Displays a single source row.
*/
class SourceRowView internal constructor(
private val mainActivity: MainActivity,
provider: SourceProvider<*>, root: ViewGroup
) {
private val connection: SourceServiceConnection<*> = provider.connection
private val mStatusIcon: View
private val mBatteryLabel: ImageView
private val sourceNameLabel: TextView
private val devicePreferences: SharedPreferences
private val filter = ChangeRunner("")
private var sourceState: BaseSourceState? = null
private var sourceName: String? = null
private val batteryLevelCache = ChangeRunner<Float>()
private val sourceNameCache = ChangeRunner<String>()
private val statusCache = ChangeRunner<SourceStatusListener.Status>()
private val splitRegex = this.mainActivity.getString(R.string.filter_split_regex).toRegex()
init {
devicePreferences = this.mainActivity.getSharedPreferences("device." + connection.serviceClassName, Context.MODE_PRIVATE)
logger.info("Creating source row for provider {} and connection {}", provider, connection)
val inflater = this.mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.activity_overview_source_row, root)
(root.getChildAt(root.childCount - 1) as TableRow).apply {
mStatusIcon = findViewById(R.id.status_icon)
sourceNameLabel = findViewById(R.id.sourceNameLabel)
mBatteryLabel = findViewById(R.id.batteryStatusLabel)
findViewById<Button>(R.id.filterSourceButton).apply {
if (provider.isFilterable) {
setOnClickListener { dialogFilterSource() }
isEnabled = true
}
text = provider.displayName
}
findViewById<View>(R.id.refreshButton)
.setOnClickListener { reconnectSource() }
}
setFilter(devicePreferences.getString("filter", "") ?: "")
}
private fun dialogFilterSource() {
val input = EditText(mainActivity).apply {
inputType = InputType.TYPE_CLASS_TEXT
setText(filter.value)
}
AlertDialog.Builder(this.mainActivity).apply {
setTitle(R.string.filter_title)
setPositiveButton(R.string.ok) { _, _ -> setFilter(input.text.toString().trim { it <= ' ' }) }
setNegativeButton(R.string.cancel, null)
setView(LinearLayout(mainActivity).apply {
orientation = LinearLayout.VERTICAL
setPadding(70, 0, 70, 0)
// Label
addView(TextView(mainActivity).apply {
setText(R.string.filter_help_label)
})
addView(input)
})
}.show()
}
private fun setFilter(newValue: String) {
filter.applyIfChanged(newValue) {
devicePreferences.edit()
.putString("filter", it)
.apply()
val allowed = it.split(splitRegex)
logger.info("setting source filter {}", allowed)
mainActivity.radarService?.setAllowedSourceIds(connection, allowed)
}
}
private fun reconnectSource() {
try {
// will restart scanning after disconnect
if (connection.isRecording) {
connection.stopRecording()
}
} catch (iobe: IndexOutOfBoundsException) {
Boast.makeText(this.mainActivity, "Could not restart scanning, there is no valid row index associated with this button.", Toast.LENGTH_LONG).show()
logger.warn(iobe.message)
}
}
fun update() {
sourceState = connection.sourceState
sourceName = when (sourceState?.status) {
SourceStatusListener.Status.CONNECTED,
SourceStatusListener.Status.CONNECTING -> connection.sourceName
?.replace("Empatica", "")
?.trim { c -> c <= ' ' }
else -> null
}
}
fun display() {
updateBattery()
updateSourceName()
updateSourceStatus()
}
private fun updateSourceStatus() {
statusCache.applyIfChanged(sourceState?.status ?: SourceStatusListener.Status.DISCONNECTED) { status ->
logger.info("Source status is {}", status)
mStatusIcon.setBackgroundResource(when(status) {
SourceStatusListener.Status.CONNECTED -> R.drawable.status_connected
SourceStatusListener.Status.DISCONNECTED -> R.drawable.status_disconnected
SourceStatusListener.Status.READY -> R.drawable.status_searching
SourceStatusListener.Status.CONNECTING -> R.drawable.status_searching
else -> sourceStatusIconDefault
})
}
}
private fun updateBattery() {
batteryLevelCache.applyIfChanged(sourceState?.batteryLevel ?: Float.NaN) {
mBatteryLabel.setImageResource(when {
it.isNaN() -> R.drawable.ic_battery_unknown
it < 0.1 -> R.drawable.ic_battery_empty
it < 0.3 -> R.drawable.ic_battery_low
it < 0.6 -> R.drawable.ic_battery_50
it < 0.85 -> R.drawable.ic_battery_80
else -> R.drawable.ic_battery_full
})
}
}
private fun updateSourceName() {
// \u2014 == —
sourceNameCache.applyIfChanged(sourceName ?: "\u2014") {
sourceNameLabel.text = it.truncate(MAX_UI_SOURCE_NAME_LENGTH)
}
}
companion object {
private val logger = LoggerFactory.getLogger(SourceRowView::class.java)
private const val MAX_UI_SOURCE_NAME_LENGTH = 10
private const val sourceStatusIconDefault = R.drawable.status_searching
}
}
| apache-2.0 | 35409beb6e4ab7c619ad321c227dbe05 | 37.566845 | 159 | 0.646007 | 4.876268 | false | false | false | false |
simonnorberg/dmach | app/src/main/java/net/simno/dmach/db/DbModule.kt | 1 | 1282 | package net.simno.dmach.db
import android.content.Context
import androidx.room.Room
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.runBlocking
import net.simno.dmach.data.defaultPatch
import net.simno.dmach.db.PatchRepository.Companion.toEntity
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DbModule {
@Provides
@Singleton
fun providePatchDatabase(@ApplicationContext context: Context): PatchDatabase {
val db = Room
.databaseBuilder(context, PatchDatabase::class.java, PatchDatabase.NAME)
.addMigrations(PatchDatabase.MIGRATION_2_3)
.fallbackToDestructiveMigration()
.build()
val dao = db.patchDao()
runBlocking {
if (dao.count() == 0) {
val defaultPatch = defaultPatch()
dao.insertPatch(defaultPatch.toEntity(defaultPatch.title))
}
}
return db
}
@Provides
@Singleton
fun providePatchRepository(patchDatabase: PatchDatabase): PatchRepository {
return PatchRepository(patchDatabase.patchDao())
}
}
| gpl-3.0 | 2b2e97e5fc508746632824183d4478f3 | 28.813953 | 84 | 0.705928 | 4.661818 | false | false | false | false |
NlRVANA/Unity | app/src/test/java/com/zwq65/unity/algorithm/dataStructures/FixedCapacityStackOfStrings.kt | 1 | 537 | package com.zwq65.unity.algorithm.dataStructures
/**
* ================================================
*
* Created by NIRVANA on 2020/6/17.
* Contact with <[email protected]>
* ================================================
*/
class FixedCapacityStackOfStrings(capacity: Int) {
private val s: Array<String?> = arrayOfNulls(capacity)
private var N = 0
val isEmpty: Boolean
get() = N == 0
fun push(item: String?) {
s[N++] = item
}
fun pop(): String? {
return s[--N]
}
} | apache-2.0 | c28b2b74a6fbb75ba349d7e5d974c8b9 | 21.416667 | 58 | 0.486034 | 4.162791 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/shortcuts/ShortcutRepository.kt | 1 | 6496 | package ch.rmy.android.http_shortcuts.data.domains.shortcuts
import ch.rmy.android.framework.data.BaseRepository
import ch.rmy.android.framework.data.RealmFactory
import ch.rmy.android.framework.data.RealmTransactionContext
import ch.rmy.android.framework.extensions.detachFromRealm
import ch.rmy.android.framework.extensions.swap
import ch.rmy.android.framework.utils.UUIDUtils.newUUID
import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryId
import ch.rmy.android.http_shortcuts.data.domains.getBase
import ch.rmy.android.http_shortcuts.data.domains.getCategoryById
import ch.rmy.android.http_shortcuts.data.domains.getShortcutById
import ch.rmy.android.http_shortcuts.data.domains.getShortcutByNameOrId
import ch.rmy.android.http_shortcuts.data.domains.getTemporaryShortcut
import ch.rmy.android.http_shortcuts.data.models.ShortcutModel
import ch.rmy.android.http_shortcuts.icons.ShortcutIcon
import io.realm.kotlin.deleteFromRealm
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class ShortcutRepository
@Inject
constructor(
realmFactory: RealmFactory,
) : BaseRepository(realmFactory) {
suspend fun getShortcutById(shortcutId: ShortcutId): ShortcutModel =
query {
getShortcutById(shortcutId)
}
.first()
suspend fun getShortcutsByIds(shortcutIds: Collection<ShortcutId>): List<ShortcutModel> =
queryItem {
getBase()
}
.shortcuts.filter { it.id in shortcutIds }
suspend fun getShortcutByNameOrId(shortcutNameOrId: ShortcutNameOrId): ShortcutModel =
queryItem {
getShortcutByNameOrId(shortcutNameOrId)
}
fun getObservableShortcuts(): Flow<List<ShortcutModel>> =
observeList {
getBase().findFirst()!!.categories
}
.map { categories ->
categories.flatMap { category ->
category.shortcuts
}
}
suspend fun getShortcuts(): List<ShortcutModel> =
queryItem {
getBase()
}
.shortcuts
suspend fun moveShortcutToCategory(shortcutId: ShortcutId, targetCategoryId: CategoryId) {
commitTransaction {
moveShortcut(shortcutId, targetCategoryId = targetCategoryId)
}
}
suspend fun swapShortcutPositions(categoryId: CategoryId, shortcutId1: ShortcutId, shortcutId2: ShortcutId) {
commitTransaction {
getCategoryById(categoryId)
.findFirst()
?.shortcuts
?.swap(shortcutId1, shortcutId2) { id }
}
}
private fun RealmTransactionContext.moveShortcut(shortcutId: ShortcutId, targetPosition: Int? = null, targetCategoryId: CategoryId? = null) {
val shortcut = getShortcutById(shortcutId)
.findFirst() ?: return
val categories = getBase()
.findFirst()
?.categories ?: return
val targetCategory = if (targetCategoryId != null) {
getCategoryById(targetCategoryId)
.findFirst()
} else {
categories.first { category -> category.shortcuts.any { it.id == shortcutId } }
} ?: return
for (category in categories) {
category.shortcuts.remove(shortcut)
}
if (targetPosition != null) {
targetCategory.shortcuts.add(targetPosition, shortcut)
} else {
targetCategory.shortcuts.add(shortcut)
}
}
suspend fun duplicateShortcut(shortcutId: ShortcutId, newName: String, newPosition: Int?, categoryId: CategoryId) {
commitTransaction {
val shortcut = getShortcutById(shortcutId)
.findFirst()
?: return@commitTransaction
val newShortcut = copyShortcut(shortcut, newUUID())
newShortcut.name = newName
moveShortcut(newShortcut.id, newPosition, categoryId)
}
}
suspend fun createTemporaryShortcutFromShortcut(shortcutId: ShortcutId) {
commitTransaction {
val shortcut = getShortcutById(shortcutId)
.findFirst()!!
copyShortcut(shortcut, ShortcutModel.TEMPORARY_ID)
}
}
suspend fun copyTemporaryShortcutToShortcut(shortcutId: ShortcutId, categoryId: CategoryId?) {
commitTransaction {
val temporaryShortcut = getTemporaryShortcut()
.findFirst() ?: return@commitTransaction
val shortcut = copyShortcut(temporaryShortcut, shortcutId)
if (categoryId != null) {
val category = getCategoryById(categoryId)
.findFirst()
?: return@commitTransaction
if (category.shortcuts.none { it.id == shortcutId }) {
category.shortcuts.add(shortcut)
}
}
}
}
private fun RealmTransactionContext.copyShortcut(sourceShortcut: ShortcutModel, targetShortcutId: ShortcutId): ShortcutModel =
sourceShortcut.detachFromRealm()
.apply {
id = targetShortcutId
parameters.forEach { parameter ->
parameter.id = newUUID()
}
headers.forEach { header ->
header.id = newUUID()
}
}
.let(::copyOrUpdate)
suspend fun deleteShortcut(shortcutId: ShortcutId) {
commitTransaction {
getShortcutById(shortcutId)
.findFirst()
?.apply {
headers.deleteAllFromRealm()
parameters.deleteAllFromRealm()
responseHandling?.deleteFromRealm()
deleteFromRealm()
}
}
}
suspend fun setIcon(shortcutId: ShortcutId, icon: ShortcutIcon) {
commitTransaction {
getShortcutById(shortcutId)
.findFirst()
?.icon = icon
}
}
suspend fun setName(shortcutId: ShortcutId, name: String) {
commitTransaction {
getShortcutById(shortcutId)
.findFirst()
?.name = name
}
}
suspend fun setDescription(shortcutId: ShortcutId, description: String) {
commitTransaction {
getShortcutById(shortcutId)
.findFirst()
?.description = description
}
}
}
| mit | c80a99ea87ab26b92a09f494da2c3341 | 34.497268 | 145 | 0.618688 | 5.426901 | false | false | false | false |
byoutline/SecretSauce | SecretSauce/src/main/java/com/byoutline/secretsauce/utils/NetworkChangeReceiver.kt | 1 | 2370 | package com.byoutline.secretsauce.utils
import android.Manifest
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import androidx.databinding.ObservableBoolean
import android.net.ConnectivityManager
import android.os.Build
import androidx.core.content.ContextCompat
import com.byoutline.secretsauce.lifecycle.AttachableViewModel
/**
* Transforms Android broadcasts into [android.databinding.ObservableBoolean].
* @author Sebastian Kacprzak <nait at naitbit.com>
*/
class NetworkChangeReceiver
(
private val connectivityManager: ConnectivityManager,
val connectedOrConnecting: ObservableBoolean = ObservableBoolean()
) : BroadcastReceiver() {
private var context: Context? = null
override fun onReceive(context: Context, intent: Intent) {
connectedOrConnecting.set(connected())
}
@SuppressLint("MissingPermission")
fun connected(): Boolean {
val ctx = context ?: return true
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(
ctx,
Manifest.permission.ACCESS_NETWORK_STATE
) != PackageManager.PERMISSION_GRANTED) {
LogUtils.LOGW(TAG, "No permission to read connection state, returning connected=true")
return true
}
val activeNetInfo = connectivityManager.activeNetworkInfo
return activeNetInfo != null && activeNetInfo.isConnectedOrConnecting
}
fun register(context: Context) {
this.context = context
context.registerReceiver(
this,
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
)
}
fun unregister(context: Context) {
context.unregisterReceiver(this)
this.context = null
}
companion object {
private val TAG = LogUtils.internalMakeLogTag(NetworkChangeReceiver::class.java)
}
}
class NetworkChangeViewModel(private val receiver: NetworkChangeReceiver) : AttachableViewModel<Context>() {
val connectedOrConnecting = receiver.connectedOrConnecting
override fun onAttach(view: Context) {
receiver.register(view)
super.onAttach(view)
registerDetachAction { receiver.unregister(view) }
}
} | apache-2.0 | 25803cc8de6193389d1b4b3a174d3770 | 31.930556 | 108 | 0.724051 | 5.152174 | false | false | false | false |
marktony/ZhiHuDaily | app/src/main/java/com/marktony/zhihudaily/data/ZhihuDailyContent.kt | 1 | 2526 | /*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.data
import android.annotation.SuppressLint
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import android.arch.persistence.room.TypeConverters
import android.os.Parcelable
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import com.marktony.zhihudaily.database.converter.StringTypeConverter
import kotlinx.android.parcel.Parcelize
@Entity(tableName = "zhihu_daily_content")
@TypeConverters(StringTypeConverter::class)
@Parcelize
@SuppressLint("ParcelCreator")
data class ZhihuDailyContent(
@ColumnInfo(name = "body")
@Expose
@SerializedName("body")
val body: String,
@ColumnInfo(name = "image_source")
@Expose
@SerializedName("image_source")
val imageSource: String,
@ColumnInfo(name = "title")
@Expose
@SerializedName("title")
val title: String,
@ColumnInfo(name = "image")
@Expose
@SerializedName("image")
val image: String,
@ColumnInfo(name = "share_url")
@Expose
@SerializedName("share_url")
val shareUrl: String,
@ColumnInfo(name = "js")
@Expose
@SerializedName("js")
val js: List<String>,
@Expose
@SerializedName("ga_prefix")
val gaPrefix: String,
@ColumnInfo(name = "images")
@Expose
@SerializedName("images")
val images: List<String>,
@ColumnInfo(name = "type")
@Expose
@SerializedName("type")
val type: Int,
@PrimaryKey
@ColumnInfo(name = "id")
@Expose
@SerializedName("id")
val id: Int = 0,
@ColumnInfo(name = "css")
@Expose
@SerializedName("css")
val css: List<String>
) : Parcelable | apache-2.0 | e4bd9bed9e4482ce4a9bae9ecc8cc2f2 | 26.769231 | 75 | 0.657957 | 4.416084 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/command/unmute/UnmuteCommand.kt | 1 | 2904 | /*
* Copyright 2016 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.chat.bukkit.command.unmute
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
/**
* Unmute command.
* Unmutes a chat channel.
*/
class UnmuteCommand(private val plugin: RPKChatBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender is Player) {
if (args.isNotEmpty()) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val chatChannelProvider = plugin.core.serviceManager.getServiceProvider(RPKChatChannelProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender)
if (minecraftProfile != null) {
val chatChannel = chatChannelProvider.getChatChannel(args[0])
if (chatChannel != null) {
if (sender.hasPermission("rpkit.chat.command.unmute.${chatChannel.name}")) {
chatChannel.addListener(minecraftProfile)
sender.sendMessage(plugin.messages["unmute-valid", mapOf(
Pair("channel", chatChannel.name)
)])
} else {
sender.sendMessage(plugin.messages["no-permission-unmute", mapOf(
Pair("channel", chatChannel.name)
)])
}
} else {
sender.sendMessage(plugin.messages["unmute-invalid-chatchannel"])
}
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["unmute-usage"])
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
return true
}
} | apache-2.0 | edb0e3a9e774d902ecefa06b3a04d590 | 42.358209 | 128 | 0.618457 | 5.223022 | false | false | false | false |
Petrulak/kotlin-mvp-clean-architecture | app/src/main/java/com/petrulak/cleankotlin/ui/example3/fragment/Example3Presenter.kt | 1 | 3319 | package com.petrulak.cleankotlin.ui.example3.fragment
import android.util.Log
import com.petrulak.cleankotlin.di.scope.ViewScope
import com.petrulak.cleankotlin.domain.interactor.definition.GetWeatherRemotelyUseCase
import com.petrulak.cleankotlin.domain.model.Weather
import com.petrulak.cleankotlin.platform.bus.data.DataBus
import com.petrulak.cleankotlin.platform.bus.event.EventBus
import com.petrulak.cleankotlin.platform.bus.event.events.BaseEvent
import com.petrulak.cleankotlin.platform.bus.event.events.FragmentSyncEvent
import com.petrulak.cleankotlin.platform.extensions.getDisposableSingleObserver
import com.petrulak.cleankotlin.ui.base.BasePresenterImpl
import com.petrulak.cleankotlin.ui.example3.fragment.Example3Contract.View
import dagger.internal.Preconditions.checkNotNull
import io.reactivex.disposables.CompositeDisposable
import java.util.*
import javax.inject.Inject
@ViewScope
class Example3Presenter
@Inject
constructor(private val getWeatherRemotelyUseCase: GetWeatherRemotelyUseCase,
private val dataBus: DataBus,
private val eventBus: EventBus) : BasePresenterImpl(), Example3Contract.Presenter {
private var view: View? = null
private val dataDisposable = CompositeDisposable()
override fun attachView(view: View) {
this.view = checkNotNull(view)
}
override fun start() {
super.start()
refresh()
subscribeToData()
subscribeToFragmentSyncEvents()
// subscribeToDummyEvents()
}
private fun subscribeToData() {
val disposable = dataBus.weatherDataBus.flowable.subscribe({ view?.showWeather(it) })
dataDisposable.add(disposable)
}
private fun subscribeToFragmentSyncEvents() {
val disposable = eventBus.fragmentSyncEvent.flowable.subscribe({ processEvent(it) })
disposables.add(disposable)
}
/**
* You can consume data/payload which is included in the event.
*/
private fun subscribeToDummyEvents() {
val disposable = eventBus.weatherDummyEvent.flowable.subscribe({ processDummyEvent(it) })
disposables.add(disposable)
}
private fun processDummyEvent(event: BaseEvent<Weather>) {
//payload can be null, we have to perform null check
event.payload?.let {
val payload = it
Log.e("Hello", "This is payload: $payload")
}
}
private fun processEvent(event: BaseEvent<Any>) {
when (event.eventType) {
FragmentSyncEvent.ACTION_SYNC_OFF -> dataDisposable.clear()
FragmentSyncEvent.ACTION_SYNC_ON -> subscribeToData()
}
}
override fun stop() {
super.stop()
dataDisposable.clear()
}
override fun refresh() {
val disposable = getWeatherRemotelyUseCase
.execute("London,uk")
.subscribeWith(getDisposableSingleObserver({ onSuccess(it) }, { onError(it) }))
disposables.add(disposable)
}
private fun onSuccess(weather: Weather) {
//Changing visibility value manually to see changes in the UI
val modified = Weather(weather.id, weather.name, Random().nextInt(80 - 65) + 65)
dataBus.weatherDataBus.emmit(modified)
view?.showWeather(modified)
}
private fun onError(t: Throwable) {
}
}
| mit | aee98d6025da0cb7ff42eb5567ffb0a3 | 32.867347 | 97 | 0.707141 | 4.622563 | false | false | false | false |
bk138/multivnc | android/app/src/main/java/com/coboltforge/dontmind/multivnc/ImportExport.kt | 1 | 2128 | package com.coboltforge.dontmind.multivnc
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.io.Reader
import java.io.Writer
/**
* Import/Export Utility
*/
object ImportExport {
/**
* Current version of [Container].
*/
private const val VERSION = 1
@Serializable
private data class Container(
val version: Int,
val connections: List<ConnectionBean>,
val metaKeys: List<MetaKeyBean>,
val metaLists: List<MetaList>
)
private val serializer = Json {
encodeDefaults = false
ignoreUnknownKeys = true
prettyPrint = true
}
/**
* Exports database to given [writer].
*/
fun exportDatabase(db: VncDatabase, writer: Writer) {
val container = Container(
VERSION,
db.connectionDao.all,
db.metaKeyDao.all,
db.metaListDao.all
)
val json = serializer.encodeToString(container)
writer.write(json)
}
/**
* Reads JSON data from given [reader] and imports it into [db].
*/
fun importDatabase(db: VncDatabase, reader: Reader) {
val json = reader.readText()
val container = serializer.decodeFromString<Container>(json)
db.runInTransaction {
container.connections.forEach {
if (db.connectionDao.get(it.id) == null)
db.connectionDao.insert(it)
else
db.connectionDao.update(it)
}
container.metaKeys.forEach {
if (db.metaKeyDao.get(it.id) == null)
db.metaKeyDao.insert(it)
else
db.metaKeyDao.update(it)
}
container.metaLists.forEach {
if (db.metaListDao.get(it.id) == null)
db.metaListDao.insert(it)
else
db.metaListDao.update(it)
}
}
}
} | gpl-3.0 | 09f9f39cea181cda27b626bbe615c47b | 25.6125 | 68 | 0.56297 | 4.676923 | false | false | false | false |
wizardofos/Protozoo | component/taskcommand/src/main/kotlin/org.protozoo.component.task.command/ListAction.kt | 1 | 719 | package org.protozoo.component.task.command
import org.apache.karaf.shell.api.action.Command
import org.apache.karaf.shell.api.action.lifecycle.Service
/**
* List all the components currently installed.
*/
@Command(scope = TaskCommandConstants.TASK_COMMAND, name = TaskCommandConstants.LIST_FUNCTION, description = "Display available tasks")
@Service
class ListAction : TaskAction() {
override fun execute() : Any? {
val tasks = manager.getAll()
if (tasks.count() == 0) {
println("No components registered")
} else {
for (task in tasks) {
println("> " + task.title + ", " + task.description)
}
}
return null
}
} | mit | fb781ba10a985d8e341392b859f97aa8 | 25.666667 | 135 | 0.630042 | 4.132184 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/news/GraphActivity.kt | 1 | 3362 | package com.github.premnirmal.ticker.news
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.charts.LineChart
import com.github.premnirmal.ticker.base.BaseGraphActivity
import com.github.premnirmal.ticker.components.InAppMessage
import com.github.premnirmal.ticker.isNetworkOnline
import com.github.premnirmal.ticker.model.HistoryProvider.Range
import com.github.premnirmal.ticker.network.data.Quote
import com.github.premnirmal.ticker.showDialog
import com.github.premnirmal.ticker.viewBinding
import com.github.premnirmal.tickerwidget.R
import com.github.premnirmal.tickerwidget.databinding.ActivityGraphBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class GraphActivity : BaseGraphActivity<ActivityGraphBinding>() {
companion object {
const val TICKER = "TICKER"
private const val DURATION = 2000
}
override val simpleName: String = "GraphActivity"
override val binding: (ActivityGraphBinding) by viewBinding(ActivityGraphBinding::inflate)
private lateinit var ticker: String
protected lateinit var quote: Quote
private val viewModel: GraphViewModel by viewModels()
override var range: Range = Range.THREE_MONTH
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupGraphView()
ticker = checkNotNull(intent.getStringExtra(TICKER))
viewModel.quote.observe(this) { quote ->
this.quote = quote
binding.tickerName.text = ticker
binding.desc.text = quote.name
viewModel.data.observe(this) { data ->
dataPoints = data
loadGraph(ticker, quote)
}
}
viewModel.error.observe(this) {
showErrorAndFinish()
}
viewModel.fetchStock(ticker)
binding.groupPeriod.setOnCheckedChangeListener { _, checkedId ->
val view = findViewById<View>(checkedId)
updateRange(view)
}
val view = when (range) {
Range.ONE_DAY -> binding.oneDay
Range.TWO_WEEKS -> binding.twoWeeks
Range.ONE_MONTH -> binding.oneMonth
Range.THREE_MONTH -> binding.threeMonth
Range.ONE_YEAR -> binding.oneYear
Range.FIVE_YEARS -> binding.fiveYears
Range.MAX -> binding.max
else -> throw UnsupportedOperationException("Range not supported")
}
binding.groupPeriod.check(view.id)
}
override fun onStart() {
super.onStart()
if (dataPoints == null) {
fetchGraphData()
}
}
private fun showErrorAndFinish() {
InAppMessage.showToast(this, R.string.error_symbol)
finish()
}
override fun fetchGraphData() {
if (isNetworkOnline()) {
binding.graphView.visibility = View.INVISIBLE
binding.progress.visibility = View.VISIBLE
viewModel.fetchHistoricalDataByRange(ticker, range)
} else {
showDialog(getString(R.string.no_network_message),
{ _, _ -> finish() }, cancelable = false)
}
}
override fun onGraphDataAdded(graphView: LineChart) {
binding.progress.visibility = View.GONE
binding.graphView.visibility = View.VISIBLE
graphView.animateX(DURATION, Easing.EasingOption.EaseInOutCubic)
}
override fun onNoGraphData(graphView: LineChart) {
binding.progress.visibility = View.GONE
binding.graphView.visibility = View.VISIBLE
}
} | gpl-3.0 | 8dbb55dd07fc3f2902df77b7685dbf6b | 32.29703 | 92 | 0.735277 | 4.389034 | false | false | false | false |
rharter/windy-city-devcon-android | core/src/main/kotlin/com/gdgchicagowest/windycitydevcon/ext/Bytes.kt | 1 | 702 | package com.gdgchicagowest.windycitydevcon.ext
/**
* Set of chars for a half-byte.
*/
private val CHARS = arrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')
/**
* Returns the string of two characters representing the HEX value of the byte.
*/
internal fun Byte.toHexString() : String {
val i = this.toInt()
val char2 = CHARS[i and 0x0f]
val char1 = CHARS[i shr 4 and 0x0f]
return "$char1$char2"
}
/**
* Returns the HEX representation of ByteArray data.
*/
internal fun ByteArray.toHexString() : String {
val builder = StringBuilder()
for (b in this) {
builder.append(b.toHexString())
}
return builder.toString()
} | apache-2.0 | 76726069c97625f75d7f6aab61b7ff01 | 25.037037 | 107 | 0.612536 | 3.205479 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/base/net/Net.kt | 1 | 739 | package com.binlly.fastpeak.base.net
import android.content.Context
import android.net.ConnectivityManager
import com.binlly.fastpeak.service.Services
/**
* Created by yy on 2017/8/23.
*/
object Net {
fun isAvailable(): Boolean {
val mConnectivityManager = Services.app().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mNetworkInfo = mConnectivityManager.activeNetworkInfo
if (mNetworkInfo != null) return mNetworkInfo.isAvailable
return false
}
fun isWifi(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return cm.activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI
}
} | mit | 2c1fbec84ed4f9f5112453d4ca44ee51 | 31.173913 | 119 | 0.742896 | 4.861842 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/business/test/model/TestModel.kt | 1 | 1352 | package com.binlly.fastpeak.business.test.model
import com.chad.library.adapter.base.entity.MultiItemEntity
import java.io.Serializable
class TestModel: MultiItemEntity, Serializable {
var item_type: Int = 0
val isSectionType: Boolean
get() = item_type == TYPE_SECTION
val isEnvType: Boolean
get() = item_type == TYPE_ENV
val isBuildType: Boolean
get() = item_type == TYPE_BUILD
val isMockType: Boolean
get() = item_type == TYPE_MOCK
val isRouterType: Boolean
get() = item_type == TYPE_ROUTER
override fun getItemType(): Int {
return item_type
}
lateinit var section: String
lateinit var env: EnvModel
lateinit var build: BuildModel
lateinit var mock: MockModel
lateinit var router: RouterModel
var valueColor: Int = 0
data class EnvModel(var key: String, var value: String, var isSelected: Boolean = false)
data class BuildModel(var key: String, var value: String)
data class MockModel(var key: String, var value: String)
data class RouterModel(var key: String, var value: String)
companion object {
private const val serialVersionUID = -4241242337755076267L
val TYPE_SECTION = 0
val TYPE_ENV = 1
val TYPE_BUILD = 2
val TYPE_MOCK = 3
val TYPE_ROUTER = 4
}
} | mit | 94d368f3a873de3bfe112dceadc6b0cb | 23.6 | 92 | 0.659763 | 4.121951 | false | false | false | false |
zxj5470/BugKotlinDocument | src/main/kotlin/com/github/zxj5470/bugktdoc/BugKtDocTools.kt | 1 | 1569 | package com.github.zxj5470.bugktdoc
import com.github.zxj5470.bugktdoc.options.BugKtDocGlobalSettings
import com.intellij.CommonBundle
import com.intellij.openapi.components.ServiceManager
import com.intellij.util.PlatformUtils
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import java.util.*
val globalSettings
get() = ServiceManager.getService(BugKtDocGlobalSettings::class.java).settings
val isTheFirstTime
get() = globalSettings.theFirstTile
val pluginActive
get() = globalSettings.useBugKtDoc
val isAlwaysShowUnitReturnType
get() = globalSettings.alwaysShowUnitReturnType
val isAlwaysShowClassFieldProperty
get() = globalSettings.alwaysShowClassFieldProperty
val isAlwaysShowConstructor
get() = globalSettings.alwaysShowConstructor
/**
* @ref https://github.com/ice1000/julia-intellij/blob/master/src/org/ice1000/julia/lang/julia-infos.kt
* class [JuliaBundle]
*/
object BugKtDocBundle {
@NonNls
private const val BUNDLE = "BugKtDocBundle"
private val bundle: ResourceBundle by lazy { ResourceBundle.getBundle(BUNDLE) }
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
CommonBundle.message(bundle, key, *params)
}
inline val KtCallableDeclaration.itsType
get() = SpecifyTypeExplicitlyIntention.getTypeForDeclaration(this).unwrap().toString()
val isKotlinNative
get() = PlatformUtils.isAppCode() || PlatformUtils.isCLion() | apache-2.0 | 342a6bbed1ef44dc8e251d131be4c888 | 31.708333 | 103 | 0.823454 | 4.064767 | false | false | false | false |
industrial-data-space/trusted-connector | ids-container-manager/src/main/kotlin/de/fhg/aisec/ids/comm/unixsocket/TrustmeUnixSocketResponseHandler.kt | 1 | 1843 | /*-
* ========================LICENSE_START=================================
* ids-container-manager
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.comm.unixsocket
import org.slf4j.LoggerFactory
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
class TrustmeUnixSocketResponseHandler {
private val lock = ReentrantLock()
private val condition = lock.newCondition()
private val LOG = LoggerFactory.getLogger(TrustmeUnixSocketResponseHandler::class.java)
private var rsp: ByteArray? = null
fun handleResponse(rsp: ByteArray): Boolean {
lock.withLock {
this.rsp = rsp.clone()
condition.signal()
return true
}
}
fun waitForResponse(): ByteArray {
lock.withLock {
while (rsp == null) {
try {
condition.await()
} catch (e: InterruptedException) {
LOG.error(e.message, e)
}
}
val result = rsp!!
LOG.debug("received response byte length: {}", result.size)
rsp = null
return result
}
}
}
| apache-2.0 | af4967ad53ca5a240d3583942ade28d4 | 31.910714 | 91 | 0.593597 | 4.774611 | false | false | false | false |
googlearchive/background-tasks-samples | WorkManager/lib/src/main/java/com/example/background/imgur/PostImageResponse.kt | 1 | 1177 | /*
*
* * Copyright (C) 2018 The Android Open Source Project
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.example.background.imgur
import com.google.gson.annotations.SerializedName
/**
* The Imgur API post image response.
*/
class PostImageResponse {
@SerializedName("data")
val data: UploadedImage? = null
@SerializedName("success")
val isSuccess: Boolean = false
@SerializedName("status")
val status: Int = 0
class UploadedImage {
@SerializedName("id")
val id: String? = null
@SerializedName("link")
val link: String? = null
}
}
| apache-2.0 | bfbac410f969642e04524067be89d9ba | 25.155556 | 78 | 0.668649 | 3.949664 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/gifs/GetOverHereGIF.kt | 1 | 1631 | package net.perfectdreams.loritta.morenitta.gifs
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.extensions.readImage
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.stream.FileImageOutputStream
object GetOverHereGIF {
suspend fun getGIF(toUse: BufferedImage): File {
var fileName = LorittaBot.TEMP + "getoverherescorpion-" + System.currentTimeMillis() + ".gif"
var output = FileImageOutputStream(File(fileName))
val writer = GifSequenceWriter(output, BufferedImage.TYPE_INT_ARGB, 10, true)
val scaled = toUse.getScaledInstance(50, 50, BufferedImage.SCALE_SMOOTH)
for (i in 0..52) {
val file = File(LorittaBot.ASSETS + "getoverhere/scorpion_${i.toString().padStart(6, '0')}.png")
if (file.exists()) {
var ogImage = readImage(File(LorittaBot.ASSETS + "getoverhere/scorpion_${i.toString().padStart(6, '0')}.png"))
var image = BufferedImage(ogImage.width, ogImage.height, BufferedImage.TYPE_INT_ARGB)
image.graphics.drawImage(ogImage, 0, 0, null)
if (i in 0..4) {
image.graphics.drawImage(scaled, 9, 27, null)
}
if (i == 5) {
image.graphics.drawImage(scaled, 49, 27, null)
}
if (i == 6) {
image.graphics.drawImage(scaled, 124, 27, null)
}
if (i == 7) {
image.graphics.drawImage(scaled, 107, 27, null)
}
if (i in 8..9) {
image.graphics.drawImage(scaled, 118, 24, null)
}
if (i == 10) {
image.graphics.drawImage(scaled, 85, 12, null)
}
writer.writeToSequence(image)
}
}
writer.close()
output.close()
return File(fileName)
}
} | agpl-3.0 | 0ad4631190b02410661e7f936c5a9359 | 33 | 114 | 0.689761 | 3.185547 | false | false | false | false |
sandeepraju/concurrency | kotlin/src/main/kotlin/io/github/sandeepraju/ServerWithEventloop.kt | 1 | 3381 | package io.github.sandeepraju
import io.github.sandeepraju.utils.Database
import io.github.sandeepraju.utils.Image
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
class AsyncServer : Server {
// selector is the Java wrapper around select() system call
val selector = Selector.open()
// create a socket to listen for traffic
val channel = ServerSocketChannel.open()
override fun listen(host: String, port: Int): Unit {
println("[${this.javaClass.simpleName}] Server listening at $host:$port")
channel.bind(InetSocketAddress(host, port))
channel.configureBlocking(false)
// register the socket channel to notify when any client "connects"
channel.register(selector, channel.validOps())
// start the event loop
while (true) {
// check if any channels are ready
selector.select()
// fetch all the keys of the channels that are ready
// on the operations we registered
val readyChannelKeys = selector.selectedKeys().iterator()
while(readyChannelKeys.hasNext()) {
val currentChannelKey = readyChannelKeys.next()
when {
currentChannelKey.isAcceptable -> { // we got a new connection
// accept the new connection and register it to the selector
// so that selector notifies us when it is ready to read the data
val acceptedChannel = (currentChannelKey.channel() as ServerSocketChannel).accept()
acceptedChannel.configureBlocking(false)
acceptedChannel.register(selector, SelectionKey.OP_READ)
}
currentChannelKey.isReadable -> { // the socket is ready to be read now
// read the data onto a buffer
val data = ByteBuffer.allocate(256)
val rwChannel = currentChannelKey.channel() as SocketChannel
rwChannel.read(data)
println(String(data.array(), 0, data.position()).trim())
// CPU intensive
Image.process("/tmp/hello.png")
// I/O intensive
// Database.query("SELECT * FROM users;")
rwChannel.configureBlocking(false)
rwChannel.register(selector, SelectionKey.OP_WRITE)
}
currentChannelKey.isWritable -> { // the socket is ready to be written now
// write response to the socket
val rwChannel = currentChannelKey.channel() as SocketChannel
rwChannel.write(ByteBuffer.wrap("pong".toByteArray()))
// close the channel
rwChannel.close()
}
}
// remove the current socket from the selector since we processed it
readyChannelKeys.remove()
}
}
}
}
fun main(args: Array<String>) {
AsyncServer().listen("0.0.0.0", 9999)
} | bsd-3-clause | cc0f6c584bea5a9ae83a48c25169be95 | 33.865979 | 107 | 0.571724 | 5.570016 | false | false | false | false |
Nagarajj/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/StartExecutionHandlerSpec.kt | 1 | 3457 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.events.ExecutionStarted
import com.netflix.spinnaker.orca.pipeline.model.Pipeline
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.*
import com.netflix.spinnaker.spek.shouldEqual
import com.nhaarman.mockito_kotlin.*
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
import org.springframework.context.ApplicationEventPublisher
object StartExecutionHandlerSpec : SubjectSpek<StartExecutionHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val publisher: ApplicationEventPublisher = mock()
subject {
StartExecutionHandler(queue, repository, publisher)
}
fun resetMocks() = reset(queue, repository, publisher)
describe("starting an execution") {
context("with a single initial stage") {
val pipeline = pipeline {
stage {
type = singleTaskStage.type
}
}
val message = StartExecution(Pipeline::class.java, pipeline.id, "foo")
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the execution as running") {
verify(repository).updateStatus(message.executionId, ExecutionStatus.RUNNING)
}
it("starts the first stage") {
verify(queue).push(StartStage(
message.executionType,
message.executionId,
"foo",
pipeline.stages.first().id
))
}
it("publishes an event") {
verify(publisher).publishEvent(check<ExecutionStarted> {
it.executionType shouldEqual message.executionType
it.executionId shouldEqual message.executionId
})
}
}
context("with multiple initial stages") {
val pipeline = pipeline {
stage {
type = singleTaskStage.type
}
stage {
type = singleTaskStage.type
}
}
val message = StartExecution(Pipeline::class.java, pipeline.id, "foo")
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("starts all the initial stages") {
argumentCaptor<StartStage>().apply {
verify(queue, times(2)).push(capture())
allValues.map { it.stageId }.toSet() shouldEqual pipeline.stages.map { it.id }.toSet()
}
}
}
}
})
| apache-2.0 | d4e5a779dcd547f6efef04ff320ca3ee | 29.59292 | 96 | 0.683541 | 4.640268 | false | false | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/data/classes/MeowsterRewards.kt | 1 | 1198 | package com.ghstudios.android.data.classes
import com.ghstudios.android.ITintedIcon
import com.ghstudios.android.mhgendatabase.R
enum class MeowsterType(val type:Int){
STONE(0),
FISH(1),
GRASS(2),
NUTS(3),
BONE(4),
BAIT(5),
HONEY(6),
INSECT(7),
MUSHROOM(8)
}
class MeowsterRewards : ITintedIcon {
var item:Item? = null
var location:String? = null
var isRare: Boolean = false
var rank: String? = null
var count:Int = 0
var percentage: Int = 0
var type: MeowsterType? = null
override fun getIconResourceString(): String {
return when(type){
MeowsterType.STONE -> "icon_ore"
MeowsterType.BAIT -> "icon_bait"
MeowsterType.BONE -> "icon_bone"
MeowsterType.FISH -> "icon_fish"
MeowsterType.GRASS -> "icon_herb"
MeowsterType.HONEY -> "icon_webbing"
MeowsterType.INSECT -> "icon_bug"
MeowsterType.MUSHROOM -> "icon_mushroom"
else -> "icon_unknown"
}
}
override fun getColorArrayId(): Int {
return R.array.item_colors
}
override fun getIconColorIndex(): Int {
return 0
}
}
| mit | 86b081bf7680a5d6c866796de2ee98f7 | 23.958333 | 52 | 0.597663 | 3.839744 | false | false | false | false |
shyiko/ktlint | ktlint-reporter-plain/src/main/kotlin/com/pinterest/ktlint/reporter/plain/PlainReporterProvider.kt | 1 | 1021 | package com.pinterest.ktlint.reporter.plain
import com.pinterest.ktlint.core.Reporter
import com.pinterest.ktlint.core.ReporterProvider
import com.pinterest.ktlint.reporter.plain.internal.Color
import java.io.PrintStream
public class PlainReporterProvider : ReporterProvider {
override val id: String = "plain"
override fun get(out: PrintStream, opt: Map<String, String>): Reporter =
PlainReporter(
out,
verbose = opt["verbose"]?.emptyOrTrue() ?: false,
groupByFile = opt["group_by_file"]?.emptyOrTrue() ?: false,
shouldColorOutput = opt["color"]?.emptyOrTrue() ?: false,
outputColor = getColor(opt["color_name"]),
pad = opt["pad"]?.emptyOrTrue() ?: false
)
private fun String.emptyOrTrue() = this == "" || this == "true"
private fun getColor(colorInput: String?): Color {
return Color.values().firstOrNull { it.name == colorInput } ?: throw IllegalArgumentException("Invalid color parameter.")
}
}
| mit | 1c1f1fb1317b0061d96a855547d91d36 | 36.814815 | 129 | 0.662096 | 4.47807 | false | false | false | false |
vanniktech/Emoji | emoji-facebook/src/commonMain/kotlin/com/vanniktech/emoji/facebook/category/SmileysAndPeopleCategoryChunk3.kt | 1 | 71746 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vanniktech.emoji.facebook.category
import com.vanniktech.emoji.facebook.FacebookEmoji
internal object SmileysAndPeopleCategoryChunk3 {
internal val EMOJIS: List<FacebookEmoji> = listOf(
FacebookEmoji(String(intArrayOf(0x1F9DF), 0, 1), listOf("zombie"), 53, 13, true),
FacebookEmoji(String(intArrayOf(0x1F9DF, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("male_zombie"), 53, 12, false),
FacebookEmoji(String(intArrayOf(0x1F9DF, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("female_zombie"), 53, 11, false),
FacebookEmoji(
String(intArrayOf(0x1F486), 0, 1), listOf("massage"), 26, 10, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FB), 0, 2), emptyList<String>(), 26, 11, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FC), 0, 2), emptyList<String>(), 26, 12, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FD), 0, 2), emptyList<String>(), 26, 13, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FE), 0, 2), emptyList<String>(), 26, 14, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FF), 0, 2), emptyList<String>(), 26, 15, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F486, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-getting-massage"), 26, 4, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 5, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 6, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 7, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 8, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 9, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F486, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-getting-massage"), 25, 59, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 25, 60, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 0, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 1, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 2, false),
FacebookEmoji(String(intArrayOf(0x1F486, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 3, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F487), 0, 1), listOf("haircut"), 26, 28, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FB), 0, 2), emptyList<String>(), 26, 29, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FC), 0, 2), emptyList<String>(), 26, 30, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FD), 0, 2), emptyList<String>(), 26, 31, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FE), 0, 2), emptyList<String>(), 26, 32, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FF), 0, 2), emptyList<String>(), 26, 33, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F487, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-getting-haircut"), 26, 22, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 23, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 24, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 25, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 26, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 26, 27, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F487, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-getting-haircut"), 26, 16, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 17, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 18, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 19, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 20, false),
FacebookEmoji(String(intArrayOf(0x1F487, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 26, 21, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B6), 0, 1), listOf("walking"), 37, 27, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB), 0, 2), emptyList<String>(), 37, 28, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC), 0, 2), emptyList<String>(), 37, 29, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD), 0, 2), emptyList<String>(), 37, 30, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE), 0, 2), emptyList<String>(), 37, 31, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF), 0, 2), emptyList<String>(), 37, 32, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B6, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-walking"), 37, 21, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 22, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 23, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 24, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 25, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 26, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B6, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-walking"), 37, 15, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 16, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 17, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 18, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 19, false),
FacebookEmoji(String(intArrayOf(0x1F6B6, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 20, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CD), 0, 1), listOf("standing_person"), 46, 30, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB), 0, 2), emptyList<String>(), 46, 31, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC), 0, 2), emptyList<String>(), 46, 32, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD), 0, 2), emptyList<String>(), 46, 33, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE), 0, 2), emptyList<String>(), 46, 34, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF), 0, 2), emptyList<String>(), 46, 35, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CD, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_standing"), 46, 24, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 25, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 26, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 27, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 28, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 29, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CD, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_standing"), 46, 18, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 19, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 20, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 21, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 22, false),
FacebookEmoji(String(intArrayOf(0x1F9CD, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 23, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CE), 0, 1), listOf("kneeling_person"), 46, 48, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB), 0, 2), emptyList<String>(), 46, 49, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC), 0, 2), emptyList<String>(), 46, 50, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD), 0, 2), emptyList<String>(), 46, 51, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE), 0, 2), emptyList<String>(), 46, 52, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF), 0, 2), emptyList<String>(), 46, 53, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CE, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_kneeling"), 46, 42, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 43, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 44, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 45, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 46, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 46, 47, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9CE, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_kneeling"), 46, 36, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 37, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 38, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 39, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 40, false),
FacebookEmoji(String(intArrayOf(0x1F9CE, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 46, 41, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D1, 0x200D, 0x1F9AF), 0, 3), listOf("person_with_probing_cane"), 49, 6, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 7, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 8, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 9, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 10, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 49, 11, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F468, 0x200D, 0x1F9AF), 0, 3), listOf("man_with_probing_cane"), 15, 23, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 24, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 25, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 26, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 27, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 15, 28, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F469, 0x200D, 0x1F9AF), 0, 3), listOf("woman_with_probing_cane"), 18, 52, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 53, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 54, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 55, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 56, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9AF), 0, 4), emptyList<String>(), 18, 57, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D1, 0x200D, 0x1F9BC), 0, 3), listOf("person_in_motorized_wheelchair"), 49, 36, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 37, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 38, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 39, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 40, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 49, 41, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F468, 0x200D, 0x1F9BC), 0, 3), listOf("man_in_motorized_wheelchair"), 15, 53, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 54, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 55, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 56, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 57, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 15, 58, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F469, 0x200D, 0x1F9BC), 0, 3), listOf("woman_in_motorized_wheelchair"), 19, 21, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 22, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 23, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 24, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 25, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9BC), 0, 4), emptyList<String>(), 19, 26, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D1, 0x200D, 0x1F9BD), 0, 3), listOf("person_in_manual_wheelchair"), 49, 42, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 43, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 44, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 45, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 46, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 49, 47, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F468, 0x200D, 0x1F9BD), 0, 3), listOf("man_in_manual_wheelchair"), 15, 59, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 15, 60, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 0, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 1, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 2, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 16, 3, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F469, 0x200D, 0x1F9BD), 0, 3), listOf("woman_in_manual_wheelchair"), 19, 27, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 28, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 29, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 30, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 31, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F9BD), 0, 4), emptyList<String>(), 19, 32, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C3), 0, 1), listOf("runner", "running"), 8, 26, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB), 0, 2), emptyList<String>(), 8, 27, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC), 0, 2), emptyList<String>(), 8, 28, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD), 0, 2), emptyList<String>(), 8, 29, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE), 0, 2), emptyList<String>(), 8, 30, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF), 0, 2), emptyList<String>(), 8, 31, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C3, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-running"), 8, 20, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 21, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 22, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 23, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 24, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 25, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C3, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-running"), 8, 14, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 15, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 16, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 17, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 18, false),
FacebookEmoji(String(intArrayOf(0x1F3C3, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 19, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F483), 0, 1), listOf("dancer"), 25, 46, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F483, 0x1F3FB), 0, 2), emptyList<String>(), 25, 47, false),
FacebookEmoji(String(intArrayOf(0x1F483, 0x1F3FC), 0, 2), emptyList<String>(), 25, 48, false),
FacebookEmoji(String(intArrayOf(0x1F483, 0x1F3FD), 0, 2), emptyList<String>(), 25, 49, false),
FacebookEmoji(String(intArrayOf(0x1F483, 0x1F3FE), 0, 2), emptyList<String>(), 25, 50, false),
FacebookEmoji(String(intArrayOf(0x1F483, 0x1F3FF), 0, 2), emptyList<String>(), 25, 51, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F57A), 0, 1), listOf("man_dancing"), 31, 26, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F57A, 0x1F3FB), 0, 2), emptyList<String>(), 31, 27, false),
FacebookEmoji(String(intArrayOf(0x1F57A, 0x1F3FC), 0, 2), emptyList<String>(), 31, 28, false),
FacebookEmoji(String(intArrayOf(0x1F57A, 0x1F3FD), 0, 2), emptyList<String>(), 31, 29, false),
FacebookEmoji(String(intArrayOf(0x1F57A, 0x1F3FE), 0, 2), emptyList<String>(), 31, 30, false),
FacebookEmoji(String(intArrayOf(0x1F57A, 0x1F3FF), 0, 2), emptyList<String>(), 31, 31, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F574, 0xFE0F), 0, 2), listOf("man_in_business_suit_levitating"), 30, 59, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F574, 0x1F3FB), 0, 2), emptyList<String>(), 30, 60, false),
FacebookEmoji(String(intArrayOf(0x1F574, 0x1F3FC), 0, 2), emptyList<String>(), 31, 0, false),
FacebookEmoji(String(intArrayOf(0x1F574, 0x1F3FD), 0, 2), emptyList<String>(), 31, 1, false),
FacebookEmoji(String(intArrayOf(0x1F574, 0x1F3FE), 0, 2), emptyList<String>(), 31, 2, false),
FacebookEmoji(String(intArrayOf(0x1F574, 0x1F3FF), 0, 2), emptyList<String>(), 31, 3, false),
),
),
FacebookEmoji(String(intArrayOf(0x1F46F), 0, 1), listOf("dancers"), 23, 16, true),
FacebookEmoji(String(intArrayOf(0x1F46F, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("men-with-bunny-ears-partying", "man-with-bunny-ears-partying"), 23, 15, false),
FacebookEmoji(String(intArrayOf(0x1F46F, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("women-with-bunny-ears-partying", "woman-with-bunny-ears-partying"), 23, 14, false),
FacebookEmoji(
String(intArrayOf(0x1F9D6), 0, 1), listOf("person_in_steamy_room"), 50, 59, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB), 0, 2), emptyList<String>(), 50, 60, true),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC), 0, 2), emptyList<String>(), 51, 0, true),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD), 0, 2), emptyList<String>(), 51, 1, true),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE), 0, 2), emptyList<String>(), 51, 2, true),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF), 0, 2), emptyList<String>(), 51, 3, true),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D6, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_in_steamy_room"), 50, 53, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 54, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 55, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 56, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 57, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 50, 58, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D6, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_in_steamy_room"), 50, 47, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 48, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 49, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 50, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 51, false),
FacebookEmoji(String(intArrayOf(0x1F9D6, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 50, 52, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D7), 0, 1), listOf("person_climbing"), 51, 16, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB), 0, 2), emptyList<String>(), 51, 17, true),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC), 0, 2), emptyList<String>(), 51, 18, true),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD), 0, 2), emptyList<String>(), 51, 19, true),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE), 0, 2), emptyList<String>(), 51, 20, true),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF), 0, 2), emptyList<String>(), 51, 21, true),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D7, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_climbing"), 51, 10, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 11, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 12, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 13, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 14, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 15, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D7, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_climbing"), 51, 4, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 5, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 6, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 7, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 8, false),
FacebookEmoji(String(intArrayOf(0x1F9D7, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 9, false),
),
),
FacebookEmoji(String(intArrayOf(0x1F93A), 0, 1), listOf("fencer"), 42, 31, false),
FacebookEmoji(
String(intArrayOf(0x1F3C7), 0, 1), listOf("horse_racing"), 8, 52, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C7, 0x1F3FB), 0, 2), emptyList<String>(), 8, 53, false),
FacebookEmoji(String(intArrayOf(0x1F3C7, 0x1F3FC), 0, 2), emptyList<String>(), 8, 54, false),
FacebookEmoji(String(intArrayOf(0x1F3C7, 0x1F3FD), 0, 2), emptyList<String>(), 8, 55, false),
FacebookEmoji(String(intArrayOf(0x1F3C7, 0x1F3FE), 0, 2), emptyList<String>(), 8, 56, false),
FacebookEmoji(String(intArrayOf(0x1F3C7, 0x1F3FF), 0, 2), emptyList<String>(), 8, 57, false),
),
),
FacebookEmoji(String(intArrayOf(0x26F7, 0xFE0F), 0, 2), listOf("skier"), 58, 1, false),
FacebookEmoji(
String(intArrayOf(0x1F3C2), 0, 1), listOf("snowboarder"), 8, 8, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C2, 0x1F3FB), 0, 2), emptyList<String>(), 8, 9, false),
FacebookEmoji(String(intArrayOf(0x1F3C2, 0x1F3FC), 0, 2), emptyList<String>(), 8, 10, false),
FacebookEmoji(String(intArrayOf(0x1F3C2, 0x1F3FD), 0, 2), emptyList<String>(), 8, 11, false),
FacebookEmoji(String(intArrayOf(0x1F3C2, 0x1F3FE), 0, 2), emptyList<String>(), 8, 12, false),
FacebookEmoji(String(intArrayOf(0x1F3C2, 0x1F3FF), 0, 2), emptyList<String>(), 8, 13, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3CC, 0xFE0F), 0, 2), listOf("golfer"), 9, 47, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3CC, 0x1F3FB), 0, 2), emptyList<String>(), 9, 48, false),
FacebookEmoji(String(intArrayOf(0x1F3CC, 0x1F3FC), 0, 2), emptyList<String>(), 9, 49, false),
FacebookEmoji(String(intArrayOf(0x1F3CC, 0x1F3FD), 0, 2), emptyList<String>(), 9, 50, false),
FacebookEmoji(String(intArrayOf(0x1F3CC, 0x1F3FE), 0, 2), emptyList<String>(), 9, 51, false),
FacebookEmoji(String(intArrayOf(0x1F3CC, 0x1F3FF), 0, 2), emptyList<String>(), 9, 52, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C4), 0, 1), listOf("surfer"), 8, 44, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB), 0, 2), emptyList<String>(), 8, 45, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC), 0, 2), emptyList<String>(), 8, 46, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD), 0, 2), emptyList<String>(), 8, 47, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE), 0, 2), emptyList<String>(), 8, 48, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF), 0, 2), emptyList<String>(), 8, 49, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C4, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-surfing"), 8, 38, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 39, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 40, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 41, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 42, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 8, 43, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3C4, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-surfing"), 8, 32, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 33, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 34, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 35, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 36, false),
FacebookEmoji(String(intArrayOf(0x1F3C4, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 8, 37, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6A3), 0, 1), listOf("rowboat"), 36, 18, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB), 0, 2), emptyList<String>(), 36, 19, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC), 0, 2), emptyList<String>(), 36, 20, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD), 0, 2), emptyList<String>(), 36, 21, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE), 0, 2), emptyList<String>(), 36, 22, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF), 0, 2), emptyList<String>(), 36, 23, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6A3, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-rowing-boat"), 36, 12, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 13, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 14, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 15, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 16, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 17, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6A3, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-rowing-boat"), 36, 6, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 7, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 8, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 9, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 10, false),
FacebookEmoji(String(intArrayOf(0x1F6A3, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 11, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3CA), 0, 1), listOf("swimmer"), 9, 11, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB), 0, 2), emptyList<String>(), 9, 12, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC), 0, 2), emptyList<String>(), 9, 13, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD), 0, 2), emptyList<String>(), 9, 14, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE), 0, 2), emptyList<String>(), 9, 15, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF), 0, 2), emptyList<String>(), 9, 16, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3CA, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-swimming"), 9, 5, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 6, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 7, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 8, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 9, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 9, 10, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3CA, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-swimming"), 8, 60, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 0, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 1, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 2, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 3, false),
FacebookEmoji(String(intArrayOf(0x1F3CA, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 9, 4, false),
),
),
FacebookEmoji(
String(intArrayOf(0x26F9, 0xFE0F), 0, 2), listOf("person_with_ball"), 58, 15, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x26F9, 0x1F3FB), 0, 2), emptyList<String>(), 58, 16, false),
FacebookEmoji(String(intArrayOf(0x26F9, 0x1F3FC), 0, 2), emptyList<String>(), 58, 17, false),
FacebookEmoji(String(intArrayOf(0x26F9, 0x1F3FD), 0, 2), emptyList<String>(), 58, 18, false),
FacebookEmoji(String(intArrayOf(0x26F9, 0x1F3FE), 0, 2), emptyList<String>(), 58, 19, false),
FacebookEmoji(String(intArrayOf(0x26F9, 0x1F3FF), 0, 2), emptyList<String>(), 58, 20, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F3CB, 0xFE0F), 0, 2), listOf("weight_lifter"), 9, 29, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F3CB, 0x1F3FB), 0, 2), emptyList<String>(), 9, 30, false),
FacebookEmoji(String(intArrayOf(0x1F3CB, 0x1F3FC), 0, 2), emptyList<String>(), 9, 31, false),
FacebookEmoji(String(intArrayOf(0x1F3CB, 0x1F3FD), 0, 2), emptyList<String>(), 9, 32, false),
FacebookEmoji(String(intArrayOf(0x1F3CB, 0x1F3FE), 0, 2), emptyList<String>(), 9, 33, false),
FacebookEmoji(String(intArrayOf(0x1F3CB, 0x1F3FF), 0, 2), emptyList<String>(), 9, 34, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B4), 0, 1), listOf("bicyclist"), 36, 52, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB), 0, 2), emptyList<String>(), 36, 53, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC), 0, 2), emptyList<String>(), 36, 54, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD), 0, 2), emptyList<String>(), 36, 55, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE), 0, 2), emptyList<String>(), 36, 56, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF), 0, 2), emptyList<String>(), 36, 57, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B4, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-biking"), 36, 46, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 47, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 48, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 49, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 50, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 36, 51, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B4, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-biking"), 36, 40, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 41, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 42, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 43, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 44, false),
FacebookEmoji(String(intArrayOf(0x1F6B4, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 45, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B5), 0, 1), listOf("mountain_bicyclist"), 37, 9, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB), 0, 2), emptyList<String>(), 37, 10, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC), 0, 2), emptyList<String>(), 37, 11, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD), 0, 2), emptyList<String>(), 37, 12, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE), 0, 2), emptyList<String>(), 37, 13, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF), 0, 2), emptyList<String>(), 37, 14, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B5, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-mountain-biking"), 37, 3, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 4, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 5, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 6, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 7, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 37, 8, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6B5, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-mountain-biking"), 36, 58, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 59, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 36, 60, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 0, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 1, false),
FacebookEmoji(String(intArrayOf(0x1F6B5, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 37, 2, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F938), 0, 1), listOf("person_doing_cartwheel"), 42, 7, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FB), 0, 2), emptyList<String>(), 42, 8, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FC), 0, 2), emptyList<String>(), 42, 9, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FD), 0, 2), emptyList<String>(), 42, 10, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FE), 0, 2), emptyList<String>(), 42, 11, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FF), 0, 2), emptyList<String>(), 42, 12, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F938, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-cartwheeling"), 42, 1, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 2, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 3, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 4, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 5, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 6, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F938, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-cartwheeling"), 41, 56, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 57, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 58, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 59, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 41, 60, false),
FacebookEmoji(String(intArrayOf(0x1F938, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 0, false),
),
),
FacebookEmoji(String(intArrayOf(0x1F93C), 0, 1), listOf("wrestlers"), 42, 34, true),
FacebookEmoji(String(intArrayOf(0x1F93C, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-wrestling"), 42, 33, false),
FacebookEmoji(String(intArrayOf(0x1F93C, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-wrestling"), 42, 32, false),
FacebookEmoji(
String(intArrayOf(0x1F93D), 0, 1), listOf("water_polo"), 42, 47, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FB), 0, 2), emptyList<String>(), 42, 48, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FC), 0, 2), emptyList<String>(), 42, 49, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FD), 0, 2), emptyList<String>(), 42, 50, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FE), 0, 2), emptyList<String>(), 42, 51, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FF), 0, 2), emptyList<String>(), 42, 52, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F93D, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-playing-water-polo"), 42, 41, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 42, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 43, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 44, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 45, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 46, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F93D, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-playing-water-polo"), 42, 35, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 36, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 37, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 38, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 39, false),
FacebookEmoji(String(intArrayOf(0x1F93D, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 40, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F93E), 0, 1), listOf("handball"), 43, 4, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FB), 0, 2), emptyList<String>(), 43, 5, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FC), 0, 2), emptyList<String>(), 43, 6, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FD), 0, 2), emptyList<String>(), 43, 7, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FE), 0, 2), emptyList<String>(), 43, 8, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FF), 0, 2), emptyList<String>(), 43, 9, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F93E, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-playing-handball"), 42, 59, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 60, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 0, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 1, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 2, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 43, 3, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F93E, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-playing-handball"), 42, 53, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 54, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 55, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 56, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 57, false),
FacebookEmoji(String(intArrayOf(0x1F93E, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 58, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F939), 0, 1), listOf("juggling"), 42, 25, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FB), 0, 2), emptyList<String>(), 42, 26, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FC), 0, 2), emptyList<String>(), 42, 27, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FD), 0, 2), emptyList<String>(), 42, 28, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FE), 0, 2), emptyList<String>(), 42, 29, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FF), 0, 2), emptyList<String>(), 42, 30, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F939, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man-juggling"), 42, 19, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 20, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 21, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 22, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 23, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 42, 24, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F939, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman-juggling"), 42, 13, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 14, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 15, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 16, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 17, false),
FacebookEmoji(String(intArrayOf(0x1F939, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 42, 18, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D8), 0, 1), listOf("person_in_lotus_position"), 51, 34, true,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB), 0, 2), emptyList<String>(), 51, 35, true),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC), 0, 2), emptyList<String>(), 51, 36, true),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD), 0, 2), emptyList<String>(), 51, 37, true),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE), 0, 2), emptyList<String>(), 51, 38, true),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF), 0, 2), emptyList<String>(), 51, 39, true),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D8, 0x200D, 0x2642, 0xFE0F), 0, 4), listOf("man_in_lotus_position"), 51, 28, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 29, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 30, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 31, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 32, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF, 0x200D, 0x2642, 0xFE0F), 0, 5), emptyList<String>(), 51, 33, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D8, 0x200D, 0x2640, 0xFE0F), 0, 4), listOf("woman_in_lotus_position"), 51, 22, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FB, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 23, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FC, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 24, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FD, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 25, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FE, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 26, false),
FacebookEmoji(String(intArrayOf(0x1F9D8, 0x1F3FF, 0x200D, 0x2640, 0xFE0F), 0, 5), emptyList<String>(), 51, 27, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6C0), 0, 1), listOf("bath"), 37, 42, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6C0, 0x1F3FB), 0, 2), emptyList<String>(), 37, 43, false),
FacebookEmoji(String(intArrayOf(0x1F6C0, 0x1F3FC), 0, 2), emptyList<String>(), 37, 44, false),
FacebookEmoji(String(intArrayOf(0x1F6C0, 0x1F3FD), 0, 2), emptyList<String>(), 37, 45, false),
FacebookEmoji(String(intArrayOf(0x1F6C0, 0x1F3FE), 0, 2), emptyList<String>(), 37, 46, false),
FacebookEmoji(String(intArrayOf(0x1F6C0, 0x1F3FF), 0, 2), emptyList<String>(), 37, 47, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F6CC), 0, 1), listOf("sleeping_accommodation"), 37, 54, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F6CC, 0x1F3FB), 0, 2), emptyList<String>(), 37, 55, false),
FacebookEmoji(String(intArrayOf(0x1F6CC, 0x1F3FC), 0, 2), emptyList<String>(), 37, 56, false),
FacebookEmoji(String(intArrayOf(0x1F6CC, 0x1F3FD), 0, 2), emptyList<String>(), 37, 57, false),
FacebookEmoji(String(intArrayOf(0x1F6CC, 0x1F3FE), 0, 2), emptyList<String>(), 37, 58, false),
FacebookEmoji(String(intArrayOf(0x1F6CC, 0x1F3FF), 0, 2), emptyList<String>(), 37, 59, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F9D1, 0x200D, 0x1F91D, 0x200D, 0x1F9D1), 0, 5), listOf("people_holding_hands"), 48, 41, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FB, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FB), 0, 7), emptyList<String>(), 48, 42, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FB), 0, 7), emptyList<String>(), 48, 47, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FC), 0, 7), emptyList<String>(), 48, 48, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FB), 0, 7), emptyList<String>(), 48, 52, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FC), 0, 7), emptyList<String>(), 48, 53, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FD), 0, 7), emptyList<String>(), 48, 54, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FB), 0, 7), emptyList<String>(), 48, 57, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FC), 0, 7), emptyList<String>(), 48, 58, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FD), 0, 7), emptyList<String>(), 48, 59, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FE), 0, 7), emptyList<String>(), 48, 60, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FB), 0, 7), emptyList<String>(), 49, 1, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FC), 0, 7), emptyList<String>(), 49, 2, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FD), 0, 7), emptyList<String>(), 49, 3, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FE), 0, 7), emptyList<String>(), 49, 4, false),
FacebookEmoji(String(intArrayOf(0x1F9D1, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F9D1, 0x1F3FF), 0, 7), emptyList<String>(), 49, 5, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F46D), 0, 1), listOf("two_women_holding_hands", "women_holding_hands"), 22, 31, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F46D, 0x1F3FB), 0, 2), emptyList<String>(), 22, 32, false),
FacebookEmoji(String(intArrayOf(0x1F46D, 0x1F3FC), 0, 2), emptyList<String>(), 22, 33, false),
FacebookEmoji(String(intArrayOf(0x1F46D, 0x1F3FD), 0, 2), emptyList<String>(), 22, 34, false),
FacebookEmoji(String(intArrayOf(0x1F46D, 0x1F3FE), 0, 2), emptyList<String>(), 22, 35, false),
FacebookEmoji(String(intArrayOf(0x1F46D, 0x1F3FF), 0, 2), emptyList<String>(), 22, 36, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FB), 0, 7), emptyList<String>(), 22, 41, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FB), 0, 7), emptyList<String>(), 22, 45, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FC), 0, 7), emptyList<String>(), 22, 46, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FB), 0, 7), emptyList<String>(), 22, 49, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FC), 0, 7), emptyList<String>(), 22, 50, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FD), 0, 7), emptyList<String>(), 22, 51, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FB), 0, 7), emptyList<String>(), 22, 53, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FC), 0, 7), emptyList<String>(), 22, 54, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FD), 0, 7), emptyList<String>(), 22, 55, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F469, 0x1F3FE), 0, 7), emptyList<String>(), 22, 56, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F46B), 0, 1), listOf("man_and_woman_holding_hands", "woman_and_man_holding_hands", "couple"), 21, 40, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F46B, 0x1F3FB), 0, 2), emptyList<String>(), 21, 41, false),
FacebookEmoji(String(intArrayOf(0x1F46B, 0x1F3FC), 0, 2), emptyList<String>(), 21, 42, false),
FacebookEmoji(String(intArrayOf(0x1F46B, 0x1F3FD), 0, 2), emptyList<String>(), 21, 43, false),
FacebookEmoji(String(intArrayOf(0x1F46B, 0x1F3FE), 0, 2), emptyList<String>(), 21, 44, false),
FacebookEmoji(String(intArrayOf(0x1F46B, 0x1F3FF), 0, 2), emptyList<String>(), 21, 45, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 21, 46, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 21, 47, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FE), 0, 7), emptyList<String>(), 21, 48, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FB, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FF), 0, 7), emptyList<String>(), 21, 49, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 21, 50, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 21, 51, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FE), 0, 7), emptyList<String>(), 21, 52, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FF), 0, 7), emptyList<String>(), 21, 53, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 21, 54, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 21, 55, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FE), 0, 7), emptyList<String>(), 21, 56, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FF), 0, 7), emptyList<String>(), 21, 57, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 21, 58, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 21, 59, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 21, 60, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FF), 0, 7), emptyList<String>(), 22, 0, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 22, 1, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 22, 2, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 22, 3, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FE), 0, 7), emptyList<String>(), 22, 4, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F46C), 0, 1), listOf("two_men_holding_hands", "men_holding_hands"), 22, 5, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F46C, 0x1F3FB), 0, 2), emptyList<String>(), 22, 6, false),
FacebookEmoji(String(intArrayOf(0x1F46C, 0x1F3FC), 0, 2), emptyList<String>(), 22, 7, false),
FacebookEmoji(String(intArrayOf(0x1F46C, 0x1F3FD), 0, 2), emptyList<String>(), 22, 8, false),
FacebookEmoji(String(intArrayOf(0x1F46C, 0x1F3FE), 0, 2), emptyList<String>(), 22, 9, false),
FacebookEmoji(String(intArrayOf(0x1F46C, 0x1F3FF), 0, 2), emptyList<String>(), 22, 10, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FC, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 22, 15, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 22, 19, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FD, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 22, 20, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 22, 23, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 22, 24, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FE, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 22, 25, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FB), 0, 7), emptyList<String>(), 22, 27, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FC), 0, 7), emptyList<String>(), 22, 28, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FD), 0, 7), emptyList<String>(), 22, 29, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x1F3FF, 0x200D, 0x1F91D, 0x200D, 0x1F468, 0x1F3FE), 0, 7), emptyList<String>(), 22, 30, false),
),
),
FacebookEmoji(
String(intArrayOf(0x1F48F), 0, 1), listOf("couplekiss"), 26, 41, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F48F, 0x1F3FB), 0, 2), emptyList<String>(), 26, 42, false),
FacebookEmoji(String(intArrayOf(0x1F48F, 0x1F3FC), 0, 2), emptyList<String>(), 26, 43, false),
FacebookEmoji(String(intArrayOf(0x1F48F, 0x1F3FD), 0, 2), emptyList<String>(), 26, 44, false),
FacebookEmoji(String(intArrayOf(0x1F48F, 0x1F3FE), 0, 2), emptyList<String>(), 26, 45, false),
FacebookEmoji(String(intArrayOf(0x1F48F, 0x1F3FF), 0, 2), emptyList<String>(), 26, 46, false),
),
),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F48B, 0x200D, 0x1F468), 0, 8), listOf("woman-kiss-man"), 20, 42, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F48B, 0x200D, 0x1F468), 0, 8), listOf("man-kiss-man"), 16, 48, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F48B, 0x200D, 0x1F469), 0, 8), listOf("woman-kiss-woman"), 21, 7, false),
FacebookEmoji(
String(intArrayOf(0x1F491), 0, 1), listOf("couple_with_heart"), 27, 7, false,
variants = listOf(
FacebookEmoji(String(intArrayOf(0x1F491, 0x1F3FB), 0, 2), emptyList<String>(), 27, 8, false),
FacebookEmoji(String(intArrayOf(0x1F491, 0x1F3FC), 0, 2), emptyList<String>(), 27, 9, false),
FacebookEmoji(String(intArrayOf(0x1F491, 0x1F3FD), 0, 2), emptyList<String>(), 27, 10, false),
FacebookEmoji(String(intArrayOf(0x1F491, 0x1F3FE), 0, 2), emptyList<String>(), 27, 11, false),
FacebookEmoji(String(intArrayOf(0x1F491, 0x1F3FF), 0, 2), emptyList<String>(), 27, 12, false),
),
),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F468), 0, 6), listOf("woman-heart-man"), 19, 51, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F468), 0, 6), listOf("man-heart-man"), 16, 22, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x2764, 0xFE0F, 0x200D, 0x1F469), 0, 6), listOf("woman-heart-woman"), 20, 16, false),
FacebookEmoji(String(intArrayOf(0x1F46A), 0, 1), listOf("family"), 21, 39, true),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F466), 0, 5), listOf("man-woman-boy"), 14, 43, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F467), 0, 5), listOf("man-woman-girl"), 14, 45, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F467, 0x200D, 0x1F466), 0, 7), listOf("man-woman-girl-boy"), 14, 46, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F466, 0x200D, 0x1F466), 0, 7), listOf("man-woman-boy-boy"), 14, 44, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F467, 0x200D, 0x1F467), 0, 7), listOf("man-woman-girl-girl"), 14, 47, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F468, 0x200D, 0x1F466), 0, 5), listOf("man-man-boy"), 14, 38, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F468, 0x200D, 0x1F467), 0, 5), listOf("man-man-girl"), 14, 40, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F468, 0x200D, 0x1F467, 0x200D, 0x1F466), 0, 7), listOf("man-man-girl-boy"), 14, 41, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F468, 0x200D, 0x1F466, 0x200D, 0x1F466), 0, 7), listOf("man-man-boy-boy"), 14, 39, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F468, 0x200D, 0x1F467, 0x200D, 0x1F467), 0, 7), listOf("man-man-girl-girl"), 14, 42, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F469, 0x200D, 0x1F466), 0, 5), listOf("woman-woman-boy"), 18, 11, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F469, 0x200D, 0x1F467), 0, 5), listOf("woman-woman-girl"), 18, 13, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F469, 0x200D, 0x1F467, 0x200D, 0x1F466), 0, 7), listOf("woman-woman-girl-boy"), 18, 14, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F469, 0x200D, 0x1F466, 0x200D, 0x1F466), 0, 7), listOf("woman-woman-boy-boy"), 18, 12, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F469, 0x200D, 0x1F467, 0x200D, 0x1F467), 0, 7), listOf("woman-woman-girl-girl"), 18, 15, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F466), 0, 3), listOf("man-boy"), 14, 34, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F466, 0x200D, 0x1F466), 0, 5), listOf("man-boy-boy"), 14, 33, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F467), 0, 3), listOf("man-girl"), 14, 37, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F467, 0x200D, 0x1F466), 0, 5), listOf("man-girl-boy"), 14, 35, false),
FacebookEmoji(String(intArrayOf(0x1F468, 0x200D, 0x1F467, 0x200D, 0x1F467), 0, 5), listOf("man-girl-girl"), 14, 36, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F466), 0, 3), listOf("woman-boy"), 18, 7, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F466, 0x200D, 0x1F466), 0, 5), listOf("woman-boy-boy"), 18, 6, false),
FacebookEmoji(String(intArrayOf(0x1F469, 0x200D, 0x1F467), 0, 3), listOf("woman-girl"), 18, 10, false),
)
}
| apache-2.0 | 8f10e2238791120cc02bacd57a90a3e3 | 78.275138 | 168 | 0.666341 | 2.685935 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/run/configurations/UnityAttachToEditorSettingsEditor.kt | 1 | 1651 | package com.jetbrains.rider.plugins.unity.run.configurations
import com.intellij.execution.impl.CheckableRunConfigurationEditor
import com.intellij.openapi.options.SettingsEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.rd.defineNestedLifetime
import com.jetbrains.rd.util.lifetime.LifetimeDefinition
class UnityAttachToEditorSettingsEditor(project: Project) : SettingsEditor<UnityAttachToEditorRunConfiguration>(),
CheckableRunConfigurationEditor<UnityAttachToEditorRunConfiguration> {
private val lifetimeDefinition: LifetimeDefinition = project.defineNestedLifetime()
private val viewModel: UnityAttachToEditorViewModel = UnityAttachToEditorViewModel(lifetimeDefinition.lifetime, project)
private val form: UnityAttachToEditorForm = UnityAttachToEditorForm(viewModel)
init {
// This doesn't work, because this editor seems to be wrapped, and any listeners
// subscribe to the wrapper, not this class, so firing this doesn't do any good.
viewModel.pid.advise(lifetimeDefinition.lifetime) { fireEditorStateChanged() }
}
override fun checkEditorData(configuration: UnityAttachToEditorRunConfiguration) {
configuration.pid = viewModel.pid.value
}
override fun resetEditorFrom(configuration: UnityAttachToEditorRunConfiguration) {
viewModel.pid.value = configuration.pid
}
override fun applyEditorTo(configuration: UnityAttachToEditorRunConfiguration) {
checkEditorData(configuration)
}
override fun createEditor() = form.panel
override fun disposeEditor() {
lifetimeDefinition.terminate()
}
} | apache-2.0 | 3fdd65a10394428b731078c9c7cf97dd | 41.358974 | 124 | 0.786796 | 5.521739 | false | true | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/render/AnimationTimer.kt | 2 | 711 | package com.cout970.magneticraft.misc.render
/**
* Created by cout970 on 16/07/2016.
*/
class AnimationTimer {
var active = true
var lastTime = System.currentTimeMillis()
var animationStage = 0f
fun updateAnimation() {
animationStage += getDelta().toFloat()
resetDelta()
}
fun resetDelta() {
lastTime = System.currentTimeMillis()
}
fun getDelta() = (System.currentTimeMillis() - lastTime).toDouble() / 1000
fun getRotationState(speed: Float): Float {
return (animationStage * speed) % 360
}
fun getMotionState(speed: Float): Float {
return Math.sin(Math.toRadians(getRotationState(speed).toDouble())).toFloat()
}
} | gpl-2.0 | 9c49f82b1342172a85f018501f773978 | 22.733333 | 85 | 0.648383 | 4.283133 | false | false | false | false |
lispyclouds/bob | src/main/kotlin/bob/core/primitives/job/Serialization.kt | 1 | 1979 | /*
* This file is part of Bob.
*
* Bob 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.
*
* Bob 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 Bob. If not, see <http://www.gnu.org/licenses/>.
*/
package bob.core.primitives.job
import bob.core.primitives.env.getEnv
import bob.core.primitives.task.getTask
import bob.util.jsonStringOf
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import kotlinx.collections.immutable.toImmutableList
private data class RawJob(
val id: String?,
val name: String,
val envId: String?,
val tasks: List<String>
)
// TODO 7: Remove !! when (1) is done
fun Job.toJson() = jsonStringOf(RawJob(
this.id,
this.name,
this.env?.id,
this.tasks.map { it.id!! }
))
fun jsonToJob(json: String) = try {
val job = Gson().fromJson(json, RawJob::class.java)
val env = when (job.envId) {
null -> null
"" -> null
else -> getEnv(job.envId)
}
// TODO 4: Remove when Gson has @Required
@Suppress("SENSELESS_COMPARISON")
when {
job?.tasks == null || job.name == null -> null
else -> {
val tasks = job.tasks.map { getTask(it) }
when {
tasks.any { it == null } -> null
else -> Job(
job.id,
job.name,
env,
job.tasks.map { getTask(it)!! }.toImmutableList()
)
}
}
}
} catch (_: JsonSyntaxException) {
null
}
| gpl-3.0 | 01ce027f1e6e287b9a019f2032dfa27a | 27.271429 | 71 | 0.613441 | 3.926587 | false | false | false | false |
spark/photon-tinker-android | mesh/src/main/java/io/particle/mesh/common/Delegates.kt | 1 | 1527 | package io.particle.mesh.common
import mu.KLogger
import mu.KotlinLogging
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun <T> KLogger.logged(): ReadWriteProperty<Any?, T?> = NullableLogWhenSetVar(this)
fun <T> KLogger.logged(initialValue: T): ReadWriteProperty<Any?, T> {
return NonNullLogWhenSetVar(initialValue, this)
}
private class NullableLogWhenSetVar<T>(logger: KLogger?) : ReadWriteProperty<Any?, T?> {
private val log: KLogger = logger ?: KotlinLogging.logger {}
private var value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
return value
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
if (this.value != value) {
log.info { "'${property.name}' value being updated to: $value" }
}
this.value = value
}
}
// this seems like I'm clearly doing something wrong by needing this whole second class...
private class NonNullLogWhenSetVar<T>(initialValue: T, logger: KLogger?) :
ReadWriteProperty<Any?, T> {
private val log: KLogger = logger ?: KotlinLogging.logger {}
private var value: T = initialValue
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
if (this.value != value) {
log.info { "'${property.name}' value being updated to: $value" }
}
this.value = value
}
}
| apache-2.0 | b3885e7eadd65f3e3dc70c0a49e90a7b | 28.365385 | 90 | 0.660118 | 4.206612 | false | false | false | false |
fnouama/intellij-community | plugins/settings-repository/src/git/CommitMessageFormatter.kt | 9 | 2585 | /*
* 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 org.jetbrains.settingsRepository.git
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import org.eclipse.jgit.lib.Ref
import org.eclipse.jgit.merge.MergeMessageFormatter
import java.net.InetAddress
public interface CommitMessageFormatter {
public fun message(text: String): String = text
public fun prependMessage(builder: StringBuilder = StringBuilder()): StringBuilder = builder
public fun mergeMessage(refsToMerge: List<Ref>, target: Ref): String = MergeMessageFormatter().format(refsToMerge, target)
}
class IdeaCommitMessageFormatter : CommitMessageFormatter {
override fun message(text: String) = StringBuilder().appendCommitOwnerInfo().append(text).toString()
override fun prependMessage(builder: StringBuilder) = builder.appendCommitOwnerInfo()
override fun mergeMessage(refsToMerge: List<Ref>, target: Ref) = StringBuilder().appendCommitOwnerInfo().append(super.mergeMessage(refsToMerge, target)).toString()
fun StringBuilder.appendCommitOwnerInfo(avoidAppInfoInstantiation: Boolean = false): StringBuilder {
if (avoidAppInfoInstantiation) {
append(ApplicationNamesInfo.getInstance().productName)
}
else {
appendAppName()
}
append(' ').append('<').append(System.getProperty("user.name", "unknown-user")).append('@').append(InetAddress.getLocalHost().hostName)
append(' ')
return this
}
fun StringBuilder.appendAppName() {
val appInfo = ApplicationInfoEx.getInstanceEx()
if (appInfo != null) {
val build = appInfo.build
append(build.productCode).append('-')
if (appInfo.majorVersion != null && !appInfo.isEAP) {
append(appInfo.fullVersion)
}
else {
var buildString = build.asStringWithoutProductCode()
if (build.buildNumber == Integer.MAX_VALUE) {
buildString = buildString.replace(".SNAPSHOT", "")
}
append(buildString)
}
}
}
} | apache-2.0 | e47813fc8c9cfdfebe92597fb8cc125c | 37.029412 | 165 | 0.732689 | 4.543058 | false | false | false | false |
android/camera-samples | CameraXVideo/utils/src/main/java/com/example/android/camera/utils/AutoFitSurfaceView.kt | 7 | 2782 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.camera.utils
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceView
import kotlin.math.roundToInt
/**
* A [SurfaceView] that can be adjusted to a specified aspect ratio and
* performs center-crop transformation of input frames.
*/
class AutoFitSurfaceView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : SurfaceView(context, attrs, defStyle) {
private var aspectRatio = 0f
/**
* Sets the aspect ratio for this view. The size of the view will be
* measured based on the ratio calculated from the parameters.
*
* @param width Camera resolution horizontal size
* @param height Camera resolution vertical size
*/
fun setAspectRatio(width: Int, height: Int) {
require(width > 0 && height > 0) { "Size cannot be negative" }
aspectRatio = width.toFloat() / height.toFloat()
holder.setFixedSize(width, height)
requestLayout()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
if (aspectRatio == 0f) {
setMeasuredDimension(width, height)
} else {
// Performs center-crop transformation of the camera frames
val newWidth: Int
val newHeight: Int
val actualRatio = if (width > height) aspectRatio else 1f / aspectRatio
if (width < height * actualRatio) {
newHeight = height
newWidth = (height * actualRatio).roundToInt()
} else {
newWidth = width
newHeight = (width / actualRatio).roundToInt()
}
Log.d(TAG, "Measured dimensions set: $newWidth x $newHeight")
setMeasuredDimension(newWidth, newHeight)
}
}
companion object {
private val TAG = AutoFitSurfaceView::class.java.simpleName
}
}
| apache-2.0 | 29252bc94bbfc049489712e20a3bcb21 | 34.21519 | 83 | 0.664989 | 4.788296 | false | false | false | false |
CarrotCodes/Warren | src/test/kotlin/chat/willow/warren/handler/QuitHandlerTests.kt | 1 | 4741 | package chat.willow.warren.handler
import chat.willow.kale.helper.CaseMapping
import chat.willow.kale.irc.message.rfc1459.QuitMessage
import chat.willow.kale.irc.prefix.Prefix
import chat.willow.kale.irc.prefix.prefix
import chat.willow.kale.irc.tag.TagStore
import chat.willow.warren.event.ConnectionLifecycleEvent
import chat.willow.warren.event.IWarrenEvent
import chat.willow.warren.event.IWarrenEventDispatcher
import chat.willow.warren.state.*
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.verify
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class QuitHandlerTests {
lateinit var handler: QuitHandler
lateinit var connectionState: ConnectionState
lateinit var channelsState: ChannelsState
lateinit var mockEventDispatcher: IWarrenEventDispatcher
val caseMappingState = CaseMappingState(mapping = CaseMapping.RFC1459)
@Before fun setUp() {
val lifecycleState = LifecycleState.CONNECTED
connectionState = ConnectionState(server = "test.server", port = 6697, nickname = "test-nick", user = "test-nick", lifecycle = lifecycleState)
channelsState = emptyChannelsState(caseMappingState)
mockEventDispatcher = mock()
handler = QuitHandler(mockEventDispatcher, connectionState, channelsState.joined)
}
@Test fun test_handle_SourceIsNull_DoesNothing() {
channelsState.joined += ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("someone", "someone-else"), mappingState = caseMappingState))
handler.handle(QuitMessage.Message(source = prefix("")), TagStore())
val expectedChannelOneState = ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("someone", "someone-else"), mappingState = caseMappingState))
val expectedChannelsState = channelsStateWith(listOf(expectedChannelOneState), caseMappingState)
assertEquals(channelsState, expectedChannelsState)
}
@Test fun test_handle_SourceIsSelf_ChangesConnectionStateToDisconnected() {
channelsState.joined += ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("test-nick", "someone-else"), mappingState = caseMappingState))
channelsState.joined += ChannelState(name = "#channel2", users = generateUsersFromNicks(listOf("another-person", "someone-else"), mappingState = caseMappingState))
handler.handle(QuitMessage.Message(source = Prefix(nick = "test-nick")), TagStore())
val expectedChannelOneState = ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("test-nick", "someone-else"), mappingState = caseMappingState))
val expectedChannelTwoState = ChannelState(name = "#channel2", users = generateUsersFromNicks(listOf("another-person", "someone-else"), mappingState = caseMappingState))
val expectedChannelsState = channelsStateWith(listOf(expectedChannelOneState, expectedChannelTwoState), caseMappingState)
assertEquals(channelsState, expectedChannelsState)
assertEquals(connectionState.lifecycle, LifecycleState.DISCONNECTED)
}
@Test fun test_handle_SourceIsSelf_FiresDisconnectedEvent() {
handler.handle(QuitMessage.Message(source = Prefix(nick = "test-nick")), TagStore())
verify(mockEventDispatcher).fire(ConnectionLifecycleEvent(lifecycle = LifecycleState.DISCONNECTED))
}
@Test fun test_handle_SourceIsOther_RemovesUserFromChannels() {
channelsState.joined += ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("test-nick", "someone-else"), mappingState = caseMappingState))
channelsState.joined += ChannelState(name = "#channel2", users = generateUsersFromNicks(listOf("another-person", "someone-else"), mappingState = caseMappingState))
handler.handle(QuitMessage.Message(source = Prefix(nick = "someone-else")), TagStore())
val expectedChannelOneState = ChannelState(name = "#channel", users = generateUsersFromNicks(listOf("test-nick"), mappingState = caseMappingState))
val expectedChannelTwoState = ChannelState(name = "#channel2", users = generateUsersFromNicks(listOf("another-person"), mappingState = caseMappingState))
val expectedChannelsState = channelsStateWith(listOf(expectedChannelOneState, expectedChannelTwoState), caseMappingState)
assertEquals(channelsState, expectedChannelsState)
}
@Test fun test_handle_SourceIsOther_DoesNotFireDisconnectedEvent() {
handler.handle(QuitMessage.Message(source = Prefix(nick = "someone-else")), TagStore())
verify(mockEventDispatcher, never()).fire(any<IWarrenEvent>())
}
} | isc | e76d9594b2f118b6480858c62f52adc8 | 53.505747 | 177 | 0.760388 | 5.164488 | false | true | false | false |
Ekito/koin | koin-projects/koin-core-ext/src/main/kotlin/org/koin/experimental/builder/InstanceBuilder.kt | 1 | 1899 | package org.koin.experimental.builder
import org.koin.core.logger.Level
import org.koin.core.scope.Scope
import org.koin.core.time.measureDurationForResult
import org.koin.ext.getFullName
import java.lang.reflect.Constructor
/**
* Create instance for type T and inject dependencies into 1st constructor
*/
inline fun <reified T : Any> Scope.create(): T {
val kClass = T::class
val instance: Any
logger.debug("!- creating class:${kClass.getFullName()}")
val constructor = kClass.java.constructors.firstOrNull()
?: error("No constructor found for class '${kClass.getFullName()}'")
val args = if (logger.isAt(Level.DEBUG)) {
val (_args, duration) = measureDurationForResult {
getArguments(constructor, this)
}
logger.debug("!- got arguments in $duration ms")
_args
} else {
getArguments(constructor, this)
}
instance = if (logger.isAt(Level.DEBUG)) {
val (_instance, duration) = measureDurationForResult {
createInstance(args, constructor)
}
logger.debug("!- created instance in $duration ms")
_instance
} else {
createInstance(args, constructor)
}
return instance as T
}
fun createInstance(args: Array<Any>, constructor: Constructor<out Any>): Any {
return if (args.isEmpty()) {
constructor.newInstance()
} else {
constructor.newInstance(*args)
}
}
/**
* Retrieve arguments for given constructor
*/
fun getArguments(constructor: Constructor<*>, context: Scope): Array<Any> {
val length = constructor.parameterTypes.size
return if (length == 0) emptyArray()
else {
val result = Array<Any>(length) { Unit }
for (i in 0 until length) {
val p = constructor.parameterTypes[i]
result[i] = context.get(p.kotlin, null, null)
}
result
}
} | apache-2.0 | 27da6755f665bc3fcbf2680786d98c6b | 28.230769 | 80 | 0.640864 | 4.315909 | false | false | false | false |
Shynixn/BlockBall | blockball-bukkit-plugin/bukkit-nms-118R2/src/main/java/com/github/shynixn/blockball/bukkit/logic/business/service/nms/v1_18_R2/InternalVersionPacket118R2ServiceImpl.kt | 1 | 7119 | package com.github.shynixn.blockball.bukkit.logic.business.service.nms.v1_18_R2
import com.github.shynixn.blockball.api.business.enumeration.CompatibilityArmorSlotType
import com.github.shynixn.blockball.api.business.proxy.PluginProxy
import com.github.shynixn.blockball.api.business.service.InternalVersionPacketService
import com.github.shynixn.blockball.api.business.service.LoggingService
import com.github.shynixn.blockball.api.persistence.entity.EntityMetaData
import com.github.shynixn.blockball.api.persistence.entity.Position
import com.google.inject.Inject
import com.mojang.datafixers.util.Pair
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import net.minecraft.core.Registry
import net.minecraft.network.FriendlyByteBuf
import net.minecraft.network.protocol.game.ClientboundAddMobPacket
import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket
import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket
import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket
import net.minecraft.world.entity.EntityType
import net.minecraft.world.entity.EquipmentSlot
import net.minecraft.world.item.ItemStack
import java.nio.charset.Charset
import java.util.*
class InternalVersionPacket118R2ServiceImpl @Inject constructor(
private val pluginProxy: PluginProxy
) : InternalVersionPacketService {
private val craftItemStackNmsMethod by lazy {
pluginProxy.findClazz("org.bukkit.craftbukkit.VERSION.inventory.CraftItemStack")
.getDeclaredMethod("asNMSCopy", pluginProxy.findClazz("org.bukkit.inventory.ItemStack"))
}
private val enumItemSlotClazz by lazy {
try {
pluginProxy.findClazz("net.minecraft.world.entity.EnumItemSlot")
} catch (e: Exception) {
pluginProxy.findClazz("net.minecraft.server.VERSION.EnumItemSlot")
}
}
private val mojangPairClazz by lazy {
pluginProxy.findClazz("com.mojang.datafixers.util.Pair")
}
/**
* Creates a new teleport packet.
*/
override fun createEntityTeleportPacket(entityId: Int, position: Position): Any {
val buffer = FriendlyByteBuf(Unpooled.buffer())
buffer.writeId(entityId)
buffer.writeDouble(position.x)
buffer.writeDouble(position.y)
buffer.writeDouble(position.z)
buffer.writeByte((position.yaw * 256.0f / 360.0f).toInt().toByte().toInt())
buffer.writeByte((position.pitch * 256.0f / 360.0f).toInt().toByte().toInt())
buffer.writeBoolean(false)
return ClientboundTeleportEntityPacket(buffer)
}
/**
* Creates a spawn packet.
*/
override fun createEntitySpawnPacket(entityId: Int, entityType: String, position: Position): Any {
val buffer = FriendlyByteBuf(Unpooled.buffer())
buffer.writeId(entityId)
val entityUUID = UUID.randomUUID()
buffer.writeLong(entityUUID.mostSignificantBits)
buffer.writeLong(entityUUID.leastSignificantBits)
val nmsEntityType = if (entityType == "ARMOR_STAND") {
EntityType.ARMOR_STAND
} else {
EntityType.SLIME
}
val nmsEntityId = Registry.ENTITY_TYPE.getId(nmsEntityType)
buffer.writeId(nmsEntityId)
buffer.writeDouble(position.x)
buffer.writeDouble(position.y)
buffer.writeDouble(position.z)
buffer.writeByte((position.yaw * 256.0f / 360.0f).toInt().toByte().toInt())
buffer.writeByte((position.pitch * 256.0f / 360.0f).toInt().toByte().toInt())
buffer.writeByte(0)
buffer.writeShort((mathhelperA(0.0, -3.9, 3.9) * 8000.0).toInt())
buffer.writeShort((mathhelperA(0.0, -3.9, 3.9) * 8000.0).toInt())
buffer.writeShort((mathhelperA(0.0, -3.9, 3.9) * 8000.0).toInt())
return ClientboundAddMobPacket(buffer)
}
/**
* Creates a entity metadata packet.
*/
override fun createEntityMetaDataPacket(entityId: Int, entityMetaData: EntityMetaData): Any {
// https://wiki.vg/Entity_metadata#Entity_Metadata_Format -> Value of Type field. Type of Value = Boolean -> 7.
val buffer = FriendlyByteBuf(Unpooled.buffer())
buffer.writeId(entityId)
val byteTypeValue = 0
val intTypeValue = 1
val booleanTypeValue = 7
val optChatTypeValue = 5
val rotationTypeValue = 8
if (entityMetaData.customNameVisible != null) {
buffer.writeByte(3)
buffer.writeId(booleanTypeValue)
buffer.writeBoolean(entityMetaData.customNameVisible!!)
}
if (entityMetaData.customname != null) {
val payload = "{\"text\": \"${entityMetaData.customname}\"}".toByteArray(Charset.forName("UTF-8"))
buffer.writeByte(2)
buffer.writeId(optChatTypeValue)
buffer.writeBoolean(true)
buffer.writeId(payload.size)
buffer.writeBytes(payload)
}
if (entityMetaData.slimeSize != null) {
val slimeSizeIndex = 16
buffer.writeByte(slimeSizeIndex)
buffer.writeId(intTypeValue)
buffer.writeId(entityMetaData.slimeSize!!)
}
if (entityMetaData.armorstandHeadRotation != null) {
buffer.writeByte(16)
buffer.writeId(rotationTypeValue)
buffer.writeFloat(entityMetaData.armorstandHeadRotation!!.x.toFloat())
buffer.writeFloat(entityMetaData.armorstandHeadRotation!!.y.toFloat())
buffer.writeFloat(entityMetaData.armorstandHeadRotation!!.z.toFloat())
}
if (entityMetaData.isInvisible != null) {
buffer.writeByte(0)
buffer.writeId(byteTypeValue)
buffer.writeByte(0x20)
}
if (entityMetaData.isSmall != null && entityMetaData.isSmall!!) {
buffer.writeByte(15)
buffer.writeId(byteTypeValue)
buffer.writeByte(0x01)
}
buffer.writeByte(255)
return ClientboundSetEntityDataPacket(buffer)
}
/**
* Creates an entity equipment packet.
*/
override fun <I> createEntityEquipmentPacket(entityId: Int, slot: CompatibilityArmorSlotType, itemStack: I): Any {
val nmsItemStack = craftItemStackNmsMethod.invoke(null, itemStack)
val pair = mojangPairClazz.getDeclaredConstructor(Any::class.java, Any::class.java)
.newInstance(enumItemSlotClazz.enumConstants[slot.id116], nmsItemStack)
return ClientboundSetEquipmentPacket(
entityId,
mutableListOf(pair) as MutableList<Pair<EquipmentSlot, ItemStack>>?
)
}
/**
* Mathhelper
*/
private fun mathhelperA(var0: Double, var2: Double, var4: Double): Double {
return if (var0 < var2) {
var2
} else {
if (var0 > var4) var4 else var0
}
}
/**
* Writes id.
*/
private fun ByteBuf.writeId(id: Int) {
var i = id
while (i and -128 != 0) {
writeByte(i and 127 or 128)
i = i ushr 7
}
writeByte(i)
}
}
| apache-2.0 | 33af5f14d85e202ff2740dce27f95761 | 37.481081 | 119 | 0.669897 | 4.362132 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/settings/RegionPreferenceView.kt | 1 | 1301 | package com.garpr.android.features.settings
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.garpr.android.R
import com.garpr.android.data.models.Region
import com.garpr.android.features.common.views.SimplePreferenceView
class RegionPreferenceView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : SimplePreferenceView(context, attrs), View.OnClickListener {
var listener: Listener? = null
interface Listener {
fun onClick(v: RegionPreferenceView)
}
init {
titleText = context.getText(R.string.region)
setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_location_on_white_24dp))
setOnClickListener(this)
if (isInEditMode) {
descriptionText = context.getString(R.string.region_endpoint_format,
context.getString(R.string.norcal), context.getString(R.string.gar_pr))
}
}
override fun onClick(v: View) {
listener?.onClick(this)
}
fun setContent(region: Region) {
descriptionText = context.getString(R.string.region_endpoint_format,
region.displayName, context.getText(region.endpoint.title))
}
}
| unlicense | 4125db3d3394f917a76c6f049ef03e8f | 29.97619 | 98 | 0.707148 | 4.351171 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/postgres/PostgresResultSetAdapters.kt | 1 | 9716 | package com.openlattice.postgres
import com.dataloom.mappers.ObjectMappers
import com.fasterxml.jackson.module.kotlin.readValue
import com.openlattice.IdConstants.LAST_WRITE_ID
import com.openlattice.data.storage.ByteBlobDataManager
import com.openlattice.data.storage.MetadataOption
import com.openlattice.data.storage.PROPERTIES
import com.openlattice.data.storage.VALUE
import com.openlattice.edm.EdmConstants.Companion.ID_FQN
import com.openlattice.edm.EdmConstants.Companion.LAST_WRITE_FQN
import com.openlattice.edm.type.PropertyType
import com.openlattice.postgres.ResultSetAdapters.*
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind
import org.apache.olingo.commons.api.edm.FullQualifiedName
import org.slf4j.LoggerFactory
import java.sql.*
import java.sql.Date
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneId
import java.util.*
internal class PostgresResultSetAdapters
private val logger = LoggerFactory.getLogger(PostgresResultSetAdapters::class.java)
private val mapper = ObjectMappers.newJsonMapper()
@Throws(SQLException::class)
fun getEntityPropertiesByPropertyTypeId(
rs: ResultSet,
authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>,
metadataOptions: Set<MetadataOption>,
byteBlobDataManager: ByteBlobDataManager
): Pair<UUID, MutableMap<UUID, MutableSet<Any>>> {
val id = id(rs)
val entitySetId = entitySetId(rs)
val propertyTypes = authorizedPropertyTypes.getValue(entitySetId)
val entity = readJsonDataColumns(
rs,
propertyTypes,
byteBlobDataManager
)
// TODO Do we need ID column in properties?
if (metadataOptions.contains(MetadataOption.LAST_WRITE)) {
entity[LAST_WRITE_ID.id] = mutableSetOf<Any>(lastWriteTyped(rs))
}
return id to entity
}
/**
* Returns linked entity data from the [ResultSet] mapped respectively by its id, entity set, origin id and property
* type id.
* Note: Do not include the linking id for the [IdConstants.ID_ID] key as a property for this adapter, because it is
* used for linked entity indexing and we preserve that key for the origin id.
* @see ConductorElasticsearchImpl.formatLinkedEntity
*/
@Throws(SQLException::class)
fun getEntityPropertiesByEntitySetIdOriginIdAndPropertyTypeId(
rs: ResultSet,
authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>,
metadataOptions: Set<MetadataOption>,
byteBlobDataManager: ByteBlobDataManager
): Pair<UUID, Pair<UUID, Map<UUID, MutableMap<UUID, MutableSet<Any>>>>> {
val id = id(rs)
val entitySetId = entitySetId(rs)
val propertyTypes = authorizedPropertyTypes.getValue(entitySetId)
val lastWrite = if (metadataOptions.contains(MetadataOption.LAST_WRITE)) {
Optional.of(lastWriteTyped(rs))
} else {
Optional.empty()
}
val entities = readJsonDataColumnsWithId(rs, propertyTypes, byteBlobDataManager, lastWrite)
return id to (entitySetId to entities)
}
/**
* Returns linked entity data from the [ResultSet] mapped respectively by its id, entity set, origin id and property
* full qualified name.
*/
@Throws(SQLException::class)
fun getEntityPropertiesByEntitySetIdOriginIdAndPropertyTypeFqn(
rs: ResultSet,
authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>,
metadataOptions: Set<MetadataOption>,
byteBlobDataManager: ByteBlobDataManager
): Pair<UUID, Pair<UUID, Map<UUID, MutableMap<FullQualifiedName, MutableSet<Any>>>>> {
val id = id(rs)
val entitySetId = entitySetId(rs)
val propertyTypes = authorizedPropertyTypes.getValue(entitySetId)
val lastWrite = if (metadataOptions.contains(MetadataOption.LAST_WRITE)) {
Optional.of(lastWriteTyped(rs))
} else {
Optional.empty()
}
val entities = readJsonDataColumnsWithId(rs, propertyTypes, byteBlobDataManager, lastWrite)
val entityByFqn = entities.mapValues { (_, propertyValues) ->
propertyValues.mapKeys {
if (it.key == LAST_WRITE_ID.id) {
LAST_WRITE_FQN
} else {
propertyTypes.getValue(it.key).type
}
}.toMutableMap()
}
return id to (entitySetId to entityByFqn)
}
@Throws(SQLException::class)
fun getEntityPropertiesByFullQualifiedName(
rs: ResultSet,
authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>,
metadataOptions: Set<MetadataOption>,
byteBlobDataManager: ByteBlobDataManager
): Pair<UUID, MutableMap<FullQualifiedName, MutableSet<Any>>> {
val id = id(rs)
val entitySetId = entitySetId(rs)
val propertyTypes = authorizedPropertyTypes.getValue(entitySetId)
val entity = readJsonDataColumns(rs, propertyTypes, byteBlobDataManager)
val entityByFqn = entity.mapKeys { propertyTypes.getValue(it.key).type }.toMutableMap()
entityByFqn[ID_FQN] = mutableSetOf<Any>(id.toString())
if (metadataOptions.contains(MetadataOption.LAST_WRITE)) {
entityByFqn[LAST_WRITE_FQN] = mutableSetOf<Any>(lastWriteTyped(rs))
}
return id to entityByFqn
}
@Throws(SQLException::class)
fun readJsonDataColumns(
rs: ResultSet,
propertyTypes: Map<UUID, PropertyType>,
byteBlobDataManager: ByteBlobDataManager
): MutableMap<UUID, MutableSet<Any>> {
val entity = mapper.readValue<MutableMap<UUID, MutableSet<Any>>>(rs.getString(PROPERTIES))
// Note: this call deletes all entries from result, which is not in propertyTypes (ID for example)
(entity.keys - propertyTypes.keys).forEach { entity.remove(it) }
propertyTypes.forEach { (_, propertyType) ->
if (propertyType.datatype == EdmPrimitiveTypeKind.Binary) {
val urls = entity.getOrElse(propertyType.id) { mutableSetOf() }
if (urls.isNotEmpty()) {
entity[propertyType.id] = byteBlobDataManager.getObjects(urls).toMutableSet()
}
}
}
return entity
}
@Throws(SQLException::class)
fun readJsonDataColumnsWithId(
rs: ResultSet,
propertyTypes: Map<UUID, PropertyType>,
byteBlobDataManager: ByteBlobDataManager,
lastWrite: Optional<OffsetDateTime>
): MutableMap<UUID, MutableMap<UUID, MutableSet<Any>>> {
val lastWriteIncluded = lastWrite.isPresent
val detailedEntity = mapper.readValue<MutableMap<UUID, MutableSet<MutableMap<String, Any>>>>(rs.getString(PROPERTIES))
val entities = mutableMapOf<UUID, MutableMap<UUID, MutableSet<Any>>>() // origin id -> property type id -> values
detailedEntity.forEach { (propertyTypeId, details) ->
// only select properties which are authorized
if (propertyTypes.keys.contains(propertyTypeId)) {
details.forEach { entityDetail ->
val originId = UUID.fromString(entityDetail[PostgresColumn.ID_VALUE.name] as String)
val propertyValue = entityDetail.getValue(VALUE)
if (!entities.containsKey(originId)) {
entities[originId] = mutableMapOf(propertyTypeId to mutableSetOf(propertyValue))
} else {
entities.getValue(originId)[propertyTypeId] = mutableSetOf(propertyValue)
}
if (lastWriteIncluded) {
entities.getValue(originId)[LAST_WRITE_ID.id] = mutableSetOf<Any>(lastWrite.get())
}
}
}
}
propertyTypes.forEach { (_, propertyType) ->
if (propertyType.datatype == EdmPrimitiveTypeKind.Binary) {
entities.forEach { (_, entity) ->
val urls = entity.getOrElse(propertyType.id) { mutableSetOf() }
if (urls.isNotEmpty()) {
entity[propertyType.id] = byteBlobDataManager.getObjects(urls).toMutableSet()
}
}
}
}
return entities
}
//TODO: If we are getting NPEs on read we may have to do better filtering here.
@Throws(SQLException::class)
private fun propertyValue(rs: ResultSet, propertyType: PropertyType): List<*>? {
val fqn = propertyType.type.fullQualifiedNameAsString
val arr = rs.getArray(fqn)
return if (arr != null) {
when (propertyType.datatype) {
EdmPrimitiveTypeKind.String, EdmPrimitiveTypeKind.GeographyPoint -> (arr.array as Array<String>).toList()
EdmPrimitiveTypeKind.Guid -> (arr.array as Array<UUID>).toList()
EdmPrimitiveTypeKind.Byte -> rs.getBytes(fqn)?.toList()
EdmPrimitiveTypeKind.Int16 -> (arr.array as Array<Short>).toList()
EdmPrimitiveTypeKind.Int32 -> (arr.array as Array<Int>).toList()
EdmPrimitiveTypeKind.Duration, EdmPrimitiveTypeKind.Int64 -> (arr.array as Array<Long>).toList()
EdmPrimitiveTypeKind.Date -> (arr.array as Array<Date>).map { it.toLocalDate() }
EdmPrimitiveTypeKind.TimeOfDay -> (arr.array as Array<Time>).map { it.toLocalTime() }
EdmPrimitiveTypeKind.DateTimeOffset -> (arr.array as Array<Timestamp>)
.map { ts ->
OffsetDateTime
.ofInstant(Instant.ofEpochMilli(ts.time), ZoneId.of("UTC"))
}
EdmPrimitiveTypeKind.Double -> (arr.array as Array<Double>).toList()
EdmPrimitiveTypeKind.Boolean -> (arr.array as Array<Boolean>).toList()
EdmPrimitiveTypeKind.Binary -> (arr.array as Array<String>).toList()
else -> {
logger.error(
"Unable to read property type {}.",
propertyType.id
)
null
}
}
} else {
null
}
} | gpl-3.0 | 1a79608d01362e7ef3bb3fd1748c5cbe | 37.868 | 122 | 0.678571 | 4.82423 | false | false | false | false |
JimSeker/ui | Communication/FragComNavLiveDemo_kt/app/src/main/java/edu/cs4730/fragcomnavlivedemo_kt/SecondFragment.kt | 1 | 1559 | package edu.cs4730.fragcomnavlivedemo_kt
import androidx.navigation.Navigation.findNavController
import android.widget.TextView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
/**
*
*/
class SecondFragment : Fragment() {
lateinit var tv1: TextView
lateinit var tv2: TextView
lateinit var btn1: Button
lateinit var mViewModel: DataViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val myView = inflater.inflate(R.layout.fragment_second, container, false)
mViewModel = ViewModelProvider(requireActivity()).get(DataViewModel::class.java)
mViewModel.gettwoLD().observe(viewLifecycleOwner) { v -> tv1.text = "Parameter1: $v" }
mViewModel.itemLD.observe(viewLifecycleOwner) { s -> tv2.text = "Parameter1: $s" }
tv1 = myView.findViewById(R.id.sf_tv1)
tv2 = myView.findViewById(R.id.sf_tv2)
btn1 = myView.findViewById(R.id.sf_btn1)
btn1.setOnClickListener(View.OnClickListener { v -> //this is calling the interface, which call into the activity, so it
mViewModel.incr_One()
mViewModel.setItem("Called by SecondFragment")
findNavController(v).navigate(R.id.action_second_to_first)
})
return myView
}
} | apache-2.0 | 25c718f489c5488f3669094132ffad0b | 37.04878 | 128 | 0.710071 | 4.259563 | false | false | false | false |
italoag/qksms | data/src/main/java/com/moez/QKSMS/blocking/CallBlockerBlockingClient.kt | 3 | 3583 | /*
* Copyright (C) 2020 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.blocking
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import androidx.core.database.getStringOrNull
import com.moez.QKSMS.common.util.extensions.isInstalled
import com.moez.QKSMS.extensions.map
import io.reactivex.Completable
import io.reactivex.Single
import timber.log.Timber
import java.util.*
import javax.inject.Inject
class CallBlockerBlockingClient @Inject constructor(
private val context: Context
) : BlockingClient {
class LookupResult(cursor: Cursor) {
val blockReason: String? = cursor.getStringOrNull(0)
}
override fun isAvailable(): Boolean = context.isInstalled("com.cuiet.blockCalls")
override fun getClientCapability() = BlockingClient.Capability.BLOCK_WITH_PERMISSION
override fun shouldBlock(address: String): Single<BlockingClient.Action> = lookup(address, "incomingNumber")
override fun isBlacklisted(address: String): Single<BlockingClient.Action> = lookup(address, "blacklistLookup")
private fun lookup(address: String, reason: String): Single<BlockingClient.Action> = Single.fromCallable {
val uri = Uri.parse("content://com.cuiet.blockCalls.ContProvBlockCalls/lookup/is.blocked.lookup")
return@fromCallable try {
val blockReason = context.contentResolver.query(uri, arrayOf("result"), reason, arrayOf(address), null)
?.use { cursor -> cursor.map(::LookupResult) }
?.find { result -> result.blockReason != null }
?.blockReason
when (blockReason) {
"true" -> BlockingClient.Action.Block()
else -> BlockingClient.Action.Unblock
}
} catch (e: Exception) {
Timber.w(e)
BlockingClient.Action.DoNothing
}
}
override fun block(addresses: List<String>): Completable = Completable.fromCallable {
val arrayList = ArrayList<String>()
arrayList.addAll(addresses)
val intent = Intent("com.cuiet.blockCalls.ADD_NUMBERS")
intent.putStringArrayListExtra("addresses", arrayList)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
override fun unblock(addresses: List<String>): Completable = Completable.fromCallable {
val arrayList = ArrayList<String>()
arrayList.addAll(addresses)
val intent = Intent("com.cuiet.blockCalls.REMOVE_NUMBERS")
intent.putStringArrayListExtra("addresses", arrayList)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
override fun openSettings() {
val intent = Intent("com.cuiet.blockCalls.OPEN_SETTINGS")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
}
| gpl-3.0 | 970c913a3c6af61044090eb161ef920d | 38.373626 | 115 | 0.701088 | 4.473159 | false | false | false | false |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/business/home/adapter/RecommendAdapter.kt | 1 | 3687 | package me.sweetll.tucao.business.home.adapter
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import me.sweetll.tucao.R
import me.sweetll.tucao.model.json.Video
import me.sweetll.tucao.extension.formatByWan
import me.sweetll.tucao.extension.load
import me.sweetll.tucao.model.json.Channel
class RecommendAdapter(data: MutableList<Pair<Channel, List<Video>>>?): BaseQuickAdapter<Pair<Channel, List<Video>>, BaseViewHolder>(R.layout.item_recommend_video, data) {
override fun convert(helper: BaseViewHolder, item: Pair<Channel, List<Video>>) {
val channel = item.first
helper.setText(R.id.text_channel, channel.name)
item.second.take(4).forEachIndexed {
index, result ->
val thumbImg: ImageView
val playText: TextView
val titleText: TextView
when (index) {
0 -> {
thumbImg = helper.getView(R.id.img_thumb1)
playText = helper.getView(R.id.text_play1)
titleText = helper.getView(R.id.text_title1)
helper.setTag(R.id.card1, result.hid)
helper.addOnClickListener(R.id.card1)
}
1 -> {
thumbImg = helper.getView(R.id.img_thumb2)
playText = helper.getView(R.id.text_play2)
titleText = helper.getView(R.id.text_title2)
helper.setTag(R.id.card2, result.hid)
helper.addOnClickListener(R.id.card2)
}
2 -> {
thumbImg = helper.getView(R.id.img_thumb3)
playText = helper.getView(R.id.text_play3)
titleText = helper.getView(R.id.text_title3)
helper.setTag(R.id.card3, result.hid)
helper.addOnClickListener(R.id.card3)
}
else -> {
thumbImg = helper.getView(R.id.img_thumb4)
playText = helper.getView(R.id.text_play4)
titleText = helper.getView(R.id.text_title4)
helper.setTag(R.id.card4, result.hid)
helper.addOnClickListener(R.id.card4)
}
}
titleText.tag = result.thumb
thumbImg.load(mContext, result.thumb)
playText.text = result.play.formatByWan()
titleText.text = result.title
}
for (index in item.second.size .. 3) {
when (index) {
0 -> {
helper.getView<View>(R.id.card1).visibility = View.INVISIBLE
}
1 -> {
helper.getView<View>(R.id.card2).visibility = View.INVISIBLE
}
2 -> {
helper.getView<View>(R.id.card3).visibility = View.INVISIBLE
}
else -> {
helper.getView<View>(R.id.card4).visibility = View.INVISIBLE
}
}
}
if (channel.id != 0) {
helper.setText(R.id.text_more, "更多${channel.name}内容")
helper.setTag(R.id.card_more, channel.id)
helper.setGone(R.id.card_more, true)
helper.setGone(R.id.img_rank, false)
helper.addOnClickListener(R.id.card_more)
} else {
helper.setGone(R.id.card_more, false)
helper.setGone(R.id.img_rank, true)
helper.addOnClickListener(R.id.img_rank)
}
}
} | mit | 79acab642eb133b4e55f03638ffaa723 | 39.888889 | 171 | 0.543898 | 4.15237 | false | false | false | false |
vhromada/Catalog-Swing | src/main/kotlin/cz/vhromada/catalog/gui/game/GameInfoDialog.kt | 1 | 9525 | package cz.vhromada.catalog.gui.game
import cz.vhromada.catalog.entity.Game
import cz.vhromada.catalog.gui.common.AbstractInfoDialog
import cz.vhromada.catalog.gui.common.CatalogSwingConstants
import javax.swing.GroupLayout
import javax.swing.JCheckBox
import javax.swing.JLabel
import javax.swing.JSpinner
import javax.swing.JTextField
import javax.swing.SpinnerNumberModel
/**
* A class represents dialog for game.
*
* @author Vladimir Hromada
*/
class GameInfoDialog : AbstractInfoDialog<Game> {
/**
* Label for name
*/
private val nameLabel = JLabel("Name")
/**
* Text field for name
*/
private val nameData = JTextField()
/**
* Label for czech Wikipedia
*/
private val wikiCzLabel = JLabel("Czech Wikipedia")
/**
* Text field for czech Wikipedia
*/
private val wikiCzData = JTextField()
/**
* Label for english Wikipedia
*/
private val wikiEnLabel = JLabel("English Wikipedia")
/**
* Text field for english Wikipedia
*/
private val wikiEnData = JTextField()
/**
* Label for count of media
*/
private val mediaCountLabel = JLabel("Count of media")
/**
* Spinner for count of media
*/
private val mediaCountData = JSpinner(SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1))
/**
* Check box for crack
*/
private val crackData = JCheckBox("Crack")
/**
* Check box for serial key
*/
private val serialData = JCheckBox("Serial key")
/**
* Check box for patch
*/
private val patchData = JCheckBox("Patch")
/**
* Check box for trainer
*/
private val trainerData = JCheckBox("Trainer")
/**
* Check box for data for trainer
*/
private val trainerDataData = JCheckBox("Data for trainer")
/**
* Check box for editor
*/
private val editorData = JCheckBox("Editor")
/**
* Check box for saves
*/
private val savesData = JCheckBox("Saves")
/**
* Label for other data
*/
private val otherDataLabel = JLabel("Other data")
/**
* Text field for other data
*/
private val otherDataData = JTextField()
/**
* Label for note
*/
private val noteLabel = JLabel("Note")
/**
* Text field for note
*/
private val noteData = JTextField()
/**
* Creates a new instance of GameInfoDialog.
*/
constructor() {
init()
}
/**
* Creates a new instance of GameInfoDialog.
*
* @param game game
*/
constructor(game: Game) : super(game) {
init()
this.nameData.text = game.name
this.wikiCzData.text = game.wikiCz
this.wikiEnData.text = game.wikiEn
this.mediaCountData.value = game.mediaCount
this.crackData.isSelected = game.crack!!
this.serialData.isSelected = game.serialKey!!
this.patchData.isSelected = game.patch!!
this.trainerData.isSelected = game.trainer!!
this.trainerDataData.isSelected = game.trainerData!!
this.editorData.isSelected = game.editor!!
this.savesData.isSelected = game.saves!!
this.otherDataData.text = game.otherData
this.noteData.text = game.note
}
override fun initComponents() {
initLabelComponent(nameLabel, nameData)
initLabelComponent(wikiCzLabel, wikiCzData)
initLabelComponent(wikiEnLabel, wikiEnData)
initLabelComponent(mediaCountLabel, mediaCountData)
initLabelComponent(otherDataLabel, otherDataData)
initLabelComponent(noteLabel, noteData)
addInputValidator(nameData)
}
override fun processData(objectData: Game?): Game {
if (objectData == null) {
return Game(id = null,
name = nameData.text,
wikiCz = wikiCzData.text,
wikiEn = wikiEnData.text,
mediaCount = mediaCountData.value as Int,
crack = crackData.isSelected,
serialKey = serialData.isSelected,
patch = patchData.isSelected,
trainer = trainerData.isSelected,
trainerData = trainerDataData.isSelected,
editor = editorData.isSelected,
saves = savesData.isSelected,
otherData = otherDataData.text,
note = noteData.text,
position = null)
}
return objectData.copy(name = nameData.text,
wikiCz = wikiCzData.text,
wikiEn = wikiEnData.text,
mediaCount = mediaCountData.value as Int,
crack = crackData.isSelected,
serialKey = serialData.isSelected,
patch = patchData.isSelected,
trainer = trainerData.isSelected,
trainerData = trainerDataData.isSelected,
editor = editorData.isSelected,
saves = savesData.isSelected,
otherData = otherDataData.text,
note = noteData.text)
}
/**
* Returns true if input is valid: name isn't empty string.
*
* @return true if input is valid: name isn't empty string
*/
override fun isInputValid(): Boolean {
return nameData.text.isNotBlank()
}
override fun getHorizontalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createHorizontalComponents(layout, nameLabel, nameData))
.addGroup(createHorizontalComponents(layout, wikiCzLabel, wikiCzData))
.addGroup(createHorizontalComponents(layout, wikiEnLabel, wikiEnData))
.addGroup(createHorizontalComponents(layout, mediaCountLabel, mediaCountData))
.addComponent(crackData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(serialData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(patchData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(trainerData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(trainerDataData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(editorData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addComponent(savesData, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE, HORIZONTAL_LONG_COMPONENT_SIZE)
.addGroup(createHorizontalComponents(layout, otherDataLabel, otherDataData))
.addGroup(createHorizontalComponents(layout, noteLabel, noteData))
}
@Suppress("DuplicatedCode")
override fun getVerticalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createVerticalComponents(layout, nameLabel, nameData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, wikiCzLabel, wikiCzData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, wikiEnLabel, wikiEnData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, mediaCountLabel, mediaCountData))
.addGap(VERTICAL_GAP_SIZE)
.addComponent(crackData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(serialData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(patchData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(trainerData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(trainerDataData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(editorData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(savesData, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, otherDataLabel, otherDataData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, noteLabel, noteData))
}
}
| mit | 59a140666184a1bad7e68b5218bcef6e | 38.036885 | 187 | 0.650919 | 5.165401 | false | false | false | false |
apiote/Bimba | app/src/main/java/ml/adamsprogs/bimba/models/Plate.kt | 1 | 3099 | package ml.adamsprogs.bimba.models
import java.io.Serializable
data class Plate(val id: ID, val departures: HashMap<Int, HashSet<Departure>>?) {
override fun toString(): String {
var result = "${id.line}=${id.stop}=${id.headsign}={"
if (departures != null) {
for ((service, column) in departures) {
result += service.toString() + ":"
for (departure in column) {
result += departure.toString() + ";"
}
}
}
result += "}"
return result
}
companion object {
/*fun fromString(string: String): Plate {
val (lineStr, stopStr, headsign, departuresString) = string.split("=")
val departures = HashMap<Int, HashSet<Departure>>()
departuresString.replace("{", "").replace("}", "").split(";")
.filter { it != "" }
.forEach {
try {
val (serviceStr, depStr) = it.split(":")
val dep = Departure.fromString(depStr)
if (departures[serviceStr] == null)
departures[serviceStr] = HashSet()
departures[serviceStr]!!.add(dep)
} catch (e: IllegalArgumentException) {
}
}
return Plate(ID(lineStr, stopStr, headsign), departures)
}
fun join(set: Set<Plate>): HashMap<String, ArrayList<Departure>> {
val departures = HashMap<String, ArrayList<Departure>>()
for (plate in set) {
for ((mode, d) in plate.departures!!) {
if (departures[mode] == null)
departures[mode] = ArrayList()
departures[mode]!!.addAll(d)
}
}
for ((mode, _) in departures) {
departures[mode]?.sortBy { it.time }
}
return departures
}*/
}
data class ID(val line: String, val stop: String, val headsign: String) : Serializable {
companion object {
val dummy = Plate.ID("", "", "")
fun fromString(string: String): ID {
val (line, stop, headsign) = string.split("|")
return ID(line,
stop, headsign)
}
}
override fun equals(other: Any?): Boolean {
if (other !is ID)
return false
return line == other.line && stop == other.stop && headsign.toLowerCase() == other.headsign.toLowerCase()
}
override fun toString(): String {
return "$line|$stop|$headsign"
}
override fun hashCode(): Int {
var result = line.hashCode()
result = 31 * result + stop.hashCode()
result = 31 * result + headsign.hashCode()
return result
}
constructor(other: Plate.ID) : this(other.line, other.stop, other.headsign)
}
} | gpl-3.0 | c3c2802f1c6a2a20ebba8a080ab3f8c7 | 35.470588 | 117 | 0.475637 | 5.047231 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/schema/shared/SchemaRepositoryTest.kt | 1 | 4353 | package com.infinum.dbinspector.domain.schema.shared
import com.infinum.dbinspector.data.models.local.cursor.input.Query
import com.infinum.dbinspector.data.models.local.cursor.output.QueryResult
import com.infinum.dbinspector.domain.Control
import com.infinum.dbinspector.domain.shared.base.BaseInteractor
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.core.qualifier.StringQualifier
import org.koin.dsl.module
import org.koin.test.get
import org.mockito.kotlin.any
@DisplayName("SchemaRepository tests")
internal class SchemaRepositoryTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory(qualifier = StringQualifier("getPage")) { mockk<BaseInteractor<Query, QueryResult>>() }
factory(qualifier = StringQualifier("getByName")) { mockk<BaseInteractor<Query, QueryResult>>() }
factory(qualifier = StringQualifier("dropByName")) { mockk<BaseInteractor<Query, QueryResult>>() }
factory { mockk<Control.Content>() }
}
)
@Test
fun `Can be instantiated`() {
val repository = object : SchemaRepository(
get(qualifier = StringQualifier("getPage")),
get(qualifier = StringQualifier("getByName")),
get(qualifier = StringQualifier("dropByName")),
get()
) {}
assertNotNull(repository)
}
@Test
fun `Get schema page calls interactor and control once`() {
val interactor: BaseInteractor<Query, QueryResult> = get(qualifier = StringQualifier("getPage"))
val control: Control.Content = get()
val repository = object : SchemaRepository(
interactor,
get(qualifier = StringQualifier("getByName")),
get(qualifier = StringQualifier("dropByName")),
control
) {}
coEvery { interactor.invoke(any()) } returns mockk()
coEvery { control.converter.invoke(any()) } returns mockk()
coEvery { control.mapper.invoke(any()) } returns mockk()
test {
repository.getPage(any())
}
coVerify(exactly = 1) { interactor.invoke(any()) }
coVerify(exactly = 1) { control.converter.invoke(any()) }
coVerify(exactly = 1) { control.mapper.invoke(any()) }
}
@Test
fun `Get schema by name calls interactor and control once`() {
val interactor: BaseInteractor<Query, QueryResult> = get(qualifier = StringQualifier("getByName"))
val control: Control.Content = get()
val repository = object : SchemaRepository(
get(qualifier = StringQualifier("getPage")),
interactor,
get(qualifier = StringQualifier("dropByName")),
control
) {}
coEvery { interactor.invoke(any()) } returns mockk()
coEvery { control.converter.invoke(any()) } returns mockk()
coEvery { control.mapper.invoke(any()) } returns mockk()
test {
repository.getByName(any())
}
coVerify(exactly = 1) { interactor.invoke(any()) }
coVerify(exactly = 1) { control.converter.invoke(any()) }
coVerify(exactly = 1) { control.mapper.invoke(any()) }
}
@Test
fun `Drop schema by name calls interactor and control once`() {
val interactor: BaseInteractor<Query, QueryResult> = get(qualifier = StringQualifier("dropByName"))
val control: Control.Content = get()
val repository = object : SchemaRepository(
get(qualifier = StringQualifier("getPage")),
get(qualifier = StringQualifier("getByName")),
interactor,
control
) {}
coEvery { interactor.invoke(any()) } returns mockk()
coEvery { control.converter.invoke(any()) } returns mockk()
coEvery { control.mapper.invoke(any()) } returns mockk()
test {
repository.dropByName(any())
}
coVerify(exactly = 1) { interactor.invoke(any()) }
coVerify(exactly = 1) { control.converter.invoke(any()) }
coVerify(exactly = 1) { control.mapper.invoke(any()) }
}
}
| apache-2.0 | 0582de84129fd1faccdb8b98e17278a3 | 36.852174 | 110 | 0.642086 | 4.726384 | false | true | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/StudyOptionsActivity.kt | 1 | 4677 | /***************************************************************************************
* Copyright (c) 2012 Norbert Nagold <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki
import android.os.Bundle
import android.view.MenuItem
import androidx.fragment.app.commit
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anki.StudyOptionsFragment.StudyOptionsListener
import com.ichi2.anki.dialogs.customstudy.CustomStudyDialog.CustomStudyListener
import com.ichi2.anki.dialogs.customstudy.CustomStudyDialogFactory
import com.ichi2.utils.ExtendedFragmentFactory
import com.ichi2.widget.WidgetStatus
import timber.log.Timber
class StudyOptionsActivity : NavigationDrawerActivity(), StudyOptionsListener, CustomStudyListener {
override fun onCreate(savedInstanceState: Bundle?) {
if (showedActivityFailedScreen(savedInstanceState)) {
return
}
val customStudyDialogFactory = CustomStudyDialogFactory({ this.col }, this)
customStudyDialogFactory.attachToActivity<ExtendedFragmentFactory>(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.studyoptions)
// create inherited navigation drawer layout here so that it can be used by parent class
initNavigationDrawer(findViewById(android.R.id.content))
if (savedInstanceState == null) {
loadStudyOptionsFragment()
}
}
private fun loadStudyOptionsFragment() {
var withDeckOptions = false
if (intent.extras != null) {
withDeckOptions = intent.extras!!.getBoolean("withDeckOptions")
}
val currentFragment = StudyOptionsFragment.newInstance(withDeckOptions)
supportFragmentManager.commit {
replace(R.id.studyoptions_frame, currentFragment)
}
}
private val currentFragment: StudyOptionsFragment?
get() = supportFragmentManager.findFragmentById(R.id.studyoptions_frame) as StudyOptionsFragment?
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (drawerToggle.onOptionsItemSelected(item)) {
return true
}
if (item.itemId == android.R.id.home) {
closeStudyOptions()
return true
}
return super.onOptionsItemSelected(item)
}
private fun closeStudyOptions(result: Int = RESULT_OK) {
// mCompat.invalidateOptionsMenu(this);
setResult(result)
finishWithAnimation(ActivityTransitionAnimation.Direction.END)
}
override fun onBackPressed() {
if (isDrawerOpen) {
super.onBackPressed()
} else {
Timber.i("Back key pressed")
closeStudyOptions()
}
}
public override fun onStop() {
super.onStop()
if (colIsOpen()) {
WidgetStatus.update(this)
saveCollectionInBackground()
}
}
public override fun onResume() {
super.onResume()
selectNavigationItem(-1)
}
override fun onRequireDeckListUpdate() {
currentFragment!!.refreshInterface()
}
/**
* Callback methods from CustomStudyDialog
*/
override fun onCreateCustomStudySession() {
// Sched already reset by CollectionTask in CustomStudyDialog
currentFragment!!.refreshInterface()
}
override fun onExtendStudyLimits() {
// Sched needs to be reset so provide true argument
currentFragment!!.refreshInterface(true)
}
}
| gpl-3.0 | 74d1361b9fa7bf34fa61a83b7c3fb228 | 40.026316 | 105 | 0.600171 | 5.521842 | false | false | false | false |
ebraminio/DroidPersianCalendar | PersianCalendar/src/main/java/com/byagowi/persiancalendar/utils/AthanUtils.kt | 1 | 1519 | package com.byagowi.persiancalendar.utils
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.net.toUri
import com.byagowi.persiancalendar.*
import com.byagowi.persiancalendar.service.AthanNotification
import com.byagowi.persiancalendar.ui.AthanActivity
// https://stackoverflow.com/a/27788209
fun getDefaultAthanUri(context: Context): Uri =
(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
context.resources.getResourcePackageName(R.raw.abdulbasit) + "/" +
context.resources.getResourceTypeName(R.raw.abdulbasit) + "/" +
context.resources.getResourceEntryName(R.raw.abdulbasit)).toUri()
val Context.athanVolume: Int
get() = appPrefs.getInt(PREF_ATHAN_VOLUME, DEFAULT_ATHAN_VOLUME)
val Context.isAscendingAthanVolumeEnabled: Boolean
get() = appPrefs.getBoolean(PREF_ASCENDING_ATHAN_VOLUME, false)
fun getCustomAthanUri(context: Context): Uri? =
context.appPrefs.getString(PREF_ATHAN_URI, null)?.takeUnless { it.isEmpty() }?.toUri()
fun startAthan(context: Context, prayTimeKey: String): Any? = if (notificationAthan) {
context.startService(
Intent(context, AthanNotification::class.java)
.putExtra(KEY_EXTRA_PRAYER_KEY, prayTimeKey)
)
} else {
context.startActivity(
Intent(context, AthanActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(KEY_EXTRA_PRAYER_KEY, prayTimeKey)
)
} | gpl-3.0 | 29cc298686ab800bbf93a7452695f9e9 | 37.974359 | 90 | 0.737986 | 3.826196 | false | false | false | false |
udevbe/westmalle | compositor/src/main/kotlin/org/westford/compositor/core/Output.kt | 3 | 6411 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.core
import com.google.auto.factory.AutoFactory
import com.google.auto.factory.Provided
import org.freedesktop.wayland.server.WlOutputResource
import org.freedesktop.wayland.shared.WlOutputTransform
import org.westford.Signal
import org.westford.compositor.core.calc.Mat4
import org.westford.compositor.core.events.OutputTransform
import javax.annotation.Nonnegative
@AutoFactory(className = "PrivateOutputFactory",
allowSubclasses = true) class Output(@param:Provided val regionFactory: FiniteRegionFactory,
@param:Provided var region: FiniteRegion,
val renderOutput: RenderOutput,
val name: String) {
val transformSignal = Signal<OutputTransform>()
val modeSignal = Signal<OutputMode>()
@Nonnegative @get:Nonnegative var scale = 1f
set(@Nonnegative scale) {
field = scale
updateOutputTransform()
}
/**
* translate from output space to compositor space
* @return
*/
var transform = Mat4.IDENTITY
private set
/**
* translate from compositor space to output space
* @return
*/
var inverseTransform = Mat4.IDENTITY
private set
var geometry = OutputGeometry(physicalWidth = 0,
physicalHeight = 0,
make = "",
model = "",
x = 0,
y = 0,
subpixel = 0,
transform = 0)
private set
var mode = OutputMode(width = 0,
height = 0,
refresh = 0,
flags = 0)
private set
fun update(resources: Set<WlOutputResource>,
outputGeometry: OutputGeometry) {
if (this.geometry != outputGeometry) {
this.geometry = outputGeometry
updateOutputTransform()
}
resources.forEach { this.notifyGeometry(it) }
}
private fun updateOutputTransform() {
val scaleMat = Transforms.SCALE(this.scale)
val x = this.geometry.x
val y = this.geometry.y
val moveMat = Transforms.TRANSLATE(x,
y)
val transformMat: Mat4
val transformNr = this.geometry.transform
if (transformNr == WlOutputTransform.NORMAL.value) {
transformMat = Mat4.IDENTITY
}
else if (transformNr == WlOutputTransform._90.value) {
transformMat = Transforms._90
}
else if (transformNr == WlOutputTransform._180.value) {
transformMat = Transforms._180
}
else if (transformNr == WlOutputTransform._270.value) {
transformMat = Transforms._270
}
else if (transformNr == WlOutputTransform.FLIPPED.value) {
transformMat = Transforms.FLIPPED
}
else if (transformNr == WlOutputTransform.FLIPPED_90.value) {
transformMat = Transforms.FLIPPED_90
}
else if (transformNr == WlOutputTransform.FLIPPED_180.value) {
transformMat = Transforms.FLIPPED_180
}
else if (transformNr == WlOutputTransform.FLIPPED_270.value) {
transformMat = Transforms.FLIPPED_270
}
else {
transformMat = Mat4.IDENTITY
}
val newTransform = transformMat * scaleMat * moveMat
if (this.transform != newTransform) {
this.transform = newTransform
this.inverseTransform = this.transform.invert()
updateRegion()
this.transformSignal.emit(OutputTransform())
}
}
private fun updateRegion() {
val regionTopLeft = this.transform * Point.ZERO
val regionBottomRight = this.transform * Point(this.mode.width,
this.mode.height)
//TODO fire region event?
//TODO check if the region is properly updated in the unit tests
this.region = this.regionFactory.create() + Rectangle.create(regionTopLeft,
regionBottomRight)
}
fun update(resources: Set<WlOutputResource>,
outputMode: OutputMode): Output {
if (this.mode != outputMode) {
this.mode = outputMode
updateRegion()
this.modeSignal.emit(outputMode)
}
resources.forEach { this.notifyMode(it) }
return this
}
fun notifyMode(wlOutputResource: WlOutputResource) {
wlOutputResource.mode(this.mode.flags,
this.mode.width,
this.mode.height,
this.mode.refresh)
}
fun notifyGeometry(wlOutputResource: WlOutputResource) {
wlOutputResource.geometry(this.geometry.x,
this.geometry.y,
this.geometry.physicalWidth,
this.geometry.physicalHeight,
this.geometry.subpixel,
this.geometry.make,
this.geometry.model,
this.geometry.transform)
}
fun local(global: Point): Point = this.inverseTransform * global
fun global(outputLocal: Point): Point = this.transform * outputLocal
}
| agpl-3.0 | 9fb7c30099ea2faa10d33ec6bff20c69 | 36.491228 | 105 | 0.565122 | 5.31592 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/store/WCOrderStore.kt | 2 | 37063 | package org.wordpress.android.fluxc.store
import kotlinx.coroutines.flow.Flow
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.Payload
import org.wordpress.android.fluxc.action.WCOrderAction
import org.wordpress.android.fluxc.action.WCOrderAction.FETCH_ORDERS
import org.wordpress.android.fluxc.annotations.action.Action
import org.wordpress.android.fluxc.generated.ListActionBuilder
import org.wordpress.android.fluxc.model.LocalOrRemoteId.LocalId
import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId
import org.wordpress.android.fluxc.model.OrderEntity
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.WCOrderListDescriptor
import org.wordpress.android.fluxc.model.WCOrderShipmentProviderModel
import org.wordpress.android.fluxc.model.WCOrderShipmentTrackingModel
import org.wordpress.android.fluxc.model.WCOrderStatusModel
import org.wordpress.android.fluxc.model.WCOrderSummaryModel
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult
import org.wordpress.android.fluxc.network.rest.wpcom.wc.order.OrderRestClient
import org.wordpress.android.fluxc.persistence.OrderSqlUtils
import org.wordpress.android.fluxc.persistence.dao.OrderMetaDataDao
import org.wordpress.android.fluxc.persistence.dao.OrderNotesDao
import org.wordpress.android.fluxc.persistence.dao.OrdersDao
import org.wordpress.android.fluxc.persistence.entity.OrderMetaDataEntity
import org.wordpress.android.fluxc.persistence.entity.OrderNoteEntity
import org.wordpress.android.fluxc.store.ListStore.FetchedListItemsPayload
import org.wordpress.android.fluxc.store.ListStore.ListError
import org.wordpress.android.fluxc.store.ListStore.ListErrorType
import org.wordpress.android.fluxc.store.WCOrderStore.OrderErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.store.WCOrderStore.UpdateOrderResult.OptimisticUpdateResult
import org.wordpress.android.fluxc.store.WCOrderStore.UpdateOrderResult.RemoteUpdateResult
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import org.wordpress.android.util.AppLog.T.API
import java.util.Calendar
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class WCOrderStore @Inject constructor(
dispatcher: Dispatcher,
private val wcOrderRestClient: OrderRestClient,
private val wcOrderFetcher: WCOrderFetcher,
private val coroutineEngine: CoroutineEngine,
private val ordersDao: OrdersDao,
private val orderNotesDao: OrderNotesDao,
private val orderMetaDataDao: OrderMetaDataDao,
private val insertOrder: InsertOrder
) : Store(dispatcher) {
companion object {
const val NUM_ORDERS_PER_FETCH = 15
const val DEFAULT_ORDER_STATUS = "any"
}
class FetchOrdersPayload(
var site: SiteModel,
var statusFilter: String? = null,
var loadMore: Boolean = false
) : Payload<BaseNetworkError>()
class FetchOrderListPayload(
val listDescriptor: WCOrderListDescriptor,
val offset: Long,
val requestStartTime: Calendar = Calendar.getInstance()
) : Payload<BaseNetworkError>()
class FetchOrdersByIdsPayload(
val site: SiteModel,
val orderIds: List<Long>
) : Payload<BaseNetworkError>()
data class FetchOrdersResponsePayload(
val site: SiteModel,
val ordersWithMeta: List<Pair<OrderEntity, List<OrderMetaDataEntity>>> = emptyList(),
val statusFilter: String? = null,
val loadedMore: Boolean = false,
val canLoadMore: Boolean = false
) : Payload<OrderError>() {
val orders = ordersWithMeta.map { it.first }
constructor(error: OrderError, site: SiteModel) : this(site) {
this.error = error
}
}
class FetchOrderListResponsePayload(
val listDescriptor: WCOrderListDescriptor,
var orderSummaries: List<WCOrderSummaryModel> = emptyList(),
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false,
val requestStartTime: Calendar
) : Payload<OrderError>() {
constructor(
error: OrderError,
listDescriptor: WCOrderListDescriptor,
requestStartTime: Calendar
) : this(listDescriptor, requestStartTime = requestStartTime) {
this.error = error
}
}
class FetchOrdersByIdsResponsePayload(
val site: SiteModel,
var orderIds: List<Long>,
var fetchedOrders: List<Pair<OrderEntity, List<OrderMetaDataEntity>>> = emptyList()
) : Payload<OrderError>() {
constructor(
error: OrderError,
site: SiteModel,
orderIds: List<Long>
) : this(site = site, orderIds = orderIds) {
this.error = error
}
}
class SearchOrdersPayload(
var site: SiteModel,
var searchQuery: String,
var offset: Int
) : Payload<BaseNetworkError>()
class SearchOrdersResponsePayload(
var site: SiteModel,
var searchQuery: String,
var canLoadMore: Boolean = false,
var offset: Int = 0,
var orders: List<OrderEntity> = emptyList()
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel, query: String) : this(site, query) {
this.error = error
}
}
class FetchOrdersCountPayload(
var site: SiteModel,
var statusFilter: String
) : Payload<BaseNetworkError>()
class FetchOrdersCountResponsePayload(
var site: SiteModel,
var statusFilter: String,
var count: Int = 0
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel, statusFilter: String) : this(site, statusFilter) {
this.error = error
}
}
class FetchHasOrdersResponsePayload(
var site: SiteModel,
var statusFilter: String? = null,
var hasOrders: Boolean = false
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel) : this(site) {
this.error = error
}
}
class UpdateOrderStatusPayload(
val order: OrderEntity,
val site: SiteModel,
val status: String
) : Payload<BaseNetworkError>()
sealed class RemoteOrderPayload : Payload<OrderError>() {
abstract val site: SiteModel
abstract val order: OrderEntity
data class Fetching(
val orderWithMeta: Pair<OrderEntity, List<OrderMetaDataEntity>>,
override val site: SiteModel
) : RemoteOrderPayload() {
override val order = orderWithMeta.first
constructor(
error: OrderError,
order: Pair<OrderEntity, List<OrderMetaDataEntity>>,
site: SiteModel
) : this(order, site) {
this.error = error
}
}
data class Updating(
override val order: OrderEntity,
override val site: SiteModel
) : RemoteOrderPayload() {
constructor(
error: OrderError,
order: OrderEntity,
site: SiteModel
) : this(order, site) {
this.error = error
}
}
}
sealed class UpdateOrderResult {
abstract val event: OnOrderChanged
data class OptimisticUpdateResult(override val event: OnOrderChanged) : UpdateOrderResult()
data class RemoteUpdateResult(override val event: OnOrderChanged) : UpdateOrderResult()
}
class FetchOrderStatusOptionsPayload(val site: SiteModel) : Payload<BaseNetworkError>()
class FetchOrderStatusOptionsResponsePayload(
val site: SiteModel,
val labels: List<WCOrderStatusModel> = emptyList()
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel) : this(site) {
this.error = error
}
}
class FetchOrderShipmentTrackingsResponsePayload(
var site: SiteModel,
var orderId: Long,
var trackings: List<WCOrderShipmentTrackingModel> = emptyList()
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel, orderId: Long) :
this(site, orderId) {
this.error = error
}
}
class AddOrderShipmentTrackingPayload(
val site: SiteModel,
var orderId: Long,
val tracking: WCOrderShipmentTrackingModel,
val isCustomProvider: Boolean
) : Payload<BaseNetworkError>()
class AddOrderShipmentTrackingResponsePayload(
val site: SiteModel,
var orderId: Long,
val tracking: WCOrderShipmentTrackingModel?
) : Payload<OrderError>() {
constructor(
error: OrderError,
site: SiteModel,
orderId: Long,
tracking: WCOrderShipmentTrackingModel
) : this(site, orderId, tracking) {
this.error = error
}
}
class DeleteOrderShipmentTrackingPayload(
val site: SiteModel,
var orderId: Long,
val tracking: WCOrderShipmentTrackingModel
) : Payload<BaseNetworkError>()
class DeleteOrderShipmentTrackingResponsePayload(
val site: SiteModel,
var orderId: Long,
val tracking: WCOrderShipmentTrackingModel?
) : Payload<OrderError>() {
constructor(
error: OrderError,
site: SiteModel,
orderId: Long,
tracking: WCOrderShipmentTrackingModel?
) : this(site, orderId, tracking) {
this.error = error
}
}
class FetchOrderShipmentProvidersPayload(
val site: SiteModel,
val order: OrderEntity
) : Payload<BaseNetworkError>()
class FetchOrderShipmentProvidersResponsePayload(
val site: SiteModel,
val order: OrderEntity,
val providers: List<WCOrderShipmentProviderModel> = emptyList()
) : Payload<OrderError>() {
constructor(error: OrderError, site: SiteModel, order: OrderEntity) : this(site, order) {
this.error = error
}
}
data class OrderError(val type: OrderErrorType = GENERIC_ERROR, val message: String = "") : OnChangedError
enum class OrderErrorType {
INVALID_PARAM,
INVALID_ID,
ORDER_STATUS_NOT_FOUND,
PLUGIN_NOT_ACTIVE,
INVALID_RESPONSE,
GENERIC_ERROR,
EMPTY_BILLING_EMAIL;
companion object {
private val reverseMap = values().associateBy(OrderErrorType::name)
fun fromString(type: String) = reverseMap[type.toUpperCase(Locale.US)] ?: GENERIC_ERROR
}
}
sealed class HasOrdersResult {
data class Success(val hasOrders: Boolean) : HasOrdersResult()
data class Failure(val error: OrderError) : HasOrdersResult()
}
// OnChanged events
data class OnOrderChanged(
val statusFilter: String? = null,
val canLoadMore: Boolean = false,
val causeOfChange: WCOrderAction? = null,
private val orderError: OrderError? = null
) : OnChanged<OrderError>() {
init {
super.error = orderError
}
}
/**
* Emitted after fetching a list of Order summaries from the network.
*/
class OnOrderSummariesFetched(
val listDescriptor: WCOrderListDescriptor,
val duration: Long
) : OnChanged<OrderError>()
class OnOrdersFetchedByIds(
val site: SiteModel,
val orderIds: List<Long>
) : OnChanged<OrderError>()
class OnOrdersSearched(
var searchQuery: String = "",
var canLoadMore: Boolean = false,
var nextOffset: Int = 0,
var searchResults: List<OrderEntity> = emptyList()
) : OnChanged<OrderError>()
class OnOrderStatusOptionsChanged(
var rowsAffected: Int
) : OnChanged<OrderError>()
class OnOrderShipmentProvidersChanged(
var rowsAffected: Int
) : OnChanged<OrderError>()
override fun onRegister() = AppLog.d(T.API, "WCOrderStore onRegister")
/**
* Given a [SiteModel] and optional statuses, returns all orders for that site matching any of those statuses.
*/
suspend fun getOrdersForSite(site: SiteModel, vararg status: String) = if (status.isEmpty()) {
ordersDao.getOrdersForSite(site.localId())
} else {
ordersDao.getOrdersForSite(site.localId(), status = status.asList())
}
/**
* Observe the changes to orders for a given [SiteModel]
*
* @param site the current site
* @param statuses an optional list of statuses to filter the list of orders, pass an empty list to include all
* orders
*/
fun observeOrdersForSite(site: SiteModel, statuses: List<String> = emptyList()): Flow<List<OrderEntity>> {
return if (statuses.isEmpty()) {
ordersDao.observeOrdersForSite(site.localId())
} else {
ordersDao.observeOrdersForSite(site.localId(), statuses)
}
}
/**
* Observe the changes to the number of orders for a given [SiteModel]
*
* @param site the current site
* @param statuses a list of statuses to filter the list of orders
*/
fun observeOrderCountForSite(
site: SiteModel,
statuses: List<String>
): Flow<Int> = ordersDao.observeOrderCountForSite(site.localId(), statuses)
fun getOrdersForDescriptor(
orderListDescriptor: WCOrderListDescriptor,
orderIds: List<Long>
): Map<Long, OrderEntity> {
val orders = ordersDao.getOrdersForSiteByRemoteIds(orderListDescriptor.site.localId(), orderIds)
return orders.associateBy { it.orderId }
}
fun getOrderSummariesByRemoteOrderIds(
site: SiteModel,
orderIds: List<Long>
): Map<RemoteId, WCOrderSummaryModel> {
val orderSummaries = OrderSqlUtils.getOrderSummariesForRemoteIds(site, orderIds)
return orderSummaries.associateBy { RemoteId(it.orderId) }
}
/**
* Given an order id and [SiteModel],
* returns the corresponding order from the database as a [OrderEntity].
*/
suspend fun getOrderByIdAndSite(orderId: Long, site: SiteModel): OrderEntity? {
return ordersDao.getOrder(orderId, site.localId())
}
/**
* Given an order id and [SiteModel],
* returns the metadata from the database for an order
*/
suspend fun getOrderMetadata(orderId: Long, site: SiteModel): List<OrderMetaDataEntity> {
return orderMetaDataDao.getOrderMetaData(orderId, site.localId())
}
/**
* Given an order id and [SiteModel],
* returns whether there is metadata in the database for an order
*/
suspend fun hasOrderMetadata(orderId: Long, site: SiteModel): Boolean {
return orderMetaDataDao.hasOrderMetaData(orderId, site.localId())
}
/**
* Returns the notes belonging to supplied [OrderEntity] as a list of [OrderNoteEntity].
*/
suspend fun getOrderNotesForOrder(site: SiteModel, orderId: Long): List<OrderNoteEntity> =
orderNotesDao.queryNotesOfOrder(siteId = site.remoteId(), orderId = RemoteId(orderId))
/**
* Returns the order status options available for the provided site [SiteModel] as a list of [WCOrderStatusModel].
*/
fun getOrderStatusOptionsForSite(site: SiteModel): List<WCOrderStatusModel> =
OrderSqlUtils.getOrderStatusOptionsForSite(site)
/**
* Returns the order status as a [WCOrderStatusModel] that matches the provided order status key.
*/
fun getOrderStatusForSiteAndKey(site: SiteModel, key: String): WCOrderStatusModel? =
OrderSqlUtils.getOrderStatusOptionForSiteByKey(site, key)
/**
* Returns shipment trackings as list of [WCOrderShipmentTrackingModel] for a single [OrderEntity]
*/
fun getShipmentTrackingsForOrder(site: SiteModel, orderId: Long): List<WCOrderShipmentTrackingModel> =
OrderSqlUtils.getShipmentTrackingsForOrder(site, orderId)
fun getShipmentTrackingByTrackingNumber(site: SiteModel, orderId: Long, trackingNumber: String) =
OrderSqlUtils.getShipmentTrackingByTrackingNumber(site, orderId, trackingNumber)
/**
* Returns the shipment providers as a list of [WCOrderShipmentProviderModel]
*/
fun getShipmentProvidersForSite(site: SiteModel): List<WCOrderShipmentProviderModel> =
OrderSqlUtils.getOrderShipmentProvidersForSite(site)
@Suppress("ComplexMethod", "UseCheckOrError")
@Subscribe(threadMode = ThreadMode.ASYNC)
override fun onAction(action: Action<*>) {
val actionType = action.type as? WCOrderAction ?: return
when (actionType) {
// remote actions
WCOrderAction.FETCH_ORDERS -> fetchOrders(action.payload as FetchOrdersPayload)
WCOrderAction.FETCH_ORDER_LIST -> fetchOrderList(action.payload as FetchOrderListPayload)
WCOrderAction.FETCH_ORDERS_BY_IDS -> fetchOrdersByIds(action.payload as FetchOrdersByIdsPayload)
WCOrderAction.FETCH_ORDERS_COUNT -> fetchOrdersCount(action.payload as FetchOrdersCountPayload)
WCOrderAction.UPDATE_ORDER_STATUS ->
throw IllegalStateException("Invalid action. Use suspendable updateOrderStatus(..) directly")
WCOrderAction.SEARCH_ORDERS -> searchOrders(action.payload as SearchOrdersPayload)
WCOrderAction.FETCH_ORDER_STATUS_OPTIONS ->
fetchOrderStatusOptions(action.payload as FetchOrderStatusOptionsPayload)
// remote responses
WCOrderAction.FETCHED_ORDERS -> handleFetchOrdersCompleted(action.payload as FetchOrdersResponsePayload)
WCOrderAction.FETCHED_ORDER_LIST ->
handleFetchOrderListCompleted(action.payload as FetchOrderListResponsePayload)
WCOrderAction.FETCHED_ORDERS_BY_IDS ->
handleFetchOrderByIdsCompleted(action.payload as FetchOrdersByIdsResponsePayload)
WCOrderAction.FETCHED_ORDERS_COUNT ->
handleFetchOrdersCountCompleted(action.payload as FetchOrdersCountResponsePayload)
WCOrderAction.SEARCHED_ORDERS -> handleSearchOrdersCompleted(action.payload as SearchOrdersResponsePayload)
WCOrderAction.FETCHED_ORDER_STATUS_OPTIONS ->
handleFetchOrderStatusOptionsCompleted(action.payload as FetchOrderStatusOptionsResponsePayload)
}
}
private fun fetchOrders(payload: FetchOrdersPayload) {
val offset = if (payload.loadMore) {
ordersDao.getOrderCountForSite(payload.site.localId())
} else {
0
}
wcOrderRestClient.fetchOrders(payload.site, offset, payload.statusFilter)
}
private fun fetchOrderList(payload: FetchOrderListPayload) {
wcOrderRestClient.fetchOrderListSummaries(
listDescriptor = payload.listDescriptor,
offset = payload.offset,
requestStartTime = payload.requestStartTime
)
}
private fun fetchOrdersByIds(payload: FetchOrdersByIdsPayload) {
payload.orderIds.chunked(NUM_ORDERS_PER_FETCH).forEach { idsToFetch ->
wcOrderRestClient.fetchOrdersByIds(payload.site, idsToFetch)
}
}
private fun searchOrders(payload: SearchOrdersPayload) {
wcOrderRestClient.searchOrders(payload.site, payload.searchQuery, payload.offset)
}
private fun fetchOrdersCount(payload: FetchOrdersCountPayload) {
with(payload) { wcOrderRestClient.fetchOrderCount(site, statusFilter) }
}
suspend fun fetchHasOrders(site: SiteModel, status: String?): HasOrdersResult {
return coroutineEngine.withDefaultContext(T.API, this, "fetchHasOrders") {
val result = wcOrderRestClient.fetchHasOrders(site, status)
return@withDefaultContext if (result.isError) {
HasOrdersResult.Failure(result.error)
} else {
HasOrdersResult.Success(result.hasOrders)
}
}
}
suspend fun fetchSingleOrder(site: SiteModel, remoteOrderId: Long): OnOrderChanged {
return coroutineEngine.withDefaultContext(T.API, this, "fetchSingleOrder") {
val result = wcOrderRestClient.fetchSingleOrder(site, remoteOrderId)
return@withDefaultContext if (result.isError) {
OnOrderChanged(orderError = result.error)
} else {
insertOrder(result.orderWithMeta)
OnOrderChanged()
}
}
}
suspend fun updateOrderStatus(
orderId: Long,
site: SiteModel,
newStatus: WCOrderStatusModel
): Flow<UpdateOrderResult> {
return coroutineEngine.flowWithDefaultContext(T.API, this, "updateOrderStatus") {
val orderModel = ordersDao.getOrder(orderId, site.localId())
if (orderModel != null) {
updateOrderStatusLocally(orderId, site.localId(), newStatus.statusKey)
val optimisticUpdateResult = OnOrderChanged(
causeOfChange = WCOrderAction.UPDATE_ORDER_STATUS
)
emit(OptimisticUpdateResult(optimisticUpdateResult))
val remotePayload = wcOrderRestClient.updateOrderStatus(orderModel, site, newStatus.statusKey)
val remoteUpdateResult: OnOrderChanged = if (remotePayload.isError) {
revertOrderStatus(remotePayload)
} else {
ordersDao.insertOrUpdateOrder(remotePayload.order)
OnOrderChanged()
}.copy(causeOfChange = WCOrderAction.UPDATE_ORDER_STATUS)
emit(RemoteUpdateResult(remoteUpdateResult))
// Needs to remain here until all event bus observables are removed from the client code
emitChange(remoteUpdateResult)
} else {
emit(
OptimisticUpdateResult(
OnOrderChanged(
orderError = OrderError(
message = "Order with id $orderId not found"
)
)
)
)
}
}
}
private suspend fun updateOrderStatusLocally(orderId: Long, localSiteId: LocalId, newStatus: String) {
val updatedOrder = ordersDao.getOrder(orderId, localSiteId)!!
.copy(status = newStatus)
ordersDao.insertOrUpdateOrder(updatedOrder)
}
@Suppress("SpreadOperator")
suspend fun fetchOrderNotes(
site: SiteModel,
orderId: Long
): WooResult<List<OrderNoteEntity>> {
return coroutineEngine.withDefaultContext(T.API, this, "fetchOrderNotes") {
val result = wcOrderRestClient.fetchOrderNotes(orderId, site)
return@withDefaultContext result.let {
if (!it.isError) {
orderNotesDao.insertNotes(*it.result!!.toTypedArray())
}
result.asWooResult()
}
}
}
suspend fun postOrderNote(
site: SiteModel,
orderId: Long,
note: String,
isCustomerNote: Boolean
): WooResult<OrderNoteEntity> {
return coroutineEngine.withDefaultContext(T.API, this, "postOrderNote") {
val result = wcOrderRestClient.postOrderNote(orderId, site, note, isCustomerNote)
return@withDefaultContext if (result.isError) {
result.asWooResult()
} else {
orderNotesDao.insertNotes(result.result!!)
result.asWooResult()
}
}
}
private fun fetchOrderStatusOptions(payload: FetchOrderStatusOptionsPayload) {
wcOrderRestClient.fetchOrderStatusOptions(payload.site)
}
suspend fun fetchOrderShipmentTrackings(orderId: Long, site: SiteModel): OnOrderChanged {
return coroutineEngine.withDefaultContext(T.API, this, "fetchOrderShipmentTrackings") {
val result = wcOrderRestClient.fetchOrderShipmentTrackings(site, orderId)
return@withDefaultContext if (result.isError) {
OnOrderChanged(orderError = result.error)
} else {
// Calculate which existing records should be deleted because they no longer exist in the payload
val existingTrackings = OrderSqlUtils.getShipmentTrackingsForOrder(
result.site,
result.orderId
)
val deleteTrackings = mutableListOf<WCOrderShipmentTrackingModel>()
existingTrackings.iterator().forEach { existing ->
var exists = false
result.trackings.iterator().forEach nti@{ newTracking ->
if (newTracking.remoteTrackingId == existing.remoteTrackingId) {
exists = true
return@nti
}
}
if (!exists) deleteTrackings.add(existing)
}
var rowsAffected = deleteTrackings.sumBy { OrderSqlUtils.deleteOrderShipmentTrackingById(it) }
// Save new shipment trackings to the database
rowsAffected += result.trackings.sumBy { OrderSqlUtils.insertOrIgnoreOrderShipmentTracking(it) }
OnOrderChanged()
}
}
}
suspend fun addOrderShipmentTracking(payload: AddOrderShipmentTrackingPayload): OnOrderChanged {
return coroutineEngine.withDefaultContext(T.API, this, "addOrderShipmentTracking") {
val result = with(payload) {
wcOrderRestClient.addOrderShipmentTrackingForOrder(
site, orderId, tracking, isCustomProvider
)
}
return@withDefaultContext if (result.isError) {
OnOrderChanged(orderError = result.error)
} else {
result.tracking?.let { OrderSqlUtils.insertOrIgnoreOrderShipmentTracking(it) }
OnOrderChanged()
}
}
}
suspend fun deleteOrderShipmentTracking(payload: DeleteOrderShipmentTrackingPayload): OnOrderChanged {
return coroutineEngine.withDefaultContext(T.API, this, "deleteOrderShipmentTracking") {
val result = with(payload) {
wcOrderRestClient.deleteShipmentTrackingForOrder(site, orderId, tracking)
}
return@withDefaultContext if (result.isError) {
OnOrderChanged(orderError = result.error)
} else {
// Remove the record from the database and send response
result.tracking?.let { OrderSqlUtils.deleteOrderShipmentTrackingById(it) }
OnOrderChanged()
}
}
}
suspend fun fetchOrderShipmentProviders(
payload: FetchOrderShipmentProvidersPayload
): OnOrderShipmentProvidersChanged {
return coroutineEngine.withDefaultContext(T.API, this, "fetchOrderShipmentProviders") {
val result = with(payload) {
wcOrderRestClient.fetchOrderShipmentProviders(site, order)
}
return@withDefaultContext if (result.isError) {
OnOrderShipmentProvidersChanged(0).also { it.error = result.error }
} else {
// Delete all providers from the db
OrderSqlUtils.deleteOrderShipmentProvidersForSite(payload.site)
// Add new list to the database
val rowsAffected = result.providers.sumBy { OrderSqlUtils.insertOrIgnoreOrderShipmentProvider(it) }
OnOrderShipmentProvidersChanged(rowsAffected)
}
}
}
@Suppress("SpreadOperator")
private fun handleFetchOrdersCompleted(payload: FetchOrdersResponsePayload) {
coroutineEngine.launch(API, this, "handleFetchOrdersCompleted") {
val onOrderChanged: OnOrderChanged = if (payload.isError) {
OnOrderChanged(orderError = payload.error)
} else {
// Clear existing uploading orders if this is a fresh fetch (loadMore = false in the original request)
// This is the simplest way of keeping our local orders in sync with remote orders
// (in case of deletions, or if the user manual changed some order IDs).
if (!payload.loadedMore) {
ordersDao.deleteOrdersForSite(payload.site.localId())
orderNotesDao.deleteOrderNotesForSite(payload.site.remoteId())
OrderSqlUtils.deleteOrderShipmentTrackingsForSite(payload.site)
}
insertOrder(*payload.ordersWithMeta.toTypedArray())
OnOrderChanged(payload.statusFilter, canLoadMore = payload.canLoadMore)
}.copy(causeOfChange = FETCH_ORDERS)
emitChange(onOrderChanged)
}
}
@Suppress("ForbiddenComment")
private fun handleFetchOrderListCompleted(payload: FetchOrderListResponsePayload) {
// TODO: Ideally we would have a separate process that prunes the following
// tables of defunct records:
// - WCOrderModel
// - WCOrderNoteModel
// - WCOrderShipmentTrackingModel
if (!payload.isError) {
// Save order summaries to the db
OrderSqlUtils.insertOrUpdateOrderSummaries(payload.orderSummaries)
// Fetch outdated or missing orders
fetchOutdatedOrMissingOrders(payload.listDescriptor.site, payload.orderSummaries)
}
val duration = Calendar.getInstance().timeInMillis - payload.requestStartTime.timeInMillis
emitChange(OnOrderSummariesFetched(listDescriptor = payload.listDescriptor, duration = duration))
mDispatcher.dispatch(ListActionBuilder.newFetchedListItemsAction(FetchedListItemsPayload(
listDescriptor = payload.listDescriptor,
remoteItemIds = payload.orderSummaries.map { it.orderId },
loadedMore = payload.loadedMore,
canLoadMore = payload.canLoadMore,
error = payload.error?.let { fetchError ->
// TODO: Use the actual error type
ListError(type = ListErrorType.GENERIC_ERROR, message = fetchError.message)
}
)))
}
private fun fetchOutdatedOrMissingOrders(site: SiteModel, fetchedSummaries: List<WCOrderSummaryModel>) {
val fetchedSummariesIds = fetchedSummaries.map { it.orderId }
val localOrdersForFetchedSummaries = ordersDao.getOrdersForSiteByRemoteIds(site.localId(), fetchedSummariesIds)
val idsToFetch = outdatedOrdersIds(fetchedSummaries, localOrdersForFetchedSummaries)
.plus(missingOrdersIds(fetchedSummariesIds, localOrdersForFetchedSummaries))
wcOrderFetcher.fetchOrders(site = site, orderIds = idsToFetch)
}
private fun outdatedOrdersIds(
fetchedSummaries: List<WCOrderSummaryModel>,
localOrdersForSiteByRemoteIds: List<OrderEntity>
): List<Long> {
val summaryModifiedDates = fetchedSummaries.associate { it.orderId to it.dateModified }
return localOrdersForSiteByRemoteIds.filter { order ->
order.dateModified != summaryModifiedDates[order.orderId]
}.map(OrderEntity::orderId)
}
private fun missingOrdersIds(
fetchedSummariesIds: List<Long>,
localOrdersForSiteByRemoteIds: List<OrderEntity>
): List<Long> {
return fetchedSummariesIds.minus(
localOrdersForSiteByRemoteIds.map(OrderEntity::orderId)
)
}
@Suppress("SpreadOperator")
private fun handleFetchOrderByIdsCompleted(payload: FetchOrdersByIdsResponsePayload) {
coroutineEngine.launch(API, this, "handleFetchOrderByIdsCompleted") {
val onOrdersFetchedByIds = if (payload.isError) {
OnOrdersFetchedByIds(payload.site, payload.orderIds).apply { error = payload.error }
} else {
OnOrdersFetchedByIds(
payload.site,
payload.fetchedOrders.map { it.first }.map { it.orderId })
}
if (!payload.isError) {
// Save the list of orders to the database
insertOrder(*payload.fetchedOrders.toTypedArray())
// Notify listeners that the list of orders has changed (only call this if there is no error)
val listTypeIdentifier = WCOrderListDescriptor.calculateTypeIdentifier(localSiteId = payload.site.id)
mDispatcher.dispatch(
ListActionBuilder.newListDataInvalidatedAction(
listTypeIdentifier
)
)
}
emitChange(onOrdersFetchedByIds)
}
}
private fun handleSearchOrdersCompleted(payload: SearchOrdersResponsePayload) {
val onOrdersSearched = if (payload.isError) {
OnOrdersSearched(payload.searchQuery)
} else {
OnOrdersSearched(payload.searchQuery, payload.canLoadMore, payload.offset, payload.orders)
}
emitChange(onOrdersSearched)
}
/**
* This is a response to a request to retrieve only the count of orders matching a filter. These
* results are not stored in the database.
*/
private fun handleFetchOrdersCountCompleted(payload: FetchOrdersCountResponsePayload) {
val onOrderChanged = if (payload.isError) {
OnOrderChanged(orderError = payload.error)
} else {
with(payload) {
OnOrderChanged(statusFilter = statusFilter)
}
}.copy(causeOfChange = WCOrderAction.FETCH_ORDERS_COUNT)
emitChange(onOrderChanged)
}
private suspend fun revertOrderStatus(payload: RemoteOrderPayload.Updating): OnOrderChanged {
updateOrderStatusLocally(
payload.order.orderId,
payload.order.localSiteId,
payload.order.status
)
return OnOrderChanged(orderError = payload.error)
}
private fun handleFetchOrderStatusOptionsCompleted(payload: FetchOrderStatusOptionsResponsePayload) {
val onOrderStatusLabelsChanged: OnOrderStatusOptionsChanged
if (payload.isError) {
onOrderStatusLabelsChanged = OnOrderStatusOptionsChanged(0).also { it.error = payload.error }
} else {
onOrderStatusLabelsChanged = onOrderStatusOptionsChanged(payload)
}
emitChange(onOrderStatusLabelsChanged)
}
private fun onOrderStatusOptionsChanged(
payload: FetchOrderStatusOptionsResponsePayload
): OnOrderStatusOptionsChanged {
val existingOptions = OrderSqlUtils.getOrderStatusOptionsForSite(payload.site)
var rowsAffected = addOrUpdateOptions(payload, existingOptions).sumBy {
OrderSqlUtils.insertOrUpdateOrderStatusOption(it)
}
rowsAffected += deleteOptions(payload, existingOptions).sumBy {
OrderSqlUtils.deleteOrderStatusOption(it)
}
return OnOrderStatusOptionsChanged(rowsAffected)
}
@Suppress("NestedBlockDepth")
private fun addOrUpdateOptions(
payload: FetchOrderStatusOptionsResponsePayload,
existingOptions: List<WCOrderStatusModel>
): List<WCOrderStatusModel> {
val addOrUpdateOptions = mutableListOf<WCOrderStatusModel>()
payload.labels.iterator().forEach { newOption ->
var exists = false
existingOptions.iterator().forEach eoi@{ existingOption ->
if (newOption.statusKey == existingOption.statusKey) {
exists = true
if (newOption.label != existingOption.label ||
newOption.statusCount != existingOption.statusCount) {
addOrUpdateOptions.add(newOption)
}
return@eoi
}
}
if (!exists) addOrUpdateOptions.add(newOption)
}
return addOrUpdateOptions
}
private fun deleteOptions(
payload: FetchOrderStatusOptionsResponsePayload,
existingOptions: List<WCOrderStatusModel>
): List<WCOrderStatusModel> {
val deleteOptions = mutableListOf<WCOrderStatusModel>()
existingOptions.iterator().forEach { existingOption ->
var exists = false
payload.labels.iterator().forEach noi@{ newOption ->
if (newOption.statusKey == existingOption.statusKey) {
exists = true
return@noi
}
}
if (!exists) deleteOptions.add(existingOption)
}
return deleteOptions
}
}
| gpl-2.0 | 4f939113ce81acbe4f7c52ed622ffe9c | 38.767167 | 119 | 0.654939 | 5.465713 | false | false | false | false |
OpenWeen/OpenWeen.Droid | app/src/main/java/moe/tlaster/openween/core/model/LimitStatusModel.kt | 1 | 834 | package moe.tlaster.openween.core.model
import com.fasterxml.jackson.annotation.JsonProperty
/**
* Created by Tlaster on 2016/8/26.
*/
class LimitStatusModel {
@field:JsonProperty("ip_limit")
var ipLimit: Long = 0
@field:JsonProperty("limit_time_unit")
var limitTimeUnit: String? = null
@field:JsonProperty("remaining_ip_hits")
var remainingIpHits: Long = 0
@field:JsonProperty("remaining_user_hits")
var remainingUserHits: Int = 0
@field:JsonProperty("reset_time")
var resetTimeValue: String? = null
@field:JsonProperty("reset_time_in_seconds")
var resetTimeInSeconds: Long = 0
@field:JsonProperty("user_limit")
var userLimit: Int = 0
@field:JsonProperty("error")
var error: String? = null
@field:JsonProperty("error_code")
var errorCode: String? = null
}
| mit | c11112b3f33d49f31160516db08259c1 | 28.785714 | 52 | 0.694245 | 3.73991 | false | false | false | false |
andersonlucasg3/SpriteKit-Android | SpriteKitLib/src/main/java/br/com/insanitech/spritekit/SKScene.kt | 1 | 1687 | package br.com.insanitech.spritekit
import br.com.insanitech.spritekit.graphics.SKColor
import br.com.insanitech.spritekit.graphics.SKPoint
import br.com.insanitech.spritekit.graphics.SKSize
open class SKScene : SKEffectNode {
var anchorPoint: SKPoint = SKPoint()
set(value) { field.point.assignByValue(value.point) }
var size: SKSize = SKSize()
set(value) {
val oldSize = SKSize(field)
field.size.assignByValue(value.size)
this.didChangeSize(oldSize)
}
var scaleMode: SKSceneScaleMode = SKSceneScaleMode.AspectFill
var backgroundColor: SKColor = SKColor(0.15f, 0.15f, 0.15f, 1.0f)
set(value) { field.color.assignByValue(value.color) }
var view: SKView? = null
internal set
init {
this.isUserInteractionEnabled = true
}
constructor(size: SKSize) {
this.size = size
this.sceneDidLoad()
}
open fun didChangeSize(oldSize: SKSize) {
}
open fun sceneDidLoad() {
}
open fun willMove(fromView: SKView) {
}
open fun didMove(toView: SKView) {
}
open fun update(currentTime: Long) {
}
open fun didEvaluateActions() {
}
open fun didFinishUpdate() {
}
override fun addChild(node: SKNode) {
super.addChild(node, false)
this.movedToScene(this)
}
override fun insertChild(node: SKNode, index: Int) {
super.insertChild(node, index, false)
this.movedToScene(this)
}
override fun convertPointForCandidateParentIfNeeded(p: SKPoint, parent: SKNode): SKPoint {
return if (parent == this) p else parent.convertFrom(p, this)
}
}
| bsd-3-clause | bd566dbaee5ac9d72b9295412966e152 | 21.197368 | 94 | 0.642561 | 3.860412 | false | false | false | false |
MatthijsKok/TI2806-Contextproject | BankChain/app/src/main/java/nl/tudelft/ewi/ds/bankchain/bank/bunq/BunqAccount.kt | 1 | 888 | package nl.tudelft.ewi.ds.bankchain.bank.bunq
import nl.tudelft.ewi.ds.bankchain.bank.Account
import nl.tudelft.ewi.ds.bankchain.bank.Party
import java8.util.stream.StreamSupport.*
import nl.tudelft.ewi.ds.bankchain.bank.bunq.api.AccountService.*
/**
* Bunq implementation of account
*/
class BunqAccount : Account {
override val party: Party
override val iban: String
override val id: Int
constructor(account: ListResponse.BunqBankAccount, party: Party) {
//retreive IBAN from list of aliases
val ac = stream<ListResponse.Alias>(account.aliases)
.filter { c -> c.type == "IBAN" }
.findFirst()
id = account.id
this.party = party
iban = ac.get().value
}
constructor(iban: String, id: Int, party: Party) {
this.iban = iban
this.party = party
this.id = id
}
}
| lgpl-3.0 | 8a362396a71d190fe2838f6498cf1680 | 26.75 | 70 | 0.644144 | 3.669421 | false | false | false | false |
minjaesong/terran-basic-java-vm | src/net/torvald/terrarum/virtualcomputer/terranvmadapter/Memvwr.kt | 1 | 3406 | package net.torvald.terrarum.virtualcomputer.terranvmadapter
import net.torvald.terranvm.runtime.TerranVM
import net.torvald.terranvm.runtime.to8HexString
import net.torvald.terranvm.runtime.toHexString
import net.torvald.terranvm.runtime.toUint
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.Font
import javax.swing.JFrame
import javax.swing.JTextArea
import javax.swing.WindowConstants
/**
* Created by minjaesong on 2017-11-21.
*/
class Memvwr(val vm: TerranVM) : JFrame("TerranVM Memory Viewer - Core Memory") {
val memArea = JTextArea()
var columns = 16
fun composeMemText() {
val sb = StringBuilder()
/*
stack: 60h..1FFh
r1: 00000000h; 0; 0.0f
cp: -1
000000 : 00 00 00 00 00 00 00 48 00 00 00 50 00 00 00 58 | .......H...P...X
*/
if (vm.stackSize != null) {
sb.append("stack: ${vm.ivtSize.toHexString()}..${(vm.ivtSize + vm.stackSize!! - 1).toHexString()} (size: ${vm.stackSize} bytes)\n")
}
else {
sb.append("stack: not defined\n")
}
// registers
for (r in 1..8) {
val rI = vm.readregInt(r)
val rF = vm.readregFloat(r)
sb.append("r$r: " +
"${rI.to8HexString()}; " +
"$rI; ${rF}f\n"
)
}
sb.append("cp: " +
"${vm.cp.to8HexString()}; " +
"${vm.cp}\n"
)
sb.append("uptime: ${vm.uptime} ms\n")
sb.append("ips: ${vm.instPerSec}\n")
sb.append("ADRESS : 0 1 2 3| 4 5 6 7| 8 9 A B| C D E F\n")
// coremem
for (i in 0..vm.memory.lastIndex) {
if (i % columns == 0) {
sb.append(i.toString(16).toUpperCase().padStart(6, '0')) // mem addr
sb.append(" : ") // separator
}
sb.append(vm.memory[i].toUint().toString(16).toUpperCase().padStart(2, '0'))
if (i % 16 in intArrayOf(3, 7, 11)) {
sb.append('|') // mem value
}
else {
sb.append(' ') // mem value
}
// ASCII viewer
if (i % columns == 15) {
sb.append("| ")
for (x in -15..0) {
val mem = vm.memory[i + x].toUint()
if (mem < 32) {
sb.append('.')
}
else {
sb.append(mem.toChar())
}
if (x + 15 in intArrayOf(3, 7, 11))
sb.append('|')
}
sb.append('\n')
}
}
// peripherals
sb.append("peripherals:\n")
for (i in 0 until vm.peripherals.size) {
sb.append("peri[$i]: ${vm.peripherals[i]?.javaClass?.simpleName ?: "null"}\n")
}
memArea.text = sb.toString()
}
fun update() {
composeMemText()
}
init {
memArea.font = Font("Monospaced", Font.PLAIN, 12)
memArea.highlighter = null
this.layout = BorderLayout()
this.isVisible = true
this.add(javax.swing.JScrollPane(memArea), BorderLayout.CENTER)
this.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
this.size = Dimension(600, 960)
}
} | mit | 1a8f67baf4fbc26e2edff9a14d033a61 | 24.425373 | 143 | 0.483558 | 3.788654 | false | false | false | false |
if710/if710.github.io | 2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/phonesms/PhoneManagerActivity.kt | 1 | 2599 | package br.ufpe.cin.android.systemservices.phonesms
import android.Manifest
import android.app.ListActivity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.telephony.TelephonyManager
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.core.content.ContextCompat
import java.util.ArrayList
class PhoneManagerActivity : ListActivity() {
internal var data = ArrayList<String>()
internal var adapter: ArrayAdapter<String>? = null
internal var telephonyManager: TelephonyManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, data)
listAdapter = adapter
}
override fun onStart() {
super.onStart()
val readPhoneState = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
val accessCoarseLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
if (readPhoneState && accessCoarseLocation) {
adapter?.add("Device ID: " + telephonyManager?.deviceId)
adapter?.add("Call State: " + telephonyManager?.callState)
adapter?.add("Device SW Version: " + telephonyManager?.deviceSoftwareVersion)
adapter?.add("Network Operator: " + telephonyManager?.networkOperator)
adapter?.add("Network Operator Name: " + telephonyManager?.networkOperatorName)
adapter?.add("Network Country ISO: " + telephonyManager?.networkCountryIso)
adapter?.add("Network Type: " + telephonyManager?.networkType)
adapter?.add("Cell Location: " + telephonyManager?.cellLocation)
adapter?.add("SIM Operator: " + telephonyManager?.simOperator)
adapter?.add("SIM Serial Number: " + telephonyManager?.simSerialNumber)
adapter?.add("SIM State: " + telephonyManager?.simState)
adapter?.add("Voice Mail Number: " + telephonyManager?.voiceMailNumber)
adapter?.add("Phone Type: " + telephonyManager?.phoneType)
//adapter.add...
} else {
Toast.makeText(this, "Conceda permissões em settings", Toast.LENGTH_SHORT).show()
finish()
}
}
override fun onStop() {
super.onStop()
adapter?.clear()
}
} | mit | 16cbb111ee0b2b59f887e63e36953904 | 41.606557 | 155 | 0.697844 | 4.977011 | false | false | false | false |
ahmedeltaher/MVP-Sample | app/src/main/java/com/task/ui/base/BaseActivity.kt | 1 | 3055 | package com.task.ui.base
import android.os.Bundle
import android.view.MenuItem
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.Unbinder
import com.task.R
import com.task.ui.base.listeners.ActionBarView
import com.task.ui.base.listeners.BaseView
/**
* Created by AhmedEltaher on 5/12/2016
*/
abstract class BaseActivity : AppCompatActivity(), BaseView, ActionBarView {
protected lateinit var presenter: Presenter<*>
@JvmField
@BindView(R.id.toolbar)
internal var toolbar: Toolbar? = null
@JvmField
@BindView(R.id.ic_toolbar_setting)
internal var icSettings: ImageView? = null
@JvmField
@BindView(R.id.ic_toolbar_refresh)
var icHome: ImageView? = null
private var unbinder: Unbinder? = null
abstract val layoutId: Int
protected abstract fun initializeDagger()
protected abstract fun initializePresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layoutId)
unbinder = ButterKnife.bind(this)
initializeDagger()
initializePresenter()
initializeToolbar()
presenter.initialize(intent.extras)
}
override fun onStart() {
super.onStart()
presenter.start()
}
override fun onStop() {
super.onStop()
presenter.finalizeView()
}
private fun initializeToolbar() {
if (toolbar != null) {
setSupportActionBar(toolbar)
supportActionBar?.title = ""
}
}
override fun setUpIconVisibility(visible: Boolean) {
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(visible)
}
override fun setTitle(titleKey: String) {
val actionBar = supportActionBar
if (actionBar != null) {
val title = findViewById<TextView>(R.id.txt_toolbar_title)
title?.text = titleKey
}
}
override fun setSettingsIconVisibility(visibility: Boolean) {
val actionBar = supportActionBar
if (actionBar != null) {
val icon = findViewById<ImageView>(R.id.ic_toolbar_setting)
icon?.visibility = if (visibility) VISIBLE else GONE
}
}
override fun setRefreshVisibility(visibility: Boolean) {
val actionBar = supportActionBar
if (actionBar != null) {
val icon = findViewById<ImageView>(R.id.ic_toolbar_refresh)
icon?.visibility = if (visibility) VISIBLE else GONE
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> finish()
}
return super.onOptionsItemSelected(item)
}
override fun onDestroy() {
super.onDestroy()
unbinder?.unbind()
}
}
| apache-2.0 | 64a9a135d4182a7440559907f9ac8355 | 25.798246 | 76 | 0.664812 | 4.7 | false | false | false | false |
clangen/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/shared/extension/Compat.kt | 1 | 2074 | package io.casey.musikcube.remote.ui.shared.extension
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import java.io.Serializable
@Suppress("deprecation")
inline fun <reified T: Parcelable> Intent.getParcelableExtraCompat(name: String): T? =
if (Build.VERSION.SDK_INT >= 33) {
this.getParcelableExtra(name, T::class.java)
}
else {
this.getParcelableExtra(name)
}
@Suppress("deprecation")
inline fun <reified T: Parcelable> Bundle.getParcelableCompat(name: String): T? =
if (Build.VERSION.SDK_INT >= 33) {
this.getParcelable(name, T::class.java)
}
else {
this.getParcelable(name)
}
@Suppress("deprecation")
inline fun <reified T: Serializable> Bundle.getSerializableCompat(name: String): T? =
if (Build.VERSION.SDK_INT >= 33) {
this.getSerializable(name, T::class.java)
}
else {
this.getSerializable(name) as T?
}
@Suppress("deprecation")
fun PackageManager.getPackageInfoCompat(name: String): PackageInfo =
if (Build.VERSION.SDK_INT >= 33) {
this.getPackageInfo(name, PackageManager.PackageInfoFlags.of(0))
}
else {
this.getPackageInfo(name, 0)
}
fun ComponentActivity.launcher(callback: ActivityResultCallback<ActivityResult>): ActivityResultLauncher<Intent> =
this.registerForActivityResult(ActivityResultContracts.StartActivityForResult(), callback)
fun Fragment.launcher(callback: ActivityResultCallback<ActivityResult>): ActivityResultLauncher<Intent> =
this.registerForActivityResult(ActivityResultContracts.StartActivityForResult(), callback)
| bsd-3-clause | d99ed00f8047843dfb9312dfefe9e29d | 34.758621 | 114 | 0.762295 | 4.460215 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/find/qidiantu/list/QidiantuListActivity.kt | 1 | 7206 | package cc.aoeiuv020.panovel.find.qidiantu.list
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import cc.aoeiuv020.panovel.IView
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.data.entity.Novel
import cc.aoeiuv020.panovel.detail.NovelDetailActivity
import cc.aoeiuv020.panovel.find.qidiantu.QidiantuActivity
import cc.aoeiuv020.panovel.settings.OtherSettings
import cc.aoeiuv020.panovel.util.safelyShow
import cc.aoeiuv020.regex.pick
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_qidiantu_list.*
import kotlinx.android.synthetic.main.activity_single_search.srlRefresh
import org.jetbrains.anko.*
/**
* 起点图首订统计小说列表页,
*/
class QidiantuListActivity : AppCompatActivity(), IView, AnkoLogger {
companion object {
fun start(ctx: Context) {
ctx.startActivity<QidiantuListActivity>()
}
fun start(ctx: Context, postUrl: String) {
ctx.startActivity<QidiantuListActivity>(
"postUrl" to postUrl
)
}
}
private lateinit var presenter: QidiantuListPresenter
private lateinit var adapter: QidiantuListAdapter
private lateinit var headAdapter: QidiantuPostAdapter
private lateinit var postUrl: String
private var itemJumpQidian: MenuItem? = null
private val snack: Snackbar by lazy {
Snackbar.make(rvContent, "", Snackbar.LENGTH_SHORT)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_qidiantu_list)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
setTitle(R.string.qidiantu)
postUrl = intent.getStringExtra("postUrl") ?: "https://www.qidiantu.com/shouding/"
srlRefresh.isRefreshing = true
srlRefresh.setOnRefreshListener {
presenter.refresh()
}
initRecycler()
presenter = QidiantuListPresenter()
presenter.attach(this)
presenter.start(this, postUrl)
}
override fun onDestroy() {
presenter.stop()
super.onDestroy()
}
private fun initRecycler() {
rvHead.adapter = QidiantuPostAdapter().also {
headAdapter = it
it.setOnItemClickListener(object : QidiantuPostAdapter.OnItemClickListener {
override fun onItemClick(item: Post) {
start(ctx, item.url)
finish()
}
})
}
rvContent.adapter = QidiantuListAdapter().also {
adapter = it
it.setOnItemClickListener(object : QidiantuListAdapter.OnItemClickListener {
override fun onItemClick(item: Item) {
try {
openBook(item)
} catch (ignore: Exception) {
innerBrowse(item.url)
}
}
})
}
}
fun innerBrowse(url: String) {
QidiantuActivity.start(this, url)
}
private fun openBook(item: Item) {
// http://www.qidiantu.com/info/1030268248.html
val bookId = item.url.pick("http.*/info/(\\d*)").first()
// https://book.qidian.com/info/1027440366
// https://m.qidian.com/info/1027440366
if (OtherSettings.jumpQidian) {
try {
// I/ActivityTaskManager: START u0 {act=android.intent.action.VIEW cat=[android.intent.category.BROWSABLE] dat=QDReader://app/showBook?query={"bookId":1027440366} flg=0x14400000 cmp=com.qidian.QDReader/.ui.activity.MainGroupActivity (has extras)} from uid 10241
// intent://app/showBook?query=%7B%22bookId%22%3A1027440366%7D#Intent;scheme=QDReader;S.browser_fallback_url=http%3A%2F%2Fdownload.qidian.com%2Fapknew%2Fsource%2FQDReaderAndroid.apk;end
val intent = Intent.parseUri(
"intent://app/showBook?query=%7B%22bookId%22%3A$bookId%7D#Intent;scheme=QDReader;S.browser_fallback_url=http%3A%2F%2Fdownload.qidian.com%2Fapknew%2Fsource%2FQDReaderAndroid.apk;end",
Intent.URI_INTENT_SCHEME
)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
return
} catch (e: ActivityNotFoundException) {
toast(R.string.qidian_not_found)
OtherSettings.jumpQidian = false
updateItem()
}
}
presenter.open(item, bookId)
}
fun openNovelDetail(novel: Novel) {
NovelDetailActivity.start(ctx, novel)
}
fun showResult(data: List<Item>, head: List<Post>, title: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed) {
return
}
srlRefresh.isRefreshing = false
adapter.setData(data)
headAdapter.setData(head)
if (title.isNotBlank()) {
setTitle(title)
}
if (data.isEmpty()) {
snack.setText(R.string.qidiantu_empty_new)
snack.show()
} else {
snack.dismiss()
}
}
fun showProgress(retry: Int, maxRetry: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed) {
return
}
srlRefresh.isRefreshing = false
snack.setText(getString(R.string.qidianshuju_post_progress_place_holder, retry, maxRetry))
snack.show()
}
fun showError(message: String, e: Throwable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed) {
return
}
srlRefresh.isRefreshing = false
snack.dismiss()
alert(
title = ctx.getString(R.string.error),
message = message + e.message
) {
okButton { }
}.safelyShow()
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_qidianshuju_list, menu)
itemJumpQidian = menu.findItem(R.id.qidian)
updateItem()
return true
}
override fun onRestart() {
super.onRestart()
updateItem()
}
private fun updateItem() {
itemJumpQidian?.setIcon(
if (OtherSettings.jumpQidian) {
R.drawable.ic_jump_qidian
} else {
R.drawable.ic_jump_qidian_blocked
}
)
}
private fun toggleQidian() {
OtherSettings.jumpQidian = !OtherSettings.jumpQidian
updateItem()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.browse -> presenter.browse()
R.id.qidian -> toggleQidian()
else -> return super.onOptionsItemSelected(item)
}
return true
}
}
| gpl-3.0 | c9a3f639f633b4666459b0f88371933e | 32.395349 | 277 | 0.618663 | 4.396816 | false | false | false | false |
dumptruckman/PluginBase | pluginbase-core/messages/src/main/kotlin/pluginbase/messages/ChatColor.kt | 1 | 6484 | /* 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 pluginbase.messages
import java.util.HashMap
/**
* All supported color values for chat.
*/
enum class ChatColor constructor(
/**
* Gets the char value associated with this color.
*
* @return A char value of this color code.
*/
val char: Char,
private val intCode: Int,
/**
* Checks if this code is a format code as opposed to a color code.
*/
val isFormat: Boolean = false) {
/**
* Represents black.
*/
BLACK('0', 0x00),
/**
* Represents dark blue.
*/
DARK_BLUE('1', 0x1),
/**
* Represents dark green.
*/
DARK_GREEN('2', 0x2),
/**
* Represents dark blue (aqua).
*/
DARK_AQUA('3', 0x3),
/**
* Represents dark red.
*/
DARK_RED('4', 0x4),
/**
* Represents dark purple.
*/
DARK_PURPLE('5', 0x5),
/**
* Represents gold.
*/
GOLD('6', 0x6),
/**
* Represents gray.
*/
GRAY('7', 0x7),
/**
* Represents dark gray.
*/
DARK_GRAY('8', 0x8),
/**
* Represents blue.
*/
BLUE('9', 0x9),
/**
* Represents green.
*/
GREEN('a', 0xA),
/**
* Represents aqua.
*/
AQUA('b', 0xB),
/**
* Represents red.
*/
RED('c', 0xC),
/**
* Represents light purple.
*/
LIGHT_PURPLE('d', 0xD),
/**
* Represents yellow.
*/
YELLOW('e', 0xE),
/**
* Represents white.
*/
WHITE('f', 0xF),
/**
* Represents magical characters that change around randomly.
*/
MAGIC('k', 0x10, true),
/**
* Makes the text bold.
*/
BOLD('l', 0x11, true),
/**
* Makes a line appear through the text.
*/
STRIKETHROUGH('m', 0x12, true),
/**
* Makes the text appear underlined.
*/
UNDERLINE('n', 0x13, true),
/**
* Makes the text italic.
*/
ITALIC('o', 0x14, true),
/**
* Resets all previous chat colors or formats.
*/
RESET('r', 0x15);
private val stringForm by lazy { "$COLOR_CHAR$char" }
override fun toString(): String {
return stringForm
}
/**
* Checks if this code is a color code as opposed to a format code.
*/
val isColor: Boolean
get() = !isFormat && this != RESET
companion object {
/**
* The special character which prefixes all chat colour codes.
*
* Use this if you need to dynamically convert colour codes from your custom format.
*/
const val COLOR_CHAR = '\u00A7'
private val STRIP_COLOR_PATTERN = "(?i)$COLOR_CHAR[0-9A-FK-OR]".toPattern()
private val BY_ID = HashMap<Int, ChatColor>()
private val BY_CHAR = HashMap<Char, ChatColor>()
/**
* Gets the color represented by the specified color code.
*
* @param code Code to check.
* @return Associated [ChatColor] with the given code, or null if it doesn't exist.
*/
@JvmStatic
fun getByChar(code: Char): ChatColor? {
return BY_CHAR[code]
}
/**
* Gets the color represented by the specified color code.
*
* @param code Code to check.
* @return Associated [ChatColor] with the given code, or null if it doesn't exist.
*/
@JvmStatic
fun getByChar(code: String): ChatColor? {
return BY_CHAR[code[0]]
}
/**
* Strips the given message of all color codes.
*
* @param input String to strip of color.
* @return A copy of the input string, without any coloring.
*/
@JvmStatic
fun stripColor(input: String?): String? {
if (input == null) {
return null
}
return STRIP_COLOR_PATTERN.matcher(input).replaceAll("")
}
/**
* Translates a string using an alternate color code character into a string that uses the internal
* ChatColor.COLOR_CODE color code character.
*
* The alternate color code character will only be replaced if it is immediately followed by 0-9, A-F, or a-f.
*
* @param altColorChar The alternate color code character to replace. Ex: &.
* @param textToTranslate Text containing the alternate color code character.
* @return Text containing the ChatColor.COLOR_CODE color code character.
*/
@JvmStatic
fun translateAlternateColorCodes(altColorChar: Char, textToTranslate: String): String {
val b = textToTranslate.toCharArray()
for (i in 0..(b.size - 2)) {
if (b[i] == altColorChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) {
b[i] = COLOR_CHAR
b[i + 1] = Character.toLowerCase(b[i + 1])
}
}
return String(b)
}
/**
* Gets the ChatColors used at the end of the given input string.
*
* @param input Input string to retrieve the colors from.
* @return Any remaining ChatColors to pass onto the next line.
*/
@JvmStatic
fun getLastColors(input: String): String {
var result = ""
val length = input.length
// Search backwards from the end as it is faster
for (index in length - 1 downTo 0) {
val section = input[index]
if (section == COLOR_CHAR && index < length - 1) {
val c = input[index + 1]
val color = getByChar(c)
if (color != null) {
result = color.toString() + result
// Once we find a color or reset we can stop searching
if (color.isColor || color == RESET) {
break
}
}
}
}
return result
}
init {
for (color in values()) {
BY_ID.put(color.intCode, color)
BY_CHAR.put(color.char, color)
}
}
}
}
| mpl-2.0 | bec32b3c8adb3b23338b6ecb2df7891d | 26.591489 | 118 | 0.51095 | 4.29404 | false | false | false | false |