repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pzhangleo/android-base | base/src/main/java/hope/base/ui/adpter/ListAdapter.kt | 1 | 1084 | package hope.base.ui.adpter
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
abstract class ListAdapter<ITEM, VH: AbstractViewHolder<ITEM>>
: RecyclerView.Adapter<VH>() {
private val data: MutableList<ITEM> = ArrayList()
var next = 0
fun noMore(): Boolean {
return next == 0
}
fun submitList(list: List<ITEM>) {
next = 0
this.data.clear()
this.data.addAll(list)
notifyDataSetChanged()
}
fun addList(list: List<ITEM>) {
val position = this.data.size
this.data.addAll(list)
notifyItemInserted(position)
}
abstract override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: VH, position: Int) {
holder.bindData(data[position], position)
}
}
abstract class AbstractViewHolder<ITEM>(v: View)
: RecyclerView.ViewHolder(v) {
abstract fun bindData(item: ITEM, position: Int)
} | lgpl-3.0 | fd66ad8ab5d0db972c865835651d37b2 | 21.604167 | 82 | 0.660517 | 4.217899 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/AnalyzePluginStartupPerformanceAction.kt | 1 | 4354 | // 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.diagnostic
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.table.TableView
import com.intellij.util.ui.ColumnInfo
import com.intellij.util.ui.ListTableModel
import java.awt.event.ActionEvent
import java.util.concurrent.TimeUnit
import javax.swing.AbstractAction
import javax.swing.Action
import javax.swing.JComponent
internal class AnalyzePluginStartupPerformanceAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
PluginStartupCostDialog(project).show()
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.project != null
}
}
data class PluginStartupCostEntry(
val pluginId: String,
val pluginName: String,
val cost: Long,
val costDetails: String
)
class PluginStartupCostDialog(private val project: Project) : DialogWrapper(project) {
val pluginsToDisable = mutableSetOf<String>()
lateinit var tableModel: ListTableModel<PluginStartupCostEntry>
lateinit var table: TableView<PluginStartupCostEntry>
init {
title = "Startup Time Cost per Plugin"
init()
}
override fun createCenterPanel(): JComponent {
val pluginCostMap = StartUpPerformanceService.getInstance().pluginCostMap
val tableData = pluginCostMap
.mapNotNull { (pluginId, costMap) ->
if (!ApplicationManager.getApplication().isInternal &&
(ApplicationInfoEx.getInstanceEx()).isEssentialPlugin(pluginId)) {
return@mapNotNull null
}
val name = PluginManagerCore.getPlugin(PluginId.getId(pluginId))?.name ?: return@mapNotNull null
var totalCost = 0L
costMap.forEachValue {
totalCost += it
true
}
val ids = costMap.keys()
ids.sort()
val costDetails = StringBuilder()
for (id in ids) {
costDetails.append(id).append(": ").append(TimeUnit.NANOSECONDS.toMillis(costMap[id as String]))
costDetails.append('\n')
}
PluginStartupCostEntry(pluginId, name, totalCost, costDetails.toString())
}
.sortedByDescending { it.cost }
val pluginColumn = object : ColumnInfo<PluginStartupCostEntry, String>("Plugin") {
override fun valueOf(item: PluginStartupCostEntry) =
item.pluginName + (if (item.pluginId in pluginsToDisable) " (will be disabled)" else "")
}
val costColumn = object : ColumnInfo<PluginStartupCostEntry, Int>("Startup Time (ms)") {
override fun valueOf(item: PluginStartupCostEntry) = TimeUnit.NANOSECONDS.toMillis(item.cost).toInt()
}
val costDetailsColumn = object : ColumnInfo<PluginStartupCostEntry, String>("Cost Details") {
override fun valueOf(item: PluginStartupCostEntry) = item.costDetails
}
val columns = if (ApplicationManager.getApplication().isInternal) {
arrayOf(pluginColumn, costColumn, costDetailsColumn)
}
else {
arrayOf(pluginColumn, costColumn)
}
tableModel = ListTableModel(columns, tableData)
table = TableView(tableModel).apply {
setShowColumns(true)
}
return JBScrollPane(table)
}
override fun createLeftSideActions(): Array<Action> {
val disableAction = object : AbstractAction("Disable Selected Plugins") {
override fun actionPerformed(e: ActionEvent?) {
for (costEntry in table.selectedObjects) {
pluginsToDisable.add(costEntry.pluginId)
}
tableModel.fireTableDataChanged()
}
}
return arrayOf(disableAction)
}
override fun doOKAction() {
super.doOKAction()
if (pluginsToDisable.isNotEmpty()) {
val plugins = pluginsToDisable.map { PluginManagerCore.getPlugin(PluginId.getId(it)) }.toSet()
IdeErrorsDialog.confirmDisablePlugins(project, plugins)
}
}
} | apache-2.0 | 8bcfd06d67ebb672a98b126557b05626 | 34.120968 | 140 | 0.724162 | 4.544885 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/classLiteral/bound/smartCast.kt | 2 | 339 | // IGNORE_BACKEND: NATIVE
// KT-16291 Smart cast doesn't work when getting class of instance
class Foo(val s: String) {
override fun equals(other: Any?): Boolean {
return other != null && other::class == this::class && s == (other as Foo).s
}
}
fun box(): String {
return if (Foo("a") == Foo("a")) "OK" else "Fail"
}
| apache-2.0 | c030cd51ea0d120f417cc5e0f4928f69 | 27.25 | 84 | 0.60472 | 3.39 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/ui/AccountViewModel.kt | 1 | 5358 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package ui
import androidx.lifecycle.*
import kotlinx.coroutines.launch
import model.*
import org.blokada.R
import service.*
import ui.utils.cause
import ui.utils.now
import utils.Logger
import java.util.*
class AccountViewModel: ViewModel() {
private val log = Logger("Account")
private val blocka = BlockaApiService
private val persistence = PersistenceService
private val alert = AlertDialogService
private val connectivity = ConnectivityService
private val _account = MutableLiveData<Account>()
val account: LiveData<Account> = _account
val accountExpiration: LiveData<ActiveUntil> = _account.map { it.active_until }.distinctUntilChanged()
// This var is thread safe because we work on Main.immediate dispatched coroutines
private var requestOngoing = false
private var lastAccountRefresh = 0L
init {
try {
updateLiveData(persistence.load(Account::class))
log.v("Loaded account from persistence")
} catch (ex: Exception) {}
}
fun restoreAccount(accountId: AccountId) {
viewModelScope.launch {
log.w("Restoring account")
try {
val accountId = accountId.toLowerCase(Locale.ENGLISH).trim()
val account = blocka.getAccount(accountId)
if (EnvironmentService.isPublicBuild() && !account.isActive()) throw BlokadaException("Account inactive after restore")
updateLiveData(account)
} catch (ex: BlokadaException) {
log.e("Failed restoring account".cause(ex))
updateLiveData(persistence.load(Account::class))
alert.showAlert(R.string.error_account_inactive_after_restore)
}
}
}
fun refreshAccount(accountExpiring: Boolean = false) {
viewModelScope.launch {
try {
log.v("Refreshing account")
requestOngoing = true
val accountId = _account.value?.id ?: persistence.load(Account::class).id
val account = blocka.getAccount(accountId)
updateLiveData(account)
log.v("Account refreshed, active: ${account.isActive()}, type: ${account.type}")
lastAccountRefresh = now()
requestOngoing = false
} catch (ex: NoPersistedAccount) {
log.w("No account to refresh yet, ignoring")
requestOngoing = false
} catch (ex: BlokadaException) {
requestOngoing = false
when {
accountExpiring -> {
log.w("Could not refresh expiring account, assuming expired".cause(ex))
account.value?.copy(
active_until = Date(0),
active = false,
type = null
)?.run {
updateLiveData(this)
}
}
connectivity.isDeviceInOfflineMode() ->
log.w("Could not refresh account but device is offline, ignoring")
else -> {
// TODO: better handling?
log.w("Could not refresh account, ignoring".cause(ex))
}
}
try {
log.v("Returning persisted copy")
updateLiveData(persistence.load(Account::class))
} catch (ex: Exception) {}
}
}
}
fun maybeRefreshAccount() {
viewModelScope.launch {
if (requestOngoing) {
log.v("maybeRefreshAccount: Account request already in progress, ignoring")
} else if (!hasAccount()) {
try {
log.w("Creating new account")
requestOngoing = true
val account = blocka.postNewAccount()
updateLiveData(account)
requestOngoing = false
} catch (ex: Exception) {
requestOngoing = false
log.w("Could not create account".cause(ex))
alert.showAlert(R.string.error_creating_account)
}
} else if (!EnvironmentService.isFdroid() && now() > lastAccountRefresh + ACCOUNT_REFRESH_MILLIS) {
log.v("Account is stale, refreshing")
refreshAccount()
}
}
}
fun isActive(): Boolean {
return account.value?.isActive() ?: false
}
private fun hasAccount() = try {
persistence.load(Account::class)
true
} catch (ex: Exception) { false }
private fun updateLiveData(account: Account) {
persistence.save(account)
viewModelScope.launch {
_account.value = account
}
}
}
private const val ACCOUNT_REFRESH_MILLIS = 10 * 60 * 1000 // Same as on iOS
| mpl-2.0 | 506ff856c6caa8f4281762c5dc75db34 | 35.195946 | 135 | 0.554601 | 5.092205 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/ParagraphIntrinsics.kt | 3 | 3783 | /*
* Copyright 2019 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.text
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.createFontFamilyResolver
import androidx.compose.ui.text.platform.ActualParagraphIntrinsics
import androidx.compose.ui.unit.Density
/**
* Calculates and presents the intrinsic width and height of text.
*/
interface ParagraphIntrinsics {
/**
* The width for text if all soft wrap opportunities were taken.
*/
val minIntrinsicWidth: Float
/**
* Returns the smallest width beyond which increasing the width never
* decreases the height.
*/
val maxIntrinsicWidth: Float
/**
* Any [Paragraph] rendered using this [ParagraphIntrinsics] will be measured and drawn using
* stale resolved fonts.
*
* If this is false, this [ParagraphIntrinsics] is using the most current font resolution from
* [FontFamily.Resolver].
*
* If this is true, recreating this [ParagraphIntrinsics] will use new fonts from
* [FontFamily.Resolver] for both display and measurement. Recreating this [ParagraphIntrinsics]
* and displaying the resulting [Paragraph] causes user-visible reflow of the displayed text.
*
* Once true, this will never become false without recreating this [ParagraphIntrinsics].
*
* It is discouraged, but safe, to continue to use this object after this becomes true. The
* only impact of using this object after [hasStaleResolvedFonts] becomes true is stale
* resolutions of async fonts for measurement and display.
*/
val hasStaleResolvedFonts: Boolean
get() = false
}
/**
* Factory method to create a [ParagraphIntrinsics].
*
* If the [style] does not contain any [androidx.compose.ui.text.style.TextDirection],
* [androidx.compose.ui.text.style.TextDirection.Content] is used as the default value.
*
* @see ParagraphIntrinsics
*/
@Suppress("DEPRECATION")
@Deprecated(
"Font.ResourceLoader is deprecated, instead use FontFamily.Resolver",
ReplaceWith("ParagraphIntrinsics(text, style, spanStyles, placeholders, density, " +
"fontFamilyResolver")
)
fun ParagraphIntrinsics(
text: String,
style: TextStyle,
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
density: Density,
resourceLoader: Font.ResourceLoader
): ParagraphIntrinsics = ActualParagraphIntrinsics(
text = text,
style = style,
spanStyles = spanStyles,
placeholders = placeholders,
density = density,
fontFamilyResolver = createFontFamilyResolver(resourceLoader)
)
fun ParagraphIntrinsics(
text: String,
style: TextStyle,
spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
density: Density,
fontFamilyResolver: FontFamily.Resolver
): ParagraphIntrinsics = ActualParagraphIntrinsics(
text = text,
style = style,
spanStyles = spanStyles,
placeholders = placeholders,
density = density,
fontFamilyResolver = fontFamilyResolver
) | apache-2.0 | cdc4cd91998023bdab3dd05bb3ea5fab | 35.038095 | 100 | 0.730373 | 4.619048 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/intention/impl/preview/IntentionPreviewModel.kt | 1 | 8531 | // 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.codeInsight.intention.impl.preview
import com.intellij.diff.comparison.ComparisonManager
import com.intellij.diff.comparison.ComparisonPolicy
import com.intellij.diff.fragments.LineFragment
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.diff.DiffColors
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.LineNumberConverter
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.progress.DumbProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.util.ui.JBUI
import java.awt.Color
import java.awt.Font
internal class IntentionPreviewModel {
companion object {
fun reformatRange(project: Project, psiFileCopy: PsiFile, lineFragment: LineFragment) {
val start = lineFragment.startOffset2
val end = lineFragment.endOffset2
if (start >= end) return
val document = FileDocumentManager.getInstance().getDocument(psiFileCopy.viewProvider.virtualFile)
if (document != null) PsiDocumentManager.getInstance(project).commitDocument(document)
WriteCommandAction.runWriteCommandAction(project, Runnable {
CodeStyleManager.getInstance(project).reformatRange(psiFileCopy, start, end, true)
})
}
fun createEditors(project: Project, result: IntentionPreviewDiffResult?): List<EditorEx> {
if (result == null) return emptyList()
val psiFileCopy: PsiFile = result.psiFile
val lines: List<LineFragment> = result.lineFragments
lines.forEach { lineFragment -> reformatRange(project, psiFileCopy, lineFragment) }
val fileText = psiFileCopy.text
val origText = result.origFile.text
val diff = ComparisonManager.getInstance().compareLines(origText, fileText,
ComparisonPolicy.TRIM_WHITESPACES, DumbProgressIndicator.INSTANCE)
var diffs = diff.mapNotNull { fragment ->
val start = getOffset(fileText, fragment.startLine2)
val end = getOffset(fileText, fragment.endLine2)
if (start > end) return@mapNotNull null
val origStart = getOffset(origText, fragment.startLine1)
val origEnd = getOffset(origText, fragment.endLine1)
if (origStart > origEnd) return@mapNotNull null
val newText = fileText.substring(start, end).trimStart('\n').trimEnd('\n').trimIndent()
val oldText = origText.substring(origStart, origEnd).trimStart('\n').trimEnd('\n').trimIndent()
val deleted = newText.isBlank()
if (deleted) {
if (oldText.isBlank()) return@mapNotNull null
return@mapNotNull DiffInfo(oldText, fragment.startLine1, fragment.endLine1 - fragment.startLine1, true)
}
var highlightRange: TextRange? = null
if (fragment.endLine2 - fragment.startLine2 == 1 && fragment.endLine1 - fragment.startLine1 == 1) {
val prefix = StringUtil.commonPrefixLength(oldText, newText)
val suffix = StringUtil.commonSuffixLength(oldText, newText)
if (prefix > 0 || suffix > 0) {
var endPos = newText.length - suffix
if (endPos > prefix) {
highlightRange = TextRange.create(prefix, endPos)
} else {
endPos = oldText.length - suffix
if (endPos > prefix) {
highlightRange = TextRange.create(prefix, endPos)
return@mapNotNull DiffInfo(oldText, fragment.startLine1, fragment.endLine1 - fragment.startLine1, true, highlightRange)
}
}
}
}
return@mapNotNull DiffInfo(newText, fragment.startLine1, fragment.endLine2 - fragment.startLine2, updatedRange = highlightRange)
}
if (diffs.any { info -> !info.deleted || info.updatedRange != null }) {
// Do not display deleted fragments if anything is added
diffs = diffs.filter { info -> !info.deleted || info.updatedRange != null }
}
if (diffs.isNotEmpty()) {
val last = diffs.last()
val maxLine = last.startLine + last.length
return diffs.map { it.createEditor(project, result.origFile.fileType, maxLine) }
}
return emptyList()
}
private data class DiffInfo(val fileText: String,
val startLine: Int,
val length: Int,
val deleted: Boolean = false,
val updatedRange: TextRange? = null) {
fun createEditor(project: Project,
fileType: FileType,
maxLine: Int): EditorEx {
val editor = createEditor(project, fileType, fileText, startLine, maxLine)
if (deleted) {
val colorsScheme = editor.colorsScheme
val attributes = TextAttributes(null, null, colorsScheme.defaultForeground, EffectType.STRIKEOUT, Font.PLAIN)
if (updatedRange != null) {
editor.markupModel.addRangeHighlighter(updatedRange.startOffset, updatedRange.endOffset, HighlighterLayer.ERROR + 1, attributes,
HighlighterTargetArea.EXACT_RANGE)
} else {
val document = editor.document
val lineCount = document.lineCount
for (line in 0 until lineCount) {
var start = document.getLineStartOffset(line)
var end = document.getLineEndOffset(line) - 1
while (start <= end && Character.isWhitespace(fileText[start])) start++
while (start <= end && Character.isWhitespace(fileText[end])) end--
if (start <= end) {
editor.markupModel.addRangeHighlighter(start, end + 1, HighlighterLayer.ERROR + 1, attributes,
HighlighterTargetArea.EXACT_RANGE)
}
}
}
}
else if (updatedRange != null) {
editor.markupModel.addRangeHighlighter(DiffColors.DIFF_MODIFIED, updatedRange.startOffset, updatedRange.endOffset,
HighlighterLayer.ERROR + 1, HighlighterTargetArea.EXACT_RANGE)
}
return editor
}
}
private fun getOffset(fileText: String, lineNumber: Int): Int {
return StringUtil.lineColToOffset(fileText, lineNumber, 0).let { pos -> if (pos == -1) fileText.length else pos }
}
private fun createEditor(project: Project, fileType: FileType, text: String, lineShift: Int, maxLine: Int): EditorEx {
val editorFactory = EditorFactory.getInstance()
val document = editorFactory.createDocument(text)
val editor = (editorFactory.createEditor(document, project, fileType, false) as EditorEx)
.apply { setBorder(JBUI.Borders.empty(2, 0, 2, 0)) }
editor.settings.apply {
isLineNumbersShown = true
isCaretRowShown = false
isLineMarkerAreaShown = false
isFoldingOutlineShown = false
additionalColumnsCount = 4
additionalLinesCount = 0
isRightMarginShown = false
isUseSoftWraps = false
isAdditionalPageAtBottom = false
}
editor.backgroundColor = getEditorBackground()
editor.settings.isUseSoftWraps = true
editor.scrollingModel.disableAnimation()
editor.gutterComponentEx.apply {
isPaintBackground = false
setLineNumberConverter(object : LineNumberConverter {
override fun convert(editor: Editor, line: Int): Int = line + lineShift
override fun getMaxLineNumber(editor: Editor): Int = maxLine
})
}
return editor
}
private fun getEditorBackground(): Color {
return EditorColorsManager.getInstance().globalScheme.defaultBackground
}
}
} | apache-2.0 | 1e34129bcc286e3bf0331f326eecaf61 | 44.142857 | 140 | 0.673544 | 4.880435 | false | false | false | false |
smmribeiro/intellij-community | plugins/java-decompiler/plugin/src/org/jetbrains/java/decompiler/IdeaLogger.kt | 12 | 2319 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.java.decompiler
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger
import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger.Severity.*
class IdeaLogger : IFernflowerLogger() {
@Suppress("SSBasedInspection")
private val LOG = logger<IdeaDecompiler>()
class InternalException(message: String, cause: Throwable) : RuntimeException(message, cause)
private var myClass: String? = null
override fun writeMessage(message: String, severity: Severity) {
val text = extendMessage(message)
when (severity) {
ERROR -> LOG.warn(text)
WARN -> LOG.warn(text)
INFO -> LOG.info(text)
else -> LOG.debug(text)
}
}
override fun writeMessage(message: String, severity: Severity, t: Throwable) {
when (t) {
is InternalException -> throw t
is ProcessCanceledException -> throw t
is InterruptedException -> throw ProcessCanceledException(t)
}
if (severity == ERROR) {
throw InternalException(extendMessage(message), t)
}
else {
val text = extendMessage(message)
when (severity) {
WARN -> LOG.warn(text, t)
INFO -> LOG.info(text, t)
else -> LOG.debug(text, t)
}
}
}
private fun extendMessage(message: String) = if (myClass != null) "$message [$myClass]" else message
override fun startReadingClass(className: String) {
LOG.debug("decompiling class $className")
myClass = className
}
override fun endReadingClass() {
LOG.debug("... class decompiled")
myClass = null
}
override fun startClass(className: String): Unit = LOG.debug("processing class $className")
override fun endClass(): Unit = LOG.debug("... class processed")
override fun startMethod(methodName: String): Unit = LOG.debug("processing method $methodName")
override fun endMethod(): Unit = LOG.debug("... method processed")
override fun startWriteClass(className: String): Unit = LOG.debug("writing class $className")
override fun endWriteClass(): Unit = LOG.debug("... class written")
}
| apache-2.0 | fb9cdd48521926550d01699cbbce0c70 | 32.128571 | 140 | 0.700302 | 4.278598 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/ObsoleteCodeMigrationInspection.kt | 1 | 8221 | // 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.inspections.migration
import com.intellij.analysis.AnalysisScope
import com.intellij.codeInspection.*
import com.intellij.codeInspection.actions.RunInspectionIntention
import com.intellij.codeInspection.ex.InspectionManagerEx
import com.intellij.codeInspection.ex.InspectionProfileImpl
import com.intellij.codeInspection.ex.InspectionToolWrapper
import com.intellij.openapi.project.Project
import com.intellij.profile.codeInspection.InspectionProjectProfileManager
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.configuration.MigrationInfo
import org.jetbrains.kotlin.idea.configuration.isLanguageVersionUpdate
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.quickfix.migration.MigrationFix
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.stubindex.KotlinSourceFilterScope
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
internal abstract class ObsoleteCodeMigrationInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool, MigrationFix {
protected abstract val fromVersion: LanguageVersion
protected abstract val toVersion: LanguageVersion
protected abstract val problemReporters: List<ObsoleteCodeProblemReporter>
final override fun isApplicable(migrationInfo: MigrationInfo): Boolean {
return migrationInfo.isLanguageVersionUpdate(fromVersion, toVersion)
}
final override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): KtVisitorVoid {
return simpleNameExpressionVisitor(fun(simpleNameExpression) {
val versionIsSatisfied = simpleNameExpression.languageVersionSettings.languageVersion >= toVersion
if (!versionIsSatisfied && !isUnitTestMode()) {
return
}
for (reporter in problemReporters) {
if (reporter.report(holder, isOnTheFly, simpleNameExpression)) {
return
}
}
})
}
}
internal interface ObsoleteCodeProblemReporter {
fun report(holder: ProblemsHolder, isOnTheFly: Boolean, simpleNameExpression: KtSimpleNameExpression): Boolean
}
internal interface ObsoleteCodeFix {
fun applyFix(project: Project, descriptor: ProblemDescriptor)
}
// Shortcut quick fix for running inspection in the project scope.
// Should work like RunInspectionAction.runInspection.
internal abstract class ObsoleteCodeInWholeProjectFix : LocalQuickFix {
protected abstract val inspectionName: String
final override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val toolWrapper = InspectionProjectProfileManager.getInstance(project).currentProfile.getInspectionTool(inspectionName, project)!!
runToolInProject(project, toolWrapper)
}
final override fun startInWriteAction(): Boolean = false
private fun runToolInProject(project: Project, toolWrapper: InspectionToolWrapper<*, *>) {
val managerEx = InspectionManager.getInstance(project) as InspectionManagerEx
val kotlinSourcesScope: GlobalSearchScope = KotlinSourceFilterScope.projectSources(GlobalSearchScope.allScope(project), project)
val cleanupScope = AnalysisScope(kotlinSourcesScope, project)
val cleanupToolProfile = runInInspectionProfileInitMode { RunInspectionIntention.createProfile(toolWrapper, managerEx, null) }
managerEx.createNewGlobalContext().codeCleanup(
cleanupScope,
cleanupToolProfile,
KotlinBundle.message("apply.in.the.project.0", toolWrapper.displayName),
null,
false
)
}
// Overcome failure during profile creating because of absent tools in tests
private inline fun <T> runInInspectionProfileInitMode(runnable: () -> T): T {
return if (!isUnitTestMode()) {
runnable()
} else {
val old = InspectionProfileImpl.INIT_INSPECTIONS
try {
InspectionProfileImpl.INIT_INSPECTIONS = true
runnable()
} finally {
InspectionProfileImpl.INIT_INSPECTIONS = old
}
}
}
}
/**
* There should be a single fix class with the same family name, this way it can be executed for all found problems from UI.
*/
internal abstract class ObsoleteCodeFixDelegateQuickFix(private val delegate: ObsoleteCodeFix) : LocalQuickFix {
final override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
delegate.applyFix(project, descriptor)
}
}
internal abstract class ObsoleteImportsUsageReporter : ObsoleteCodeProblemReporter {
/**
* Required to report the problem only on one psi element instead of the every single qualifier
* in the import statement.
*/
protected abstract val textMarker: String
protected abstract val packageBindings: Map<String, String>
protected open val importsToRemove: Set<String> = emptySet()
protected abstract val wholeProjectFix: LocalQuickFix
@Nls
protected abstract fun problemMessage(): String
protected abstract fun wrapFix(fix: ObsoleteCodeFix): LocalQuickFix
final override fun report(holder: ProblemsHolder, isOnTheFly: Boolean, simpleNameExpression: KtSimpleNameExpression): Boolean {
if (simpleNameExpression.text != textMarker) return false
val parent = simpleNameExpression.parent as? KtExpression ?: return false
val reportExpression = parent as? KtDotQualifiedExpression ?: simpleNameExpression
findBinding(simpleNameExpression) ?: return false
holder.registerProblem(
reportExpression,
problemMessage(),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixesWithWholeProject(isOnTheFly, wrapFix(ObsoleteImportFix()), wholeProjectFix)
)
return true
}
private fun findBinding(simpleNameExpression: KtSimpleNameExpression): Binding? {
if (simpleNameExpression.text != textMarker) return null
val importDirective = simpleNameExpression.parents
.takeWhile { it is KtDotQualifiedExpression || it is KtImportDirective }
.lastOrNull() as? KtImportDirective ?: return null
val fqNameStr = importDirective.importedFqName?.asString() ?: return null
val bindEntry = packageBindings.entries.find { (affectedImportPrefix, _) ->
fqNameStr.startsWith(affectedImportPrefix)
} ?: return null
return Binding(
FqName(bindEntry.value),
fqNameStr in importsToRemove,
importDirective
)
}
private inner class ObsoleteImportFix : ObsoleteCodeFix {
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val simpleNameExpression = when (val element = descriptor.psiElement) {
is KtSimpleNameExpression -> element
is KtDotQualifiedExpression -> element.selectorExpression as? KtSimpleNameExpression
else -> null
} ?: return
val binding = findBinding(simpleNameExpression) ?: return
if (binding.shouldRemove) {
binding.importDirective.delete()
} else {
simpleNameExpression.mainReference.bindToFqName(
binding.bindTo, shorteningMode = KtSimpleNameReference.ShorteningMode.NO_SHORTENING
)
}
}
}
private class Binding(
val bindTo: FqName,
val shouldRemove: Boolean,
val importDirective: KtImportDirective
)
}
| apache-2.0 | b232c8d580d1abcb09c3ca70d408fabc | 41.158974 | 158 | 0.726554 | 5.524866 | false | false | false | false |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/utils/alertDialogs/AlertDialogHelper.kt | 1 | 1415 | package info.nightscout.androidaps.utils.alertDialogs
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.annotation.LayoutRes
import androidx.annotation.StyleRes
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.view.ContextThemeWrapper
import info.nightscout.androidaps.core.R
object AlertDialogHelper {
@Suppress("FunctionName")
fun Builder(context: Context, @StyleRes themeResId: Int = R.style.AppTheme) =
AlertDialog.Builder(ContextThemeWrapper(context, themeResId))
fun buildCustomTitle(context: Context, title: String,
@DrawableRes iconResource: Int = R.drawable.ic_check_while_48dp,
@StyleRes themeResId: Int = R.style.AppTheme,
@LayoutRes layoutResource: Int = R.layout.dialog_alert_custom): View? {
val titleLayout = LayoutInflater.from(ContextThemeWrapper(context, themeResId)).inflate(layoutResource, null)
(titleLayout.findViewById<View>(R.id.alertdialog_title) as TextView).text = title
(titleLayout.findViewById<View>(R.id.alertdialog_icon) as ImageView).setImageResource(iconResource)
titleLayout.findViewById<View>(R.id.alertdialog_title).isSelected = true
return titleLayout
}
} | agpl-3.0 | a3eb8e7912dbf61e6a79353dc33c069c | 43.25 | 117 | 0.74841 | 4.654605 | false | false | false | false |
mdaniel/intellij-community | plugins/gradle/java/src/service/project/GradleDependencyCollector.kt | 1 | 2124 | // 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.plugins.gradle.service.project
import com.intellij.ide.plugins.DependencyCollector
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginAdvertiserService
import kotlinx.coroutines.launch
import org.jetbrains.plugins.gradle.util.GradleConstants
class GradleDependencyCollector : DependencyCollector {
override fun collectDependencies(project: Project): List<String> {
val projectInfoList = ProjectDataManager.getInstance().getExternalProjectsData(project, GradleConstants.SYSTEM_ID)
val result = mutableListOf<String>()
for (externalProjectInfo in projectInfoList) {
val projectStructure = externalProjectInfo.externalProjectStructure ?: continue
val libraries = ExternalSystemApiUtil.findAll(projectStructure, ProjectKeys.LIBRARY)
for (libraryNode in libraries) {
val groupId = libraryNode.data.groupId
val artifactId = libraryNode.data.artifactId
if (groupId != null && artifactId != null) {
result.add("$groupId:$artifactId")
}
}
}
return result
}
}
class GradleDependencyUpdater : ExternalSystemTaskNotificationListenerAdapter() {
override fun onEnd(id: ExternalSystemTaskId) {
if (id.projectSystemId == GradleConstants.SYSTEM_ID && id.type == ExternalSystemTaskType.RESOLVE_PROJECT) {
id.findProject()?.let {
it.coroutineScope.launch {
PluginAdvertiserService.getInstance().rescanDependencies(it)
}
}
}
}
}
| apache-2.0 | 056129f5992eb89a24b94cccfedd9f3a | 46.2 | 120 | 0.782957 | 5.093525 | false | false | false | false |
sewerk/Bill-Calculator | app/src/test/java/pl/srw/billcalculator/extensions.kt | 1 | 1939 | @file:JvmName("Whitebox")
package pl.srw.billcalculator
import java.lang.reflect.Field
fun Any.invokeHiddenMethod(name: String) {
val method = this.javaClass.getDeclaredMethod(name)
method.isAccessible = true
method.invoke(this)
}
fun <T> Any.getState(name: String): T {
return getInternalState(this, name)
}
fun Any.setState(name: String, value: Any) {
setInternalState(this, name, value)
}
@Suppress("UNCHECKED_CAST")
fun <T> getInternalState(target: Any, field: String): T {
val c = target.javaClass
try {
val f = getFieldFromHierarchy(c, field)
f.isAccessible = true
return f.get(target) as T
} catch (e: Exception) {
throw RuntimeException("Unable to get internal state on a private field. Please report to mockito mailing list.", e)
}
}
fun setInternalState(target: Any, field: String, value: Any) {
val c = target.javaClass
try {
val f = getFieldFromHierarchy(c, field)
f.isAccessible = true
f.set(target, value)
} catch (e: Exception) {
throw RuntimeException("Unable to set internal state on a private field. Please report to mockito mailing list.", e)
}
}
private fun getFieldFromHierarchy(clazz: Class<*>, field: String): Field {
var vClazz = clazz
var f = getField(vClazz, field)
while (f == null && vClazz != Any::class.java) {
vClazz = vClazz.superclass
f = getField(vClazz, field)
}
if (f == null) {
throw RuntimeException(
"You want me to get this field: '" + field +
"' on this class: '" + vClazz.simpleName +
"' but this field is not declared withing hierarchy of this class!")
}
return f
}
private fun getField(clazz: Class<*>, field: String): Field? {
try {
return clazz.getDeclaredField(field)
} catch (e: NoSuchFieldException) {
return null
}
}
| mit | 097d10119e74db63f8fc9bf785a33ebc | 27.101449 | 124 | 0.630737 | 3.893574 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/ide/startup/CheckProjectActivity.kt | 1 | 2875 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.startup
import com.intellij.configurationStore.checkUnknownMacros
import com.intellij.internal.statistic.collectors.fus.project.ProjectFsStatsCollector
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl
import com.intellij.util.TimeoutUtil
import com.intellij.util.concurrency.NonUrgentExecutor
internal class CheckProjectActivity : StartupActivity.DumbAware {
init {
if (ApplicationManager.getApplication().isHeadlessEnvironment || ApplicationManager.getApplication().isUnitTestMode) {
throw ExtensionNotApplicableException.INSTANCE
}
}
override fun runActivity(project: Project) {
NonUrgentExecutor.getInstance().execute {
checkUnknownMacros(project, true)
checkProjectRoots(project)
}
}
private fun checkProjectRoots(project: Project) {
val roots = ProjectRootManager.getInstance(project).contentRoots
if (roots.isEmpty()) {
return
}
val watcher = (LocalFileSystem.getInstance() as? LocalFileSystemImpl ?: return).fileWatcher
if (!watcher.isOperational) {
ProjectFsStatsCollector.watchedRoots(project, -1)
return
}
val logger = logger<CheckProjectActivity>()
logger.debug("FW/roots waiting started")
while (watcher.isSettingRoots) {
if (project.isDisposed) {
return
}
TimeoutUtil.sleep(10)
}
logger.debug("FW/roots waiting finished")
val manualWatchRoots = watcher.manualWatchRoots
var pctNonWatched = 0
if (manualWatchRoots.isNotEmpty()) {
val unwatched = roots.filter { root -> root.isInLocalFileSystem && manualWatchRoots.any { VfsUtilCore.isAncestorOrSelf(it, root) } }
if (unwatched.isNotEmpty()) {
val message = ApplicationBundle.message("watcher.non.watchable.project", ApplicationNamesInfo.getInstance().fullProductName)
watcher.notifyOnFailure(message, null)
logger.info("unwatched roots: ${unwatched.map { it.presentableUrl }}")
logger.info("manual watches: ${manualWatchRoots}")
pctNonWatched = (100.0 * unwatched.size / roots.size).toInt()
}
}
ProjectFsStatsCollector.watchedRoots(project, pctNonWatched)
}
}
| apache-2.0 | d69131589903889c26440a3a3b1692ed | 40.071429 | 158 | 0.762783 | 4.705401 | false | false | false | false |
spring-cloud/spring-cloud-contract | specs/spring-cloud-contract-spec-kotlin/src/main/kotlin/org/springframework/cloud/contract/spec/internal/ResponseDsl.kt | 1 | 11145 | /*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.cloud.contract.spec.internal
import org.springframework.cloud.contract.spec.toDslProperties
import org.springframework.cloud.contract.spec.toDslProperty
import org.springframework.cloud.contract.spec.util.RegexpUtils
import java.util.regex.Pattern
/**
* Represents the response side of the HTTP communication.
*
* @author Tim Ysewyn
* @since 2.2.0
*/
@ContractDslMarker
class ResponseDsl : CommonDsl() {
private val delegate = Response()
/**
* The HTTP response status.
*/
var status: DslProperty<Any>? = null
/**
* The HTTP response delay in milliseconds.
*/
var delay: DslProperty<Any>? = null
/**
* The HTTP response headers.
*/
var headers: Headers? = null
/**
* The HTTP response cookies.
*/
var cookies: Cookies? = null
/**
* The HTTP response body.
*/
var body: Body? = null
/**
* Indicates asynchronous communication.
*/
var async: Boolean = false
/**
* The HTTP response body matchers.
*/
var bodyMatchers: ResponseBodyMatchers? = null
fun code(code: Int): DslProperty<Any> = code.toDslProperty()
fun fixedMilliseconds(delay: Int): DslProperty<Any> = delay.toDslProperty()
/**
* @deprecated Use the {@link #fixedMilliseconds(int) fixedMilliseconds} method.
*/
fun fixedMilliseconds(delay: Long): DslProperty<Any> = fixedMilliseconds(delay.toInt())
fun headers(headers: HeadersDsl.() -> Unit) {
this.headers = ResponseHeadersDsl().apply(headers).get()
}
fun cookies(cookies: CookiesDsl.() -> Unit) {
this.cookies = ResponseCookiesDsl().apply(cookies).get()
}
fun body(body: Map<String, Any>) = Body(body.toDslProperties())
fun body(vararg body: Pair<String, Any>) = Body(body.toMap().toDslProperties())
fun body(body: Pair<String, Any>) = Body(mapOf(body).toDslProperties())
fun body(body: List<Any>) = Body(body.toDslProperties())
fun body(body: Any) = Body(body)
fun bodyMatchers(configurer: ResponseBodyMatchersDsl.() -> Unit) {
bodyMatchers = ResponseBodyMatchersDsl().apply(configurer).get()
}
/* HELPER VARIABLES */
/* HTTP STATUS CODES */
val CONTINUE
get() = code(HttpStatus.CONTINUE)
val SWITCHING_PROTOCOLS
get() = code(HttpStatus.SWITCHING_PROTOCOLS)
val PROCESSING
get() = code(HttpStatus.PROCESSING)
val CHECKPOINT
get() = code(HttpStatus.CHECKPOINT)
val OK
get() = code(HttpStatus.OK)
val CREATED
get() = code(HttpStatus.CREATED)
val ACCEPTED
get() = code(HttpStatus.ACCEPTED)
val NON_AUTHORITATIVE_INFORMATION
get() = code(HttpStatus.NON_AUTHORITATIVE_INFORMATION)
val NO_CONTENT
get() = code(HttpStatus.NO_CONTENT)
val RESET_CONTENT
get() = code(HttpStatus.RESET_CONTENT)
val PARTIAL_CONTENT
get() = code(HttpStatus.PARTIAL_CONTENT)
val MULTI_STATUS
get() = code(HttpStatus.MULTI_STATUS)
val ALREADY_REPORTED
get() = code(HttpStatus.ALREADY_REPORTED)
val IM_USED
get() = code(HttpStatus.IM_USED)
val MULTIPLE_CHOICES
get() = code(HttpStatus.MULTIPLE_CHOICES)
val MOVED_PERMANENTLY
get() = code(HttpStatus.MOVED_PERMANENTLY)
val FOUND
get() = code(HttpStatus.FOUND)
val SEE_OTHER
get() = code(HttpStatus.SEE_OTHER)
val NOT_MODIFIED
get() = code(HttpStatus.NOT_MODIFIED)
val TEMPORARY_REDIRECT
get() = code(HttpStatus.TEMPORARY_REDIRECT)
val PERMANENT_REDIRECT
get() = code(HttpStatus.PERMANENT_REDIRECT)
val BAD_REQUEST
get() = code(HttpStatus.BAD_REQUEST)
val UNAUTHORIZED
get() = code(HttpStatus.UNAUTHORIZED)
val PAYMENT_REQUIRED
get() = code(HttpStatus.PAYMENT_REQUIRED)
val FORBIDDEN
get() = code(HttpStatus.FORBIDDEN)
val NOT_FOUND
get() = code(HttpStatus.NOT_FOUND)
val METHOD_NOT_ALLOWED
get() = code(HttpStatus.METHOD_NOT_ALLOWED)
val NOT_ACCEPTABLE
get() = code(HttpStatus.NOT_ACCEPTABLE)
val PROXY_AUTHENTICATION_REQUIRED
get() = code(HttpStatus.PROXY_AUTHENTICATION_REQUIRED)
val REQUEST_TIMEOUT
get() = code(HttpStatus.REQUEST_TIMEOUT)
val CONFLICT
get() = code(HttpStatus.CONFLICT)
val GONE
get() = code(HttpStatus.GONE)
val LENGTH_REQUIRED
get() = code(HttpStatus.LENGTH_REQUIRED)
val PRECONDITION_FAILED
get() = code(HttpStatus.PRECONDITION_FAILED)
val PAYLOAD_TOO_LARGE
get() = code(HttpStatus.PAYLOAD_TOO_LARGE)
val UNSUPPORTED_MEDIA_TYPE
get() = code(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
val REQUESTED_RANGE_NOT_SATISFIABLE
get() = code(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
val EXPECTATION_FAILED
get() = code(HttpStatus.EXPECTATION_FAILED)
val I_AM_A_TEAPOT
get() = code(HttpStatus.I_AM_A_TEAPOT)
val UNPROCESSABLE_ENTITY
get() = code(HttpStatus.UNPROCESSABLE_ENTITY)
val LOCKED
get() = code(HttpStatus.LOCKED)
val FAILED_DEPENDENCY
get() = code(HttpStatus.FAILED_DEPENDENCY)
val UPGRADE_REQUIRED
get() = code(HttpStatus.UPGRADE_REQUIRED)
val PRECONDITION_REQUIRED
get() = code(HttpStatus.PRECONDITION_REQUIRED)
val TOO_MANY_REQUESTS
get() = code(HttpStatus.TOO_MANY_REQUESTS)
val REQUEST_HEADER_FIELDS_TOO_LARGE
get() = code(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE)
val UNAVAILABLE_FOR_LEGAL_REASONS
get() = code(HttpStatus.UNAVAILABLE_FOR_LEGAL_REASONS)
val INTERNAL_SERVER_ERROR
get() = code(HttpStatus.INTERNAL_SERVER_ERROR)
val NOT_IMPLEMENTED
get() = code(HttpStatus.NOT_IMPLEMENTED)
val BAD_GATEWAY
get() = code(HttpStatus.BAD_GATEWAY)
val SERVICE_UNAVAILABLE
get() = code(HttpStatus.SERVICE_UNAVAILABLE)
val GATEWAY_TIMEOUT
get() = code(HttpStatus.GATEWAY_TIMEOUT)
val HTTP_VERSION_NOT_SUPPORTED
get() = code(HttpStatus.HTTP_VERSION_NOT_SUPPORTED)
val VARIANT_ALSO_NEGOTIATES
get() = code(HttpStatus.VARIANT_ALSO_NEGOTIATES)
val INSUFFICIENT_STORAGE
get() = code(HttpStatus.INSUFFICIENT_STORAGE)
val LOOP_DETECTED
get() = code(HttpStatus.LOOP_DETECTED)
val BANDWIDTH_LIMIT_EXCEEDED
get() = code(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED)
val NOT_EXTENDED
get() = code(HttpStatus.NOT_EXTENDED)
val NETWORK_AUTHENTICATION_REQUIRED
get() = code(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED)
/* REGEX */
val anyAlphaUnicode
get() = delegate.anyAlphaUnicode()
val anyAlphaNumeric
get() = delegate.anyAlphaNumeric()
val anyNumber
get() = delegate.anyNumber()
val anyInteger
get() = delegate.anyInteger()
val anyPositiveInt
get() = delegate.anyPositiveInt()
val anyDouble
get() = delegate.anyDouble()
val anyHex
get() = delegate.anyHex()
val aBoolean
get() = delegate.aBoolean()
val anyIpAddress
get() = delegate.anyIpAddress()
val anyHostname
get() = delegate.anyHostname()
val anyEmail
get() = delegate.anyEmail()
val anyUrl
get() = delegate.anyUrl()
val anyHttpsUrl
get() = delegate.anyHttpsUrl()
val anyUuid
get() = delegate.anyUuid()
val anyDate
get() = delegate.anyDate()
val anyDateTime
get() = delegate.anyDateTime()
val anyTime
get() = delegate.anyTime()
val anyIso8601WithOffset
get() = delegate.anyIso8601WithOffset()
val anyNonBlankString
get() = delegate.anyNonBlankString()
val anyNonEmptyString
get() = delegate.anyNonEmptyString()
/* HELPER FUNCTIONS */
fun value(value: ClientDslProperty) = delegate.value(value)
fun v(value: ClientDslProperty) = delegate.value(value)
fun value(value: DslProperty<Any>) = delegate.value(value)
fun v(value: DslProperty<Any>) = delegate.value(value)
fun value(value: Pattern) = delegate.value(value)
fun v(value: Pattern) = delegate.value(value)
fun value(value: RegexProperty) = delegate.value(value)
fun v(value: RegexProperty) = delegate.value(value)
fun value(value: Any?) = delegate.value(value)
fun v(value: Any?) = delegate.value(value)
fun value(client: ClientDslProperty, server: ServerDslProperty) = delegate.value(client, server)
fun v(client: ClientDslProperty, server: ServerDslProperty) = delegate.value(client, server)
fun value(server: ServerDslProperty, client: ClientDslProperty) = delegate.value(client, server)
fun v(server: ServerDslProperty, client: ClientDslProperty) = delegate.value(client, server)
fun fromRequest() = FromRequestDsl()
fun anyOf(vararg values: String?) = delegate.anyOf(*values)
internal fun get(): Response {
val response = Response()
status?.also { response.status = status }
delay?.also { response.delay = delay }
headers?.also { response.headers = headers }
cookies?.also { response.cookies = cookies }
body?.also { response.body = body }
response.async = async
bodyMatchers?.also { response.bodyMatchers = bodyMatchers }
return response
}
private class ResponseHeadersDsl : HeadersDsl() {
private val common = Common()
override fun matching(value: Any?): Any? {
return value?.also {
return when (value) {
is String -> return this.common.value(
c(value),
p(NotToEscapePattern(Pattern.compile(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*")))
)
else -> value
}
}
}
}
private class ResponseCookiesDsl : CookiesDsl() {
private val common = Common()
override fun matching(value: Any?): Any? {
return value?.also {
return when (value) {
is String -> return this.common.value(
c(value),
p(regex(RegexpUtils.escapeSpecialRegexWithSingleEscape(value) + ".*"))
)
else -> value
}
}
}
}
}
| apache-2.0 | 47eebcc25f774a07751c5c42109c8759 | 25.223529 | 128 | 0.63598 | 4.188275 | false | false | false | false |
JetBrains/kotlin-native | performance/ring/src/main/kotlin/org/jetbrains/ring/ForLoopsBenchmark.kt | 2 | 2050 | package org.jetbrains.ring
class ForLoopsBenchmark {
private val array: Array<Int> = Array(BENCHMARK_SIZE) {
it
}
private val intArray: IntArray = IntArray(BENCHMARK_SIZE) {
it
}
private val charArray: CharArray = CharArray(BENCHMARK_SIZE) {
it.toChar()
}
private val string: String = charArray.joinToString()
private val floatArray: FloatArray = FloatArray(BENCHMARK_SIZE) {
it.toFloat()
}
fun arrayLoop(): Long {
var sum = 0L
for (e in array) {
sum += e
}
return sum
}
fun intArrayLoop(): Long {
var sum = 0L
for (e in intArray) {
sum += e
}
return sum
}
fun charArrayLoop(): Long {
var sum = 0L
for (e in charArray) {
sum += e.toLong()
}
return sum
}
fun stringLoop(): Long {
var sum = 0L
for (e in string) {
sum += e.hashCode()
}
return sum
}
fun floatArrayLoop(): Double {
var sum = 0.0
for (e in floatArray) {
sum += e
}
return sum
}
// Iterations over .indices
fun arrayIndicesLoop(): Long {
var sum = 0L
for (i in array.indices) {
sum += array[i]
}
return sum
}
fun intArrayIndicesLoop(): Long {
var sum = 0L
for (i in intArray.indices) {
sum += intArray[i]
}
return sum
}
fun charArrayIndicesLoop(): Long {
var sum = 0L
for (i in charArray.indices) {
sum += charArray[i].toLong()
}
return sum
}
fun stringIndicesLoop(): Long {
var sum = 0L
for (i in string.indices) {
sum += string[i].hashCode()
}
return sum
}
fun floatArrayIndicesLoop(): Double {
var sum = 0.0
for (i in floatArray.indices) {
sum += floatArray[i]
}
return sum
}
} | apache-2.0 | d6cfcd84e0cd33dd15eb6287776f42dd | 18.721154 | 69 | 0.48439 | 4.253112 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis-api-providers-ide-impl/src/org/jetbrains/kotlin/analysis/providers/ide/KotlinIdeDeclarationProviderFactory.kt | 1 | 5226 | // 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.analysis.providers.ide
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey
import org.jetbrains.kotlin.analysis.providers.KotlinDeclarationProvider
import org.jetbrains.kotlin.analysis.providers.KotlinDeclarationProviderFactory
import org.jetbrains.kotlin.idea.stubindex.*
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
internal class KotlinIdeDeclarationProviderFactory(private val project: Project) : KotlinDeclarationProviderFactory() {
override fun createDeclarationProvider(searchScope: GlobalSearchScope): KotlinDeclarationProvider {
return KotlinIdeDeclarationProvider(project, searchScope)
}
}
private class KotlinIdeDeclarationProvider(
private val project: Project,
private val searchScope: GlobalSearchScope
) : KotlinDeclarationProvider() {
private val stubIndex: StubIndex = StubIndex.getInstance()
private inline fun <INDEX_KEY : Any, reified PSI : PsiElement> firstMatchingOrNull(
stubKey: StubIndexKey<INDEX_KEY, PSI>,
key: INDEX_KEY,
crossinline filter: (PSI) -> Boolean = { true }
): PSI? {
var result: PSI? = null
stubIndex.processElements(
stubKey, key, project, searchScope, PSI::class.java,
) { candidate ->
if (filter(candidate)) {
result = candidate
return@processElements false // do not continue searching over PSI
}
true
}
return result
}
override fun getClassesByClassId(classId: ClassId): Collection<KtClassOrObject> {
return KotlinFullClassNameIndex
.get(classId.asStringForIndexes(), project, searchScope)
.filter { candidate -> candidate.containingKtFile.packageFqName == classId.packageFqName }
}
override fun getTypeAliasesByClassId(classId: ClassId): Collection<KtTypeAlias> {
return listOfNotNull(getTypeAliasByClassId(classId)) //todo
}
override fun getTypeAliasNamesInPackage(packageFqName: FqName): Set<Name> {
return KotlinTopLevelTypeAliasByPackageIndex
.get(packageFqName.asStringForIndexes(), project, searchScope)
.mapNotNullTo(mutableSetOf()) { it.nameAsName }
}
override fun getPropertyNamesInPackage(packageFqName: FqName): Set<Name> {
return KotlinTopLevelPropertyByPackageIndex
.get(packageFqName.asStringForIndexes(), project, searchScope)
.mapNotNullTo(mutableSetOf()) { it.nameAsName }
}
override fun getFunctionsNamesInPackage(packageFqName: FqName): Set<Name> {
return KotlinTopLevelFunctionByPackageIndex
.get(packageFqName.asStringForIndexes(), project, searchScope)
.mapNotNullTo(mutableSetOf()) { it.nameAsName }
}
override fun getFacadeFilesInPackage(packageFqName: FqName): Collection<KtFile> {
return KotlinFileFacadeClassByPackageIndex
.get(packageFqName.asString(), project, searchScope)
}
override fun findFilesForFacade(facadeFqName: FqName): Collection<KtFile> {
return KotlinFileFacadeFqNameIndex.get(
key = facadeFqName.asString(),
project = project,
scope = searchScope
) //TODO original LC has platformSourcesFirst()
}
private fun getTypeAliasByClassId(classId: ClassId): KtTypeAlias? {
return firstMatchingOrNull(
stubKey = KotlinTopLevelTypeAliasFqNameIndex.KEY,
key = classId.asStringForIndexes(),
filter = { candidate -> candidate.containingKtFile.packageFqName == classId.packageFqName }
) ?: firstMatchingOrNull(stubKey = KotlinInnerTypeAliasClassIdIndex.key, key = classId.asString())
}
override fun getTopLevelProperties(callableId: CallableId): Collection<KtProperty> =
KotlinTopLevelPropertyFqnNameIndex.get(callableId.asStringForIndexes(), project, searchScope)
override fun getTopLevelFunctions(callableId: CallableId): Collection<KtNamedFunction> =
KotlinTopLevelFunctionFqnNameIndex.get(callableId.asStringForIndexes(), project, searchScope)
override fun getClassNamesInPackage(packageFqName: FqName): Set<Name> =
KotlinTopLevelClassByPackageIndex
.get(packageFqName.asStringForIndexes(), project, searchScope)
.mapNotNullTo(hashSetOf()) { it.nameAsName }
companion object {
private fun CallableId.asStringForIndexes(): String =
(if (packageName.isRoot) callableName.asString() else toString()).replace('/', '.')
private fun FqName.asStringForIndexes(): String =
asString().replace('/', '.')
private fun ClassId.asStringForIndexes(): String =
asSingleFqName().asStringForIndexes()
}
}
| apache-2.0 | acb31679b48f4e78e0005d940a41db9f | 41.145161 | 158 | 0.716418 | 5.278788 | false | false | false | false |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/utils/junix/virt/virsh/LibvirtXmlArch.kt | 2 | 356 | package com.github.kerubistan.kerub.utils.junix.virt.virsh
import javax.xml.bind.annotation.XmlAttribute
import javax.xml.bind.annotation.XmlElement
class LibvirtXmlArch {
@get:XmlAttribute(name = "name")
var name: String = ""
@get:XmlElement(name = "wordsize")
var wordsize: Int = 0
@get:XmlElement(name = "emulator")
var emulator: String = ""
}
| apache-2.0 | 0b60e28e6d6290a24e24cefd2a889437 | 24.428571 | 58 | 0.744382 | 3.122807 | false | false | false | false |
JetBrains/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/CommitSessionCollector.kt | 1 | 11781 | // 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.vcs.commit
import com.intellij.diff.DiffContext
import com.intellij.diff.DiffExtension
import com.intellij.diff.FrameDiffTool
import com.intellij.diff.actions.impl.OpenInEditorAction
import com.intellij.diff.requests.DiffRequest
import com.intellij.diff.requests.MessageDiffRequest
import com.intellij.diff.tools.util.DiffDataKeys
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.diff.util.DiffUtil
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionResult
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ChangesViewWorkflowManager
import com.intellij.openapi.vcs.changes.ui.ChangesTree
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CommitCheck
import com.intellij.openapi.vcs.checkin.CommitProblem
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.TreeActions
import java.awt.event.HierarchyEvent
import java.awt.event.MouseEvent
import java.util.*
import javax.swing.JTree
class CommitSessionCounterUsagesCollector : CounterUsagesCollector() {
companion object {
val GROUP = EventLogGroup("commit.interactions", 4)
val FILES_TOTAL = EventFields.RoundedInt("files_total")
val FILES_INCLUDED = EventFields.RoundedInt("files_included")
val UNVERSIONED_TOTAL = EventFields.RoundedInt("unversioned_total")
val UNVERSIONED_INCLUDED = EventFields.RoundedInt("unversioned_included")
val COMMIT_CHECK_CLASS = EventFields.Class("commit_check_class")
val COMMIT_PROBLEM_CLASS = EventFields.Class("commit_problem_class")
val EXECUTION_ORDER = EventFields.Enum("execution_order", CommitCheck.ExecutionOrder::class.java)
val COMMIT_OPTION = EventFields.Enum("commit_option", CommitOption::class.java)
val COMMIT_PROBLEM_PLACE = EventFields.Enum("commit_problem_place", CommitProblemPlace::class.java)
val IS_FROM_SETTINGS = EventFields.Boolean("is_from_settings")
val IS_SUCCESS = EventFields.Boolean("is_success")
val WARNINGS_COUNT = EventFields.RoundedInt("warnings_count")
val ERRORS_COUNT = EventFields.RoundedInt("errors_count")
val SESSION = GROUP.registerIdeActivity("session",
startEventAdditionalFields = arrayOf(FILES_TOTAL, FILES_INCLUDED,
UNVERSIONED_TOTAL, UNVERSIONED_INCLUDED),
finishEventAdditionalFields = arrayOf())
val COMMIT_CHECK_SESSION = GROUP.registerIdeActivity("commit_check_session",
startEventAdditionalFields = arrayOf(COMMIT_CHECK_CLASS, EXECUTION_ORDER),
finishEventAdditionalFields = arrayOf(IS_SUCCESS))
val EXCLUDE_FILE = GROUP.registerEvent("exclude.file", EventFields.InputEventByAnAction, EventFields.InputEventByMouseEvent)
val INCLUDE_FILE = GROUP.registerEvent("include.file", EventFields.InputEventByAnAction, EventFields.InputEventByMouseEvent)
val SELECT_FILE = GROUP.registerEvent("select.item", EventFields.InputEventByAnAction, EventFields.InputEventByMouseEvent)
val SHOW_DIFF = GROUP.registerEvent("show.diff")
val CLOSE_DIFF = GROUP.registerEvent("close.diff")
val JUMP_TO_SOURCE = GROUP.registerEvent("jump.to.source", EventFields.InputEventByAnAction)
val COMMIT = GROUP.registerEvent("commit", FILES_INCLUDED, UNVERSIONED_INCLUDED)
val COMMIT_AND_PUSH = GROUP.registerEvent("commit.and.push", FILES_INCLUDED, UNVERSIONED_INCLUDED)
val TOGGLE_COMMIT_CHECK = GROUP.registerEvent("toggle.commit.check", COMMIT_CHECK_CLASS, IS_FROM_SETTINGS, EventFields.Enabled)
val TOGGLE_COMMIT_OPTION = GROUP.registerEvent("toggle.commit.option", COMMIT_OPTION, EventFields.Enabled)
val VIEW_COMMIT_PROBLEM = GROUP.registerEvent("view.commit.problem", COMMIT_PROBLEM_CLASS, COMMIT_PROBLEM_PLACE)
val CODE_ANALYSIS_WARNING = GROUP.registerEvent("code.analysis.warning", WARNINGS_COUNT, ERRORS_COUNT)
}
enum class CommitOption { SIGN_OFF, RUN_HOOKS, AMEND }
enum class CommitProblemPlace { NOTIFICATION, COMMIT_TOOLWINDOW, PUSH_DIALOG }
override fun getGroup(): EventLogGroup = GROUP
}
@Service(Service.Level.PROJECT)
class CommitSessionCollector(val project: Project) {
companion object {
@JvmStatic
fun getInstance(project: Project): CommitSessionCollector = project.service()
}
private var activity: StructuredIdeActivity? = null
private fun shouldTrackEvents(): Boolean {
val mode = CommitModeManager.getInstance(project).getCurrentCommitMode()
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.COMMIT_TOOLWINDOW_ID)
return toolWindow != null && mode is CommitMode.NonModalCommitMode && !mode.isToggleMode
}
private fun updateToolWindowState() {
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.COMMIT_TOOLWINDOW_ID)
val isSessionActive = shouldTrackEvents() && toolWindow?.isVisible == true
if (!isSessionActive) {
finishActivity()
}
else if (activity == null) {
val commitUi = ChangesViewWorkflowManager.getInstance(project).commitWorkflowHandler?.ui ?: return
activity = CommitSessionCounterUsagesCollector.SESSION.started(project) {
listOf(
CommitSessionCounterUsagesCollector.FILES_TOTAL.with(commitUi.getDisplayedChanges().size),
CommitSessionCounterUsagesCollector.FILES_INCLUDED.with(commitUi.getIncludedChanges().size),
CommitSessionCounterUsagesCollector.UNVERSIONED_TOTAL.with(commitUi.getDisplayedUnversionedFiles().size),
CommitSessionCounterUsagesCollector.UNVERSIONED_INCLUDED.with(commitUi.getIncludedUnversionedFiles().size)
)
}
}
}
private fun finishActivity() {
activity?.finished()
activity = null
}
fun logFileSelected(event: MouseEvent) {
if (!shouldTrackEvents()) return
CommitSessionCounterUsagesCollector.SELECT_FILE.log(project, null, event)
}
fun logFileSelected(event: AnActionEvent) {
if (!shouldTrackEvents()) return
CommitSessionCounterUsagesCollector.SELECT_FILE.log(project, event, null)
}
fun logInclusionToggle(excluded: Boolean, event: AnActionEvent) {
if (!shouldTrackEvents()) return
if (excluded) {
CommitSessionCounterUsagesCollector.EXCLUDE_FILE.log(project, event, null)
}
else {
CommitSessionCounterUsagesCollector.INCLUDE_FILE.log(project, event, null)
}
}
fun logInclusionToggle(excluded: Boolean, event: MouseEvent) {
if (!shouldTrackEvents()) return
if (excluded) {
CommitSessionCounterUsagesCollector.EXCLUDE_FILE.log(project, null, event)
}
else {
CommitSessionCounterUsagesCollector.INCLUDE_FILE.log(project, null, event)
}
}
fun logCommit(executorId: String?, includedChanges: Int, includedUnversioned: Int) {
if (!shouldTrackEvents()) return
if (executorId == "Git.Commit.And.Push.Executor") {
CommitSessionCounterUsagesCollector.COMMIT_AND_PUSH.log(project, includedChanges, includedUnversioned)
}
else {
CommitSessionCounterUsagesCollector.COMMIT.log(project, includedChanges, includedUnversioned)
}
finishActivity()
updateToolWindowState()
}
fun logDiffViewer(isShown: Boolean) {
if (!shouldTrackEvents()) return
if (isShown) {
CommitSessionCounterUsagesCollector.SHOW_DIFF.log(project)
}
else {
CommitSessionCounterUsagesCollector.CLOSE_DIFF.log(project)
}
}
fun logJumpToSource(event: AnActionEvent) {
if (!shouldTrackEvents()) return
CommitSessionCounterUsagesCollector.JUMP_TO_SOURCE.log(project, event)
}
fun logCommitCheckToggled(checkinHandler: CheckinHandler, isSettings: Boolean, value: Boolean) {
CommitSessionCounterUsagesCollector.TOGGLE_COMMIT_CHECK.log(checkinHandler.javaClass, isSettings, value)
}
fun logCommitOptionToggled(option: CommitSessionCounterUsagesCollector.CommitOption, value: Boolean) {
CommitSessionCounterUsagesCollector.TOGGLE_COMMIT_OPTION.log(option, value)
}
fun logCodeAnalysisWarnings(warnings: Int, errors: Int) {
CommitSessionCounterUsagesCollector.CODE_ANALYSIS_WARNING.log(warnings, errors)
}
fun logCommitProblemViewed(commitProblem: CommitProblem, place: CommitSessionCounterUsagesCollector.CommitProblemPlace) {
CommitSessionCounterUsagesCollector.VIEW_COMMIT_PROBLEM.log(commitProblem.javaClass, place)
}
internal class MyToolWindowManagerListener(val project: Project) : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
getInstance(project).updateToolWindowState()
}
}
internal class MyDiffExtension : DiffExtension() {
private val HierarchyEvent.isShowingChanged get() = (changeFlags and HierarchyEvent.SHOWING_CHANGED.toLong()) != 0L
override fun onViewerCreated(viewer: FrameDiffTool.DiffViewer, context: DiffContext, request: DiffRequest) {
val project = context.project ?: return
if (!DiffUtil.isUserDataFlagSet(DiffUserDataKeysEx.LAST_REVISION_WITH_LOCAL, context)) return
if (request is MessageDiffRequest) return
viewer.component.addHierarchyListener { e ->
if (e.isShowingChanged) {
if (e.component.isShowing) {
getInstance(project).logDiffViewer(true)
}
else {
getInstance(project).logDiffViewer(false)
}
}
}
}
}
/**
* See [com.intellij.internal.statistic.collectors.fus.actions.persistence.ActionsCollectorImpl]
*/
internal class MyAnActionListener : AnActionListener {
private val ourStats: MutableMap<AnActionEvent, Project> = WeakHashMap()
override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) {
val project = event.project ?: return
if (action is OpenInEditorAction) {
val context = event.getData(DiffDataKeys.DIFF_CONTEXT) ?: return
if (!DiffUtil.isUserDataFlagSet(DiffUserDataKeysEx.LAST_REVISION_WITH_LOCAL, context)) return
ourStats[event] = project
}
if (action is TreeActions) {
val component = event.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as? JTree ?: return
if (component.getClientProperty(ChangesTree.LOG_COMMIT_SESSION_EVENTS) != true) return
ourStats[event] = project
}
}
override fun afterActionPerformed(action: AnAction, event: AnActionEvent, result: AnActionResult) {
val project = ourStats.remove(event) ?: return
if (!result.isPerformed) return
if (action is OpenInEditorAction) {
getInstance(project).logJumpToSource(event)
}
if (action is TreeActions) {
getInstance(project).logFileSelected(event)
}
}
}
}
| apache-2.0 | 2d8f0fb8987decaa231f4b7151d20719 | 44.662791 | 158 | 0.747475 | 4.844161 | false | false | false | false |
androidx/androidx | core/core/src/androidTest/java/androidx/core/content/pm/PackageInfoCompatHasSignaturesTest.kt | 3 | 21778 | /*
* 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.core.content.pm
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.Signature
import android.content.pm.SigningInfo
import android.os.Build
import androidx.core.content.pm.PackageInfoCompatHasSignaturesTest.Companion.Params.QueryType
import androidx.core.content.pm.PackageInfoCompatHasSignaturesTest.MockCerts.MockSignatures
import androidx.core.content.pm.PackageInfoCompatHasSignaturesTest.MockCerts.MockSigningInfo
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import androidx.testutils.mockito.mockThrowOnUnmocked
import androidx.testutils.mockito.whenever
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.mockito.Mockito.any
import org.mockito.Mockito.anyInt
import org.mockito.Mockito.eq
import org.mockito.internal.util.reflection.FieldSetter
import java.security.MessageDigest
/**
* Verifies [PackageInfoCompat.hasSignatures].
*
* Due to testability restrictions with the [SigningInfo] and [Signature] classes and
* infrastructure for install test packages in a device test, this test uses mocked classes to
* verify the correct method calls. Mocking in general is preferable to signing several test
* packages as this isolates the test parameters to inside the test class.
*
* As final class mocking is only available starting from [Build.VERSION_CODES.P], this test
* manually runs itself for both [Build.VERSION_CODES.O] and the current device SDK version
* by swapping [Build.VERSION.SDK_INT].
*/
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.P)
@LargeTest
@RunWith(Parameterized::class)
class PackageInfoCompatHasSignaturesTest {
companion object {
// Following are random public certs (effectively random strings) as this test does not
// validate the actual signature integrity. Only the fact that the hashes and comparisons
// work and return the correct values.
private const val CERT_1 = "2d2d2d2d2d424547494e2043455254494649434154452d2d2d2d2d0a4d494" +
"9422b44434341574767417749424167495548384f42374c355a53594f7852577056774e454f4c336" +
"5726c5077774451594a4b6f5a496876634e4151454c0a425141774454454c4d416b4741315545426" +
"84d4356564d774942634e4d6a41774f5449794d6a4d774d6a557a576867504d7a41794d4441784d6" +
"a51794d7a41790a4e544e614d413078437a414a42674e5642415954416c56544d4947664d4130474" +
"35371475349623344514542415155414134474e4144434269514b42675144450a6f3650386341636" +
"c77734a646e773457415a755a685244795031556473334d5766703738434448344548614d682f393" +
"54a7941316e5a776e2f644174747375640a6e464356713065592b32736d373663334d454a542b456" +
"86b443170792f6148324f366c3639314d2b334e7a6a616272752f4c457451364d736232494553454" +
"2690a7a63415350756a4a635458586b346a6d44535a4d6d6359653259466d506b633151534f31387" +
"875446a514944415141426f314d775554416442674e56485134450a4667515534746446716839634" +
"16d4d35707665674d514265476c442b4b774d77487759445652306a42426777466f4155347464467" +
"1683963416d4d35707665670a4d514265476c442b4b774d7744775944565230544151482f4241557" +
"7417745422f7a414e42676b71686b6947397730424151734641414f426751436a70535a760a4d546" +
"76f584c3042304b393577486b61353476685a6c2f5a4c6231427243752f686431746761736766434" +
"9566d4d34754335614774697a422b4a3335462f4f2b0a5344572b62585854314c634b4951795a625" +
"66772335537736c39584f5773322f55474a33653739555948473144656f497235367534475074312" +
"b5338746347500a464b36496e4e42534a56584a325231446b7a754e5843476d63766a4d7a4e426b7" +
"47034504d773d3d0a2d2d2d2d2d454e442043455254494649434154452d2d2d2d2d0a"
private const val CERT_2 = "2d2d2d2d2d424547494e2043455254494649434154452d2d2d2d2d0a4d494" +
"9422b4443434157476741774942416749554739426d31332f566c61747370564461486d46574f6c7" +
"65a696b45774451594a4b6f5a496876634e4151454c0a425141774454454c4d416b4741315545426" +
"84d4356564d774942634e4d6a41774f5449794d6a4d774d7a4130576867504d7a41794d4441784d6" +
"a51794d7a417a0a4d4452614d413078437a414a42674e5642415954416c56544d4947664d4130474" +
"35371475349623344514542415155414134474e4144434269514b42675144510a595875516f67783" +
"4324c77572b3568656b6f694c50507178655964494250555668743442584d6e494f7835434449665" +
"96d6461424650645865685546395036340a7974576a2b316963677452776e4c2f62487a525953413" +
"637514c39492b7a45456e2b7342777779566f51325858644c51546f49394f537a54444375744f4c4" +
"2430a6f65754f46727373566642676f4d6838685a4f5a31775448442f706c6b38543541384463313" +
"7505159774944415141426f314d775554416442674e56485134450a466751554c7a5754614673507" +
"23161526d304166556569704b346d6d75785977487759445652306a42426777466f41554c7a57546" +
"1467350723161526d3041660a556569704b346d6d7578597744775944565230544151482f4241557" +
"7417745422f7a414e42676b71686b6947397730424151734641414f42675141496147524d0a4d423" +
"74c74464957714847542f69766f56572b4f6a58664f477332554f75416455776d7a6b374b7a57727" +
"874744639616a355250307756637755625654444e740a464c326b4c3171574450513471613333643" +
"34744325555416b49474b724d514668523839756a303438514c7871386a72466f663447324572755" +
"85353354d79790a5669573735357038354f50704c635a753939796c2b536d7675633938685170796" +
"a6f564f6c773d3d0a2d2d2d2d2d454e442043455254494649434154452d2d2d2d2d0a"
private const val CERT_3 = "2d2d2d2d2d424547494e2043455254494649434154452d2d2d2d2d0a4d494" +
"9422b444343415747674177494241674955484f6f6d736b2b642f79336c4854434e3371675166413" +
"335646e51774451594a4b6f5a496876634e4151454c0a425141774454454c4d416b4741315545426" +
"84d4356564d774942634e4d6a41774f5449794d6a4d774d7a4578576867504d7a41794d4441784d6" +
"a51794d7a417a0a4d5446614d413078437a414a42674e5642415954416c56544d4947664d4130474" +
"35371475349623344514542415155414134474e4144434269514b42675144520a6355494b3450724" +
"d396930685834546168485055334c575665677630546668307273785153637042496a73306b6a6a6" +
"34e78342f31363948674c70476f5a334d0a63424350612f61574a4778794c7145514537774b77644" +
"a6148596b4b56706e55706a4d313030634b6b6b4a356565336b56414958746f2f6c436b626b554a6" +
"1730a47334f71307677774936656130707336684350313863693066727844766d6630536e2b54615" +
"2396a31774944415141426f314d775554416442674e56485134450a466751554464553443534c393" +
"746516d774954555332444e4472356b464c5177487759445652306a42426777466f4155446455344" +
"3534c393746516d774954550a5332444e4472356b464c517744775944565230544151482f4241557" +
"7417745422f7a414e42676b71686b6947397730424151734641414f426751437a567054470a59796" +
"1444a6c456279447775443457616b38306d5a4153613534646a69446e6335324d30776e614145776" +
"84e496978623547465a50357878337859302f494c520a6a72544a6e6744377643586c556f5256384" +
"379794653534169306f3977544b475554434d762b303446324a6c474a4b7665486a346d473544746" +
"6335331574b520a6644454a792b456376563658314b716a73466d524a4a6d7a30347464525363304" +
"c74622f2f673d3d0a2d2d2d2d2d454e442043455254494649434154452d2d2d2d2d0a"
private const val CERT_4 = "2d2d2d2d2d424547494e2043455254494649434154452d2d2d2d2d0a4d494" +
"9422b444343415747674177494241674955526f49427173485858413246636938324d412b73706d5" +
"6684d7634774451594a4b6f5a496876634e4151454c0a425141774454454c4d416b4741315545426" +
"84d4356564d774942634e4d6a41774f5449304d546b784d7a4d77576867504d7a41794d4441784d6" +
"a59784f54457a0a4d7a42614d413078437a414a42674e5642415954416c56544d4947664d4130474" +
"35371475349623344514542415155414134474e4144434269514b426751432b0a306549525344554" +
"e4972666663486f4d61697431705a6b39534769616c41694e56484b6e4950466876754233497a475" +
"05a4d476f6d6a3956534667766e7047360a4f7166453033734e575949503944776772485546692f6" +
"e356f45504f742f617643746b4b71623957737531777643746b37795163354d626276644e6b78344" +
"c740a3679724a7151545946424479356c49624c67454b4d744a5344584246356a38747173326e705" +
"145514f774944415141426f314d775554416442674e56485134450a4667515557354c6e5751344f3" +
"2523576515731355452564955726f744e476b77487759445652306a42426777466f415557354c6e5" +
"751344f32523576515731350a5452564955726f744e476b7744775944565230544151482f4241557" +
"7417745422f7a414e42676b71686b6947397730424151734641414f42675141685768654f0a77525" +
"85339365536444a705459597374754741634a77414e434d3244503938325653613136766e7769653" +
"842477a6a724a51794f354e4a4846637a4f566e54330a626834496a65337751787551334138566e4" +
"54d334230683553373030524c524337373936555a787465683874304f6c7a515031703358452b776" +
"571797a6c4e330a4f494f435a486f6b494b6f4957527964734e58547a55353448625850597275556" +
"e71574451673d3d0a2d2d2d2d2d454e442043455254494649434154452d2d2d2d2d0a"
private const val TEST_PKG_NAME = "com.example.app"
private val nullCerts: List<Certificate>? = null
private val emptyCerts = emptyList<Certificate>()
private val multiSignerCerts = listOf(CERT_1, CERT_3).map(::Certificate)
private val pastHistoryCerts = listOf(CERT_1, CERT_2, CERT_3).map(::Certificate)
private val noHistoryCerts = listOf(CERT_1).map(::Certificate)
private val extraCert = Certificate(CERT_4)
data class Params(
val sdkVersion: Int,
val mockCerts: MockCerts,
val queryType: QueryType,
val certType: CertType,
val matchExact: Boolean
) {
enum class CertType(val flag: Int) {
X509(PackageManager.CERT_INPUT_RAW_X509),
SHA256(PackageManager.CERT_INPUT_SHA256)
}
enum class QueryType { NONE, EXACT_COUNT, FEWER, MORE }
val queryCerts = when (queryType) {
QueryType.NONE -> emptyList()
QueryType.EXACT_COUNT -> mockCerts.certificates.orEmpty()
QueryType.FEWER -> mockCerts.certificates!!.drop(1)
QueryType.MORE -> mockCerts.certificates.orEmpty() + extraCert
}
val success = when (mockCerts.certificates) {
// If the certs returned in the packgae are null/empty, the query can never succeed
nullCerts, emptyCerts -> false
// Otherwise success depends on what the query set is
else -> when (queryType) {
// None always fails, to ensure verify cannot accidentally succeed
QueryType.NONE -> false
// If querying the exact same certs, then always succeed
QueryType.EXACT_COUNT -> true
// Otherwise if querying fewer, only succeed if not matching exactly all
QueryType.FEWER -> !matchExact
// Otherwise matching more than available, which should always fail
QueryType.MORE -> false
}
}
// For naming the test method variant
override fun toString(): String {
val certsVariant = when (mockCerts.certificates) {
nullCerts -> "null"
emptyCerts -> "empty"
multiSignerCerts -> "multiSign"
pastHistoryCerts -> "pastHistory"
noHistoryCerts -> "noHistory"
else -> throw IllegalArgumentException("Invalid mockCerts $mockCerts")
}
@Suppress("DEPRECATION")
val queryFlag = when (val flag = mockCerts.flag) {
PackageManager.GET_SIGNATURES -> "GET_SIGNATURES"
PackageManager.GET_SIGNING_CERTIFICATES -> "GET_SIGNING_CERTIFICATES"
else -> throw IllegalArgumentException("Invalid certs type $flag")
}
val sdkVersionName = sdkVersion.takeUnless { it == Build.VERSION.SDK_INT }
?: "current"
return "$queryFlag," +
"$certsVariant${certType.name}," +
"sdkVersion=$sdkVersionName," +
"query=$queryType," +
"matchExact=$matchExact"
}
}
@Suppress("DEPRECATION")
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun parameters(): Array<Params> {
return listOf(
listOf(
MockSignatures(nullCerts),
MockSignatures(emptyCerts),
MockSignatures(multiSignerCerts),
// Legacy GET_SIGNATURES cannot include certificate history
MockSignatures(noHistoryCerts)
).associateWith { Build.VERSION_CODES.O_MR1 },
listOf(
MockSigningInfo(
multiSigners = false,
hasHistory = null,
contentsSigners = null,
certHistory = null
),
MockSigningInfo(
multiSigners = false,
hasHistory = null,
contentsSigners = null,
certHistory = emptyCerts
),
MockSigningInfo(
multiSigners = true,
hasHistory = null,
contentsSigners = multiSignerCerts,
certHistory = null
),
MockSigningInfo(
multiSigners = false,
hasHistory = true,
contentsSigners = null,
certHistory = pastHistoryCerts
),
MockSigningInfo(
multiSigners = false,
hasHistory = false,
contentsSigners = null,
certHistory = noHistoryCerts
)
).associateWith { Build.VERSION.SDK_INT }
)
.flatMap {
// Multiply all base params by QueryType, CertType and matchExact values to
// get the complete set of possibilities
it.entries.flatMap { (mockCerts, sdkVersion) ->
listOfNotNull(
QueryType.NONE,
QueryType.EXACT_COUNT,
QueryType.MORE,
QueryType.FEWER.takeIf {
val certificates = mockCerts.certificates
!certificates.isNullOrEmpty() && certificates.size > 1
}
).flatMap { queryType ->
listOf(
Params.CertType.X509,
Params.CertType.SHA256
).flatMap { certType ->
listOf(true, false).map { matchExact ->
Params(sdkVersion, mockCerts, queryType, certType, matchExact)
}
}
}
}
}
.toTypedArray()
}
private val sdkIntField = Build.VERSION::class.java.getDeclaredField("SDK_INT")
private fun setDeviceSdkVersion(sdkVersion: Int) {
FieldSetter.setField(Build.VERSION::class.java, sdkIntField, sdkVersion)
assertThat(Build.VERSION.SDK_INT).isEqualTo(sdkVersion)
}
}
@Parameterized.Parameter(0)
lateinit var params: Params
private var savedSdkVersion: Int = Build.VERSION.SDK_INT
@Before
fun saveSdkVersion() {
savedSdkVersion = Build.VERSION.SDK_INT
}
@After
fun resetSdkVersion() {
if (Build.VERSION.SDK_INT != savedSdkVersion) {
setDeviceSdkVersion(savedSdkVersion)
}
}
@Test
fun verify() {
val mock = mockPackageManager()
val certs = params.queryCerts.map { it.bytes(params.certType) }
.associateWith { params.certType.flag }
// SDK_INT must be changed after mocks are built, since MockMaker will do an SDK check
if (Build.VERSION.SDK_INT != params.sdkVersion) {
setDeviceSdkVersion(params.sdkVersion)
}
assertThat(PackageInfoCompat.hasSignatures(mock, TEST_PKG_NAME, certs, params.matchExact))
.isEqualTo(params.success)
if (Build.VERSION.SDK_INT != savedSdkVersion) {
setDeviceSdkVersion(savedSdkVersion)
}
}
@Suppress("DEPRECATION")
private fun mockPackageManager() = mockThrowOnUnmocked<PackageManager> {
val mockCerts = params.mockCerts
whenever(getPackageInfo(TEST_PKG_NAME, params.mockCerts.flag)) {
PackageInfo().apply {
when (mockCerts) {
is MockSignatures -> {
@Suppress("DEPRECATION")
signatures = mockCerts.certificates?.map { it.signature }?.toTypedArray()
}
is MockSigningInfo -> {
signingInfo = mockThrowOnUnmocked<SigningInfo> {
whenever(hasMultipleSigners()) { mockCerts.multiSigners }
mockCerts.hasHistory?.let {
// Only allow this method if params specify it. to ensure past
// certificates aren't considered when multi-signing is enabled
whenever(hasPastSigningCertificates()) { it }
}
mockCerts.contentsSigners
?.map { it.signature }
?.toTypedArray()
?.let { whenever(apkContentsSigners) { it } }
// Only allow fetching history if not multi signed
if (!hasMultipleSigners()) {
whenever(signingCertificateHistory) {
mockCerts.certHistory
?.map { it.signature }
?.toTypedArray()
}
}
}
}
}
}
}
if (!params.matchExact && params.sdkVersion >= Build.VERSION_CODES.P) {
whenever(hasSigningCertificate(eq(TEST_PKG_NAME), any(), anyInt())) {
val certs = params.mockCerts.certificates?.asSequence() ?: return@whenever false
val query = getArgument(1) as ByteArray
val certType = when (val type = getArgument(2) as Int) {
PackageManager.CERT_INPUT_RAW_X509 -> Params.CertType.X509
PackageManager.CERT_INPUT_SHA256 -> Params.CertType.SHA256
else -> throw IllegalArgumentException("Invalid type $type")
}
certs.map { it.bytes(certType) }.contains(query)
}
}
}
sealed class MockCerts {
abstract val certificates: List<Certificate>?
abstract val flag: Int
data class MockSignatures(override val certificates: List<Certificate>?) : MockCerts() {
@Suppress("DEPRECATION")
override val flag = PackageManager.GET_SIGNATURES
}
data class MockSigningInfo(
val multiSigners: Boolean,
val hasHistory: Boolean?,
val contentsSigners: List<Certificate>?,
val certHistory: List<Certificate>?
) : MockCerts() {
override val certificates = contentsSigners ?: certHistory
override val flag = PackageManager.GET_SIGNING_CERTIFICATES
}
}
/**
* [Signature] wrapper to cache arrays and digests.
*/
data class Certificate(val publicCertX509: String) {
val signature = Signature(publicCertX509)
private val x509Bytes = signature.toByteArray()!!
private val sha256Bytes = MessageDigest.getInstance("SHA256").digest(x509Bytes)
fun bytes(certType: Params.CertType): ByteArray = when (certType) {
Params.CertType.X509 -> x509Bytes
Params.CertType.SHA256 -> sha256Bytes
}
}
} | apache-2.0 | cc06c0853b0270b626bbd2079570ad58 | 50.609005 | 100 | 0.647534 | 3.545751 | false | true | false | false |
androidx/androidx | health/connect/connect-client/src/test/java/androidx/health/connect/client/impl/converters/aggregate/AggregationResultConverterTest.kt | 3 | 7767 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client.impl.converters.aggregate
import androidx.health.connect.client.aggregate.AggregationResult
import androidx.health.connect.client.aggregate.AggregationResultGroupedByDuration
import androidx.health.connect.client.aggregate.AggregationResultGroupedByPeriod
import androidx.health.connect.client.records.metadata.DataOrigin
import androidx.health.platform.client.proto.DataProto
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneOffset
import org.junit.Assert.assertThrows
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AggregationResultConverterTest {
@Test
fun retrieveAggregateDataRow() {
val proto =
DataProto.AggregateDataRow.newBuilder()
.addDataOrigins(DataProto.DataOrigin.newBuilder().setApplicationId("testApp"))
.putDoubleValues("doubleKey", 123.4)
.putLongValues("longKey", 567)
.build()
proto
.retrieveAggregateDataRow()
.assertEquals(
AggregationResult(
longValues = mapOf(Pair("longKey", 567L)),
doubleValues = mapOf(Pair("doubleKey", 123.4)),
dataOrigins = setOf(DataOrigin("testApp")),
)
)
}
// ZoneOffset.ofTotalSeconds() has been banned but safe here for serialization.
@SuppressWarnings("GoodTime")
@Test
fun toAggregateDataRowGroupByDuration() {
val proto =
DataProto.AggregateDataRow.newBuilder()
.addDataOrigins(DataProto.DataOrigin.newBuilder().setApplicationId("testApp"))
.putDoubleValues("doubleKey", 123.4)
.putLongValues("longKey", 567)
.setStartTimeEpochMs(1111)
.setEndTimeEpochMs(9999)
.setZoneOffsetSeconds(123)
.build()
proto
.toAggregateDataRowGroupByDuration()
.assertEquals(
AggregationResultGroupedByDuration(
result =
AggregationResult(
longValues = mapOf(Pair("longKey", 567L)),
doubleValues = mapOf(Pair("doubleKey", 123.4)),
dataOrigins = setOf(DataOrigin("testApp")),
),
startTime = Instant.ofEpochMilli(1111),
endTime = Instant.ofEpochMilli(9999),
zoneOffset = ZoneOffset.ofTotalSeconds(123),
)
)
}
@Test
fun toAggregateDataRowGroupByDuration_startOrEndTimeNotSet_throws() {
val proto =
DataProto.AggregateDataRow.newBuilder()
.addDataOrigins(DataProto.DataOrigin.newBuilder().setApplicationId("testApp"))
.putDoubleValues("doubleKey", 123.4)
.putLongValues("longKey", 567)
.setStartTimeEpochMs(1111)
.setEndTimeEpochMs(9999)
.setZoneOffsetSeconds(123)
.build()
var thrown =
assertThrows(IllegalArgumentException::class.java) {
proto
.toBuilder()
.clearStartTimeEpochMs()
.build()
.toAggregateDataRowGroupByDuration()
}
assertThat(thrown.message).isEqualTo("start time must be set")
thrown =
assertThrows(IllegalArgumentException::class.java) {
proto.toBuilder().clearEndTimeEpochMs().build().toAggregateDataRowGroupByDuration()
}
assertThat(thrown.message).isEqualTo("end time must be set")
}
@Test
fun toAggregateDataRowGroupByPeriod() {
val proto =
DataProto.AggregateDataRow.newBuilder()
.addDataOrigins(DataProto.DataOrigin.newBuilder().setApplicationId("testApp"))
.putDoubleValues("doubleKey", 123.4)
.putLongValues("longKey", 567)
.setStartLocalDateTime("2022-02-11T20:22:02")
.setEndLocalDateTime("2022-02-22T20:22:02")
.build()
proto
.toAggregateDataRowGroupByPeriod()
.assertEquals(
AggregationResultGroupedByPeriod(
result =
AggregationResult(
longValues = mapOf(Pair("longKey", 567L)),
doubleValues = mapOf(Pair("doubleKey", 123.4)),
dataOrigins = setOf(DataOrigin("testApp")),
),
startTime = LocalDateTime.parse("2022-02-11T20:22:02"),
endTime = LocalDateTime.parse("2022-02-22T20:22:02"),
)
)
}
@Test
fun toAggregateDataRowGroupByPeriod_startOrEndTimeNotSet_throws() {
val proto =
DataProto.AggregateDataRow.newBuilder()
.addDataOrigins(DataProto.DataOrigin.newBuilder().setApplicationId("testApp"))
.putDoubleValues("doubleKey", 123.4)
.putLongValues("longKey", 567)
.setStartLocalDateTime("2022-02-11T20:22:02")
.setEndLocalDateTime("2022-02-12T20:22:02")
.build()
var thrown =
assertThrows(IllegalArgumentException::class.java) {
proto
.toBuilder()
.clearStartLocalDateTime()
.build()
.toAggregateDataRowGroupByPeriod()
}
assertThat(thrown.message).isEqualTo("start time must be set")
thrown =
assertThrows(IllegalArgumentException::class.java) {
proto.toBuilder().clearEndLocalDateTime().build().toAggregateDataRowGroupByPeriod()
}
assertThat(thrown.message).isEqualTo("end time must be set")
}
private fun AggregationResult.assertEquals(expected: AggregationResult) {
assertThat(longValues).isEqualTo(expected.longValues)
assertThat(doubleValues).isEqualTo(expected.doubleValues)
assertThat(dataOrigins).isEqualTo(expected.dataOrigins)
}
// ZoneOffset.ofTotalSeconds() has been banned but safe here for serialization.
@SuppressWarnings("GoodTime")
private fun AggregationResultGroupedByDuration.assertEquals(
expected: AggregationResultGroupedByDuration,
) {
result.assertEquals(expected.result)
assertThat(startTime).isEqualTo(expected.startTime)
assertThat(endTime).isEqualTo(expected.endTime)
assertThat(zoneOffset).isEqualTo(expected.zoneOffset)
}
private fun AggregationResultGroupedByPeriod.assertEquals(
expected: AggregationResultGroupedByPeriod,
) {
result.assertEquals(expected.result)
assertThat(startTime).isEqualTo(expected.startTime)
assertThat(endTime).isEqualTo(expected.endTime)
}
}
| apache-2.0 | 42532b0b6829874d6f63a26a955def52 | 39.664921 | 99 | 0.61272 | 5.106509 | false | true | false | false |
androidx/androidx | compose/ui/ui/samples/src/main/java/androidx/compose/ui/samples/FocusAwareInputSamples.kt | 3 | 9761 | /*
* 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.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.material.darkColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType.Companion.KeyDown
import androidx.compose.ui.input.key.KeyEventType.Companion.KeyUp
import androidx.compose.ui.input.key.KeyEventType.Companion.Unknown
import androidx.compose.ui.input.key.isAltPressed
import androidx.compose.ui.input.key.isCtrlPressed
import androidx.compose.ui.input.key.isMetaPressed
import androidx.compose.ui.input.key.isShiftPressed
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.input.rotary.onPreRotaryScrollEvent
import androidx.compose.ui.input.rotary.onRotaryScrollEvent
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
import kotlinx.coroutines.launch
@Suppress("UNUSED_ANONYMOUS_PARAMETER")
@Sampled
@Composable
fun KeyEventSample() {
// When the inner Box is focused, and the user presses a key, the key goes down the hierarchy
// and then back up to the parent. At any stage you can stop the propagation by returning
// true to indicate that you consumed the event.
Box(
Modifier
.onPreviewKeyEvent { keyEvent1 -> false }
.onKeyEvent { keyEvent4 -> false }
) {
Box(
Modifier
.onPreviewKeyEvent { keyEvent2 -> false }
.onKeyEvent { keyEvent3 -> false }
.focusable()
)
}
}
@Sampled
@Composable
fun KeyEventTypeSample() {
Box(
Modifier
.onKeyEvent {
when (it.type) {
KeyUp -> println(" KeyUp Pressed")
KeyDown -> println(" KeyUp Pressed")
Unknown -> println("Unknown key type")
else -> println("New KeyTpe (For Future Use)")
}
false
}
.focusable()
)
}
@ExperimentalComposeUiApi
@Sampled
@Composable
fun KeyEventIsAltPressedSample() {
Box(
Modifier
.onKeyEvent {
if (it.isAltPressed && it.key == Key.A) {
println("Alt + A is pressed")
true
} else {
false
}
}
.focusable()
)
}
@ExperimentalComposeUiApi
@Sampled
@Composable
fun KeyEventIsCtrlPressedSample() {
Box(
Modifier
.onKeyEvent {
if (it.isCtrlPressed && it.key == Key.A) {
println("Ctrl + A is pressed")
true
} else {
false
}
}
.focusable()
)
}
@ExperimentalComposeUiApi
@Sampled
@Composable
fun KeyEventIsMetaPressedSample() {
Box(
Modifier
.onKeyEvent {
if (it.isMetaPressed && it.key == Key.A) {
println("Meta + A is pressed")
true
} else {
false
}
}
.focusable()
)
}
@ExperimentalComposeUiApi
@Sampled
@Composable
fun KeyEventIsShiftPressedSample() {
Box(
Modifier
.onKeyEvent {
if (it.isShiftPressed && it.key == Key.A) {
println("Shift + A is pressed")
true
} else {
false
}
}
.focusable()
)
}
@OptIn(ExperimentalComposeUiApi::class)
@Sampled
@Composable
fun RotaryEventSample() {
val scrollState = rememberScrollState()
val coroutineScope = rememberCoroutineScope()
val focusRequester = remember { FocusRequester() }
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(scrollState)
.onRotaryScrollEvent {
coroutineScope.launch {
scrollState.scrollTo((scrollState.value +
it.verticalScrollPixels).roundToInt())
}
true
}
.focusRequester(focusRequester)
.focusable(),
) {
repeat(100) {
Text(
text = "item $it",
modifier = Modifier.align(CenterHorizontally),
color = White,
)
}
}
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
@OptIn(ExperimentalComposeUiApi::class)
@Sampled
@Composable
fun PreRotaryEventSample() {
MaterialTheme(colors = darkColors()) {
val rowScrollState = rememberScrollState()
val columnScrollState = rememberScrollState()
val coroutineScope = rememberCoroutineScope()
val focusRequester = remember { FocusRequester() }
var interceptScroll by remember { mutableStateOf(false) }
Column(
Modifier
.onPreRotaryScrollEvent {
// You can intercept an event before it is sent to the child.
if (interceptScroll) {
coroutineScope.launch {
rowScrollState.scrollBy(it.horizontalScrollPixels)
}
// return true to consume this event.
true
} else {
// return false to ignore this event and continue propagation to the child.
false
}
}
.onRotaryScrollEvent {
// If the child does not use the scroll, we get notified here.
coroutineScope.launch {
rowScrollState.scrollBy(it.horizontalScrollPixels)
}
true
}
) {
Row(
modifier = Modifier.align(CenterHorizontally),
verticalAlignment = CenterVertically
) {
Text(
modifier = Modifier.width(70.dp),
text = if (interceptScroll) "Row" else "Column",
style = TextStyle(color = White)
)
Switch(
checked = interceptScroll,
onCheckedChange = { interceptScroll = it },
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.horizontalScroll(rowScrollState)
) {
repeat(100) {
Text(
text = "row item $it ",
modifier = Modifier.align(CenterVertically),
color = White,
)
}
}
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(columnScrollState)
.onRotaryScrollEvent {
coroutineScope.launch {
columnScrollState.scrollBy(it.verticalScrollPixels)
}
true
}
.focusRequester(focusRequester)
.focusable(),
) {
repeat(100) {
Text(
text = "column item $it",
modifier = Modifier.align(CenterHorizontally),
color = White,
)
}
}
}
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
}
| apache-2.0 | c182b123ebe67eba0fb939cebaa404d3 | 31.536667 | 99 | 0.572585 | 5.284786 | false | false | false | false |
chemickypes/Glitchy | app/src/main/java/me/bemind/glitchlibrary/Components.kt | 1 | 3023 | package me.bemind.glitchlibrary
import android.content.Context
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Parcel
import android.os.Parcelable
import android.text.TextPaint
import android.text.style.TypefaceSpan
import android.util.AttributeSet
import android.widget.TextView
/**
* Created by angelomoroni on 04/05/17.
*/
enum class TYPEFONT {
BOLD,REGULAR,LIGHT,MONO
}
class GlitcyTypefaceSpan(family:String,val typeface:Typeface) : TypefaceSpan(family){
override fun updateDrawState(ds: TextPaint?) {
applyCustomTypeFace(ds,typeface)
}
override fun updateMeasureState(paint: TextPaint?) {
applyCustomTypeFace(paint,typeface)
}
private fun applyCustomTypeFace(ds: TextPaint?, typeface: Typeface) {
val oldstyle = when(ds?.typeface){
null -> 0
else -> ds.typeface.style
}
val fake = oldstyle and typeface.style.inv()
if((fake and Typeface.BOLD)!=0){
ds?.isFakeBoldText = true
}
if((fake and Typeface.ITALIC)!=0){
ds?.textSkewX = (-0.25f)
}
ds?.typeface = typeface
}
}
object GlitchyTypeFaceGetter {
/* val BOLD = "Montserrat-Bold.otf"
val REGULAR = "Montserrat-Regular.otf"
val LIGHT = "Montserrat-Light.otf"*/
val BOLD = "apercu-bold-webfont.ttf"
val REGULAR = "apercu-regular-webfont.ttf"
val LIGHT = "apercu-light-webfont.ttf"
val MONO = "apercu-mono-webfont.ttf"
fun getTypeFace(context:Context, typefont: TYPEFONT = TYPEFONT.REGULAR) : Typeface{
return Typeface.createFromAsset(context.assets,
when(typefont){
TYPEFONT.LIGHT -> LIGHT
TYPEFONT.BOLD -> BOLD
TYPEFONT.MONO -> MONO
else -> REGULAR
})
}
}
interface CustomFontText {
fun customizeTypeFace(context: Context,typefont: TYPEFONT,action : (Typeface) -> Unit){
action(GlitchyTypeFaceGetter.getTypeFace(context,typefont))
}
}
class GlithcyTextView : TextView,CustomFontText{
constructor(context: Context) : super(context){
initView()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs){
initView(attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr){
initView(attrs)
}
private fun initView(attrs: AttributeSet? = null) {
if(isInEditMode || attrs == null) return
//attrs is not null
val a = context.obtainStyledAttributes(attrs,R.styleable.GlithcyTextView)
val tyEnum = a.getInteger(R.styleable.GlithcyTextView_glitchyTypeface,0)
val ty = when(tyEnum){
0 -> TYPEFONT.REGULAR
1 -> TYPEFONT.BOLD
2 -> TYPEFONT.LIGHT
3 -> TYPEFONT.MONO
else -> TYPEFONT.REGULAR
}
customizeTypeFace(context,ty, this::setTypeface)
}
}
| apache-2.0 | 5a7f84fbc21c816af499a4d6b1fcb8f2 | 25.991071 | 112 | 0.639431 | 3.988127 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/harmony_regex/PatternTest2.kt | 4 | 44938 | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test.text.harmony_regex
import kotlin.text.*
import kotlin.test.*
class PatternTest2 {
fun assertTrue(msg: String, value: Boolean) = assertTrue(value, msg)
fun assertFalse(msg: String, value: Boolean) = assertFalse(value, msg)
/**
* Tests simple pattern compilation and matching methods
*/
@Test fun testSimpleMatch() {
val regex = Regex("foo.*")
var testString = "foo123"
assertTrue(regex.matches(testString))
assertTrue(regex in testString)
assertTrue(regex.find(testString) != null)
testString = "fox"
assertFalse(regex.matches(testString))
assertFalse(regex in testString)
assertFalse(regex.find(testString) != null)
assertTrue(Regex("foo.*").matches("foo123"))
assertFalse(Regex("foo.*").matches("fox"))
assertFalse(Regex("bar").matches("foobar"))
assertTrue(Regex("").matches(""))
}
@Test fun testCursors() {
val regex: Regex
var result: MatchResult?
try {
regex = Regex("foo")
result = regex.find("foobar")
assertNotNull(result)
assertEquals(0, result!!.range.start)
assertEquals(3, result.range.endInclusive + 1)
assertNull(result.next())
result = regex.find("barfoobar")
assertNotNull(result)
assertEquals(3, result!!.range.start)
assertEquals(6, result.range.endInclusive + 1)
assertNull(result.next())
result = regex.find("barfoo")
assertNotNull(result)
assertEquals(3, result!!.range.start)
assertEquals(6, result.range.endInclusive + 1)
assertNull(result.next())
result = regex.find("foobarfoobarfoo")
assertNotNull(result)
assertEquals(0, result!!.range.start)
assertEquals(3, result.range.endInclusive + 1)
result = result.next()
assertNotNull(result)
assertEquals(6, result!!.range.start)
assertEquals(9, result.range.endInclusive + 1)
result = result.next()
assertNotNull(result)
assertEquals(12, result!!.range.start)
assertEquals(15, result.range.endInclusive + 1)
assertNull(result.next())
result = regex.find("foobarfoobarfoo", 0)
assertNotNull(result)
assertEquals(0, result!!.range.start)
assertEquals(3, result.range.endInclusive + 1)
result = regex.find("foobarfoobarfoo", 4)
assertNotNull(result)
assertEquals(6, result!!.range.start)
assertEquals(9, result.range.endInclusive + 1)
} catch (e: IllegalArgumentException) {
println(e.message)
fail()
}
}
@Test fun testGroups() {
val regex: Regex
var result: MatchResult?
regex = Regex("(p[0-9]*)#?(q[0-9]*)")
result = regex.find("p1#q3p2q42p5p71p63#q888")
assertNotNull(result)
assertEquals(0, result!!.range.start)
assertEquals(5, result.range.endInclusive + 1)
assertEquals(3, result.groups.size)
assertEquals(0, result.groups[0]!!.range.start)
assertEquals(5, result.groups[0]!!.range.endInclusive + 1)
assertEquals(0, result.groups[1]!!.range.start)
assertEquals(2, result.groups[1]!!.range.endInclusive + 1)
assertEquals(3, result.groups[2]!!.range.start)
assertEquals(5, result.groups[2]!!.range.endInclusive + 1)
assertEquals("p1#q3", result.value)
assertEquals("p1#q3", result.groupValues[0])
assertEquals("p1", result.groupValues[1])
assertEquals("q3", result.groupValues[2])
result = result.next()
assertNotNull(result)
assertEquals(5, result!!.range.start)
assertEquals(10, result.range.endInclusive + 1)
assertEquals(3, result.groups.size)
assertEquals(10, result.groups[0]!!.range.endInclusive + 1)
assertEquals(5, result.groups[1]!!.range.start)
assertEquals(7, result.groups[1]!!.range.endInclusive + 1)
assertEquals(7, result.groups[2]!!.range.start)
assertEquals(10, result.groups[2]!!.range.endInclusive + 1)
assertEquals("p2q42", result.value)
assertEquals("p2q42", result.groupValues[0])
assertEquals("p2", result.groupValues[1])
assertEquals("q42", result.groupValues[2])
result = result.next()
assertNotNull(result)
assertEquals(15, result!!.range.start)
assertEquals(23, result.range.endInclusive + 1)
assertEquals(3, result.groups.size)
assertEquals(15, result.groups[0]!!.range.start)
assertEquals(23, result.groups[0]!!.range.endInclusive + 1)
assertEquals(15, result.groups[1]!!.range.start)
assertEquals(18, result.groups[1]!!.range.endInclusive + 1)
assertEquals(19, result.groups[2]!!.range.start)
assertEquals(23, result.groups[2]!!.range.endInclusive + 1)
assertEquals("p63#q888", result.value)
assertEquals("p63#q888", result.groupValues[0])
assertEquals("p63", result.groupValues[1])
assertEquals("q888", result.groupValues[2])
assertNull(result.next())
}
@Test fun testReplace() {
var regex: Regex
// Note: examples from book,
// Hitchens, Ron, 2002, "Java NIO", O'Reilly, page 171
regex = Regex("a*b")
var testString = "aabfooaabfooabfoob"
assertTrue(regex.replace(testString, "-") == "-foo-foo-foo-")
assertTrue(regex.replaceFirst(testString, "-") == "-fooaabfooabfoob")
regex = Regex("([bB])yte")
testString = "Byte for byte"
assertTrue(regex.replaceFirst(testString, "$1ite") == "Bite for byte")
assertTrue(regex.replace(testString, "$1ite") == "Bite for bite")
regex = Regex("\\d\\d\\d\\d([- ])")
testString = "card #1234-5678-1234"
assertTrue(regex.replaceFirst(testString, "xxxx$1") == "card #xxxx-5678-1234")
assertTrue(regex.replace(testString, "xxxx$1") == "card #xxxx-xxxx-1234")
regex = Regex("(up|left)( *)(right|down)")
testString = "left right, up down"
assertTrue(regex.replaceFirst(testString, "$3$2$1") == "right left, up down")
assertTrue(regex.replace(testString, "$3$2$1") == "right left, down up")
regex = Regex("([CcPp][hl]e[ea]se)")
testString = "I want cheese. Please."
assertTrue(regex.replaceFirst(testString, "<b> $1 </b>") == "I want <b> cheese </b>. Please.")
assertTrue(regex.replace(testString, "<b> $1 </b>") == "I want <b> cheese </b>. <b> Please </b>.")
}
@Test fun testEscapes() {
var regex: Regex
var result: MatchResult?
// Test \\ sequence
regex = Regex("([a-z]+)\\\\([a-z]+);")
result = regex.find("fred\\ginger;abbott\\costello;jekell\\hyde;")
assertNotNull(result)
assertEquals("fred", result!!.groupValues[1])
assertEquals("ginger", result.groupValues[2])
result = result.next()
assertNotNull(result)
assertEquals("abbott", result!!.groupValues[1])
assertEquals("costello", result.groupValues[2])
result = result.next()
assertNotNull(result)
assertEquals("jekell", result!!.groupValues[1])
assertEquals("hyde", result.groupValues[2])
assertNull(result.next())
// Test \n, \t, \r, \f, \e, \a sequences
regex = Regex("([a-z]+)[\\n\\t\\r\\f\\e\\a]+([a-z]+)")
result = regex.find("aa\nbb;cc\u0009\rdd;ee\u000C\u001Bff;gg\n\u0007hh")
assertNotNull(result)
assertEquals("aa", result!!.groupValues[1])
assertEquals("bb", result.groupValues[2])
result = result.next()
assertNotNull(result)
assertEquals("cc", result!!.groupValues[1])
assertEquals("dd", result.groupValues[2])
result = result.next()
assertNotNull(result)
assertEquals("ee", result!!.groupValues[1])
assertEquals("ff", result.groupValues[2])
result = result.next()
assertNotNull(result)
assertEquals("gg", result!!.groupValues[1])
assertEquals("hh", result.groupValues[2])
assertNull(result.next())
// Test \\u and \\x sequences
regex = Regex("([0-9]+)[\\u0020:\\x21];")
result = regex.find("11:;22 ;33-;44!;")
assertNotNull(result)
assertEquals("11", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("22", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("44", result!!.groupValues[1])
assertNull(result.next())
// Test invalid unicode sequences // TODO: Double check it.
try {
regex = Regex("\\u")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\u;")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\u002")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\u002;")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
// Test invalid hex sequences
try {
regex = Regex("\\x")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\x;")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\xa")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\xa;")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
// Test \0 (octal) sequences (1, 2 and 3 digit)
regex = Regex("([0-9]+)[\\07\\040\\0160];")
result = regex.find("11\u0007;22:;33 ;44p;")
assertNotNull(result)
assertEquals("11", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("33", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("44", result!!.groupValues[1])
assertNull(result.next())
// Test invalid octal sequences
try {
regex = Regex("\\08")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\0")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\0;")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
// Test \c (control character) sequence
regex = Regex("([0-9]+)[\\cA\\cB\\cC\\cD];")
result = regex.find("11\u0001;22:;33\u0002;44p;55\u0003;66\u0004;")
assertNotNull(result)
assertEquals("11", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("33", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("55", result!!.groupValues[1])
result = result.next()
assertNotNull(result)
assertEquals("66", result!!.groupValues[1])
assertNull(result.next())
// More thorough control escape test
// Ensure that each escape matches exactly the corresponding
// character
// code and no others (well, from 0-255 at least)
for (i in 0..25) {
regex = Regex("\\c${'A' + i}")
var match_char = -1
for (j in 0..255) {
if (regex.matches("${j.toChar()}")) {
assertEquals(-1, match_char)
match_char = j
}
}
assertTrue(match_char == i + 1)
}
// Test invalid control escapes
try {
regex = Regex("\\c")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
}
@Test fun testCharacterClasses() {
var regex: Regex
// Test one character range
regex = Regex("[p].*[l]")
assertTrue(regex.matches("paul"))
assertTrue(regex.matches("pool"))
assertFalse(regex.matches("pong"))
assertTrue(regex.matches("pl"))
// Test two character range
regex = Regex("[pm].*[lp]")
assertTrue(regex.matches("prop"))
assertTrue(regex.matches("mall"))
assertFalse(regex.matches("pong"))
assertTrue(regex.matches("pill"))
// Test range including [ and ]
regex = Regex("[<\\[].*[\\]>]")
assertTrue(regex.matches("<foo>"))
assertTrue(regex.matches("[bar]"))
assertFalse(regex.matches("{foobar]"))
assertTrue(regex.matches("<pill]"))
// Test range using ^
regex = Regex("[^bc][a-z]+[tr]")
assertTrue(regex.matches("pat"))
assertTrue(regex.matches("liar"))
assertFalse(regex.matches("car"))
assertTrue(regex.matches("gnat"))
// Test character range using -
regex = Regex("[a-z]_+[a-zA-Z]-+[0-9p-z]")
assertTrue(regex.matches("d__F-8"))
assertTrue(regex.matches("c_a-q"))
assertFalse(regex.matches("a__R-a"))
assertTrue(regex.matches("r_____d-----5"))
// Test range using unicode characters and unicode and hex escapes
regex = Regex("[\\u1234-\\u2345]_+[a-z]-+[\u0001-\\x11]")
assertTrue(regex.matches("\u2000_q-\u0007"))
assertTrue(regex.matches("\u1234_z-\u0001"))
assertFalse(regex.matches("r_p-q"))
assertTrue(regex.matches("\u2345_____d-----\n"))
// Test ranges including the "-" character
regex = Regex("[\\*-/]_+[---]!+[--AP]")
assertTrue(regex.matches("-_-!!A"))
assertTrue(regex.matches("\u002b_-!!!-"))
assertFalse(regex.matches("!_-!@"))
assertTrue(regex.matches(",______-!!!!!!!P"))
// Test nested ranges
regex = Regex("[pm[t]][a-z]+[[r]lp]")
assertTrue(regex.matches("prop"))
assertTrue(regex.matches("tsar"))
assertFalse(regex.matches("pong"))
assertTrue(regex.matches("moor"))
// Test character class intersection with &&
// TODO: figure out what x&&y or any class with a null intersection
// set (like [[a-c]&&[d-f]]) might mean. It doesn't mean "match
// nothing" and doesn't mean "match anything" so I'm stumped.
regex = Regex("[[a-p]&&[g-z]]+-+[[a-z]&&q]-+[x&&[a-z]]-+")
assertTrue(regex.matches("h--q--x--"))
assertTrue(regex.matches("hog--q-x-"))
assertFalse(regex.matches("ape--q-x-"))
assertTrue(regex.matches("mop--q-x----"))
// Test error cases with &&
// TODO: What is this check?
regex = Regex("[&&[xyz]]")
regex.matches("&")
regex.matches("x")
regex.matches("y")
regex = Regex("[[xyz]&[axy]]")
regex.matches("x")
regex.matches("z")
regex.matches("&")
regex = Regex("[abc[123]&&[345]def]")
regex.matches("a")
regex = Regex("[[xyz]&&]")
regex = Regex("[[abc]&]")
try {
regex = Regex("[[abc]&&")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
regex = Regex("[[abc]\\&&[xyz]]")
regex = Regex("[[abc]&\\&[xyz]]")
// Test 3-way intersection
regex = Regex("[[a-p]&&[g-z]&&[d-k]]")
assertTrue(regex.matches("g"))
assertFalse(regex.matches("m"))
// Test nested intersection
regex = Regex("[[[a-p]&&[g-z]]&&[d-k]]")
assertTrue(regex.matches("g"))
assertFalse(regex.matches("m"))
// Test character class subtraction with && and ^
regex = Regex("[[a-z]&&[^aeiou]][aeiou][[^xyz]&&[a-z]]")
assertTrue(regex.matches("pop"))
assertTrue(regex.matches("tag"))
assertFalse(regex.matches("eat"))
assertFalse(regex.matches("tax"))
assertTrue(regex.matches("zip"))
// Test . (DOT), with and without DOTALL
// Note: DOT not allowed in character classes
regex = Regex(".+/x.z")
assertTrue(regex.matches("!$/xyz"))
assertFalse(regex.matches("%\n\r/x\nz"))
regex = Regex(".+/x.z", RegexOption.DOT_MATCHES_ALL)
assertTrue(regex.matches("%\n\r/x\nz"))
// Test \d (digit)
regex = Regex("\\d+[a-z][\\dx]")
assertTrue(regex.matches("42a6"))
assertTrue(regex.matches("21zx"))
assertFalse(regex.matches("ab6"))
assertTrue(regex.matches("56912f9"))
// Test \D (not a digit)
regex = Regex("\\D+[a-z]-[\\D3]")
assertTrue(regex.matches("za-p"))
assertTrue(regex.matches("%!e-3"))
assertFalse(regex.matches("9a-x"))
assertTrue(regex.matches("\u1234pp\ny-3"))
// Test \s (whitespace)
regex = Regex("<[a-zA-Z]+\\s+[0-9]+[\\sx][^\\s]>")
assertTrue(regex.matches("<cat \t1 x>"))
assertFalse(regex.matches("<cat \t1 >"))
val result = regex.find("xyz <foo\n\r22 5> <pp \t\n \r \u000b41x\u1234><pp \nx7\rc> zzz")
assertNotNull(result)
assertNotNull(result!!.next())
assertNull(result.next()!!.next())
// Test \S (not whitespace) // TODO: We've removed \f from string since kotlin doesn't recognize this escape in a string.
regex = Regex("<[a-z] \\S[0-9][\\S\n]+[^\\S]221>")
assertTrue(regex.matches("<f $0**\n** 221>"))
assertTrue(regex.matches("<x 441\t221>"))
assertFalse(regex.matches("<z \t9\ng 221>"))
assertTrue(regex.matches("<z 60\ngg\u1234 221>"))
regex = Regex("<[a-z] \\S[0-9][\\S\n]+[^\\S]221[\\S&&[^abc]]>")
assertTrue(regex.matches("<f $0**\n** 221x>"))
assertTrue(regex.matches("<x 441\t221z>"))
assertFalse(regex.matches("<x 441\t221 >"))
assertFalse(regex.matches("<x 441\t221c>"))
assertFalse(regex.matches("<z \t9\ng 221x>"))
assertTrue(regex.matches("<z 60\ngg\u1234 221\u0001>"))
// Test \w (ascii word)
regex = Regex("<\\w+\\s[0-9]+;[^\\w]\\w+/[\\w$]+;")
assertTrue(regex.matches("<f1 99;!foo5/a$7;"))
assertFalse(regex.matches("<f$ 99;!foo5/a$7;"))
assertTrue(regex.matches("<abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789 99;!foo5/a$7;"))
// Test \W (not an ascii word)
regex = Regex("<\\W\\w+\\s[0-9]+;[\\W_][^\\W]+\\s[0-9]+;")
assertTrue(regex.matches("<\$foo3\n99;_bar\t0;"))
assertFalse(regex.matches("<hh 99;_g 0;"))
assertTrue(regex.matches("<*xx\t00;^zz 11;"))
// Test x|y pattern
// TODO
}
@Test fun testPOSIXGroups() {
var regex: Regex
// Test POSIX groups using \p and \P (in the group and not in the group)
// Groups are Lower, Upper, ASCII, Alpha, Digit, XDigit, Alnum, Punct,
// Graph, Print, Blank, Space, Cntrl
// Test \p{Lower}
/*
* FIXME: Requires complex range processing p = Regex("<\\p{Lower}\\d\\P{Lower}:[\\p{Lower}Z]\\s[^\\P{Lower}]>");
* m = p.matcher("<a4P:g x>"); assertTrue(m.matches()); m = p.matcher("<p4%:Z\tq>");
* assertTrue(m.matches()); m = p.matcher("<A6#:e e>");
* assertFalse(m.matches());
*/
regex = Regex("\\p{Lower}+")
assertTrue(regex.matches("abcdefghijklmnopqrstuvwxyz"))
// Invalid uses of \p{Lower}
try {
regex = Regex("\\p")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\p;")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\p{")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\p{;")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\p{Lower")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\p{Lower;")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
// Test \p{Upper}
/*
* FIXME: Requires complex range processing p = Regex("<\\p{Upper}\\d\\P{Upper}:[\\p{Upper}z]\\s[^\\P{Upper}]>");
* m = p.matcher("<A4p:G X>"); assertTrue(m.matches()); m = p.matcher("<P4%:z\tQ>");
* assertTrue(m.matches()); m = p.matcher("<a6#:E E>");
* assertFalse(m.matches());
*/
regex = Regex("\\p{Upper}+")
assertTrue(regex.matches("ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
// Invalid uses of \p{Upper}
try {
regex = Regex("\\p{Upper")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\p{Upper;")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
// Test \p{ASCII}
/*
* FIXME: Requires complex range processing p = Regex("<\\p{ASCII}\\d\\P{ASCII}:[\\p{ASCII}\u1234]\\s[^\\P{ASCII}]>");
* m = p.matcher("<A4\u0080:G X>"); assertTrue(m.matches()); m =
* p.matcher("<P4\u00ff:\u1234\t\n>"); assertTrue(m.matches()); m =
* p.matcher("<\u00846#:E E>"); assertFalse(m.matches())
*/
regex = Regex("\\p{ASCII}")
for (i in 0 until 0x80) {
assertTrue(regex.matches("${i.toChar()}"))
}
for (i in 0x80..0xff) {
assertFalse(regex.matches("${i.toChar()}"))
}
// Invalid uses of \p{ASCII}
try {
regex = Regex("\\p{ASCII")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
try {
regex = Regex("\\p{ASCII;")
fail("IllegalArgumentException expected")
} catch (e: IllegalArgumentException) {
}
// Test \p{Alpha}
// TODO
// Test \p{Digit}
// TODO
// Test \p{XDigit}
// TODO
// Test \p{Alnum}
// TODO
// Test \p{Punct}
// TODO
// Test \p{Graph}
// TODO
// Test \p{Print}
// TODO
// Test \p{Blank}
// TODO
// Test \p{Space}
// TODO
// Test \p{Cntrl}
// TODO
}
@Test fun testUnicodeCategories() {
// Test Unicode categories using \p and \P
// One letter codes: L, M, N, P, S, Z, C
// Two letter codes: Lu, Nd, Sc, Sm, ...
// See java.lang.Character and Unicode standard for complete list
// TODO
// Test \p{L}
// TODO
// Test \p{N}
// TODO
// ... etc
// Test two letter codes:
// From unicode.org:
// Lu
// Ll
// Lt
// Lm
// Lo
// Mn
// Mc
// Me
// Nd
// Nl
// No
// Pc
// Pd
// Ps
// Pe
// Pi
// Pf
// Po
// Sm
// Sc
// Sk
// So
// Zs
// Zl
// Zp
// Cc
// Cf
// Cs
// Co
// Cn
}
@Test fun testUnicodeBlocks() {
var regex: Regex
// Test Unicode blocks using \p and \P
for (block in UBlocks) {
regex = Regex("\\p{In" + block.name + "}")
if (block.low > 0) {
assertFalse(regex.matches((block.low - 1).toChar().toString()))
}
for (i in block.low..block.high) {
assertTrue(regex.matches(i.toChar().toString()))
}
if (block.high < 0xFFFF) {
assertFalse(regex.matches((block.high + 1).toChar().toString()))
}
regex = Regex("\\P{In" + block.name + "}")
if (block.low > 0) {
assertTrue(regex.matches((block.low - 1).toChar().toString()))
}
for (i in block.low..block.high) {
assertFalse("assert: Regex: $regex, match to: ${i.toChar()} ($i)", regex.matches(i.toChar().toString()))
}
if (block.high < 0xFFFF) {
assertTrue(regex.matches((block.high + 1).toChar().toString()))
}
}
}
@Test fun testCapturingGroups() {
// Test simple capturing groups
// TODO
// Test grouping without capture (?:...)
// TODO
// Test combination of grouping and capture
// TODO
// Test \<num> sequence with capturing and non-capturing groups
// TODO
// Test \<num> with <num> out of range
// TODO
}
@Test fun testRepeats() {
// Test ?
// TODO
// Test *
// TODO
// Test +
// TODO
// Test {<num>}, including 0, 1 and more
// TODO
// Test {<num>,}, including 0, 1 and more
// TODO
// Test {<n1>,<n2>}, with n1 < n2, n1 = n2 and n1 > n2 (illegal?)
// TODO
}
@Test fun testAnchors() {
// Test ^, default and MULTILINE
// TODO
// Test $, default and MULTILINE
// TODO
// Test \b (word boundary)
// TODO
// Test \B (not a word boundary)
// TODO
// Test \A (beginning of string)
// TODO
// Test \Z (end of string)
// TODO
// Test \z (end of string)
// TODO
// Test \G
// TODO
// Test positive lookahead using (?=...)
// TODO
// Test negative lookahead using (?!...)
// TODO
// Test positive lookbehind using (?<=...)
// TODO
// Test negative lookbehind using (?<!...)
// TODO
}
@Test fun testMisc() {
var regex: Regex
// Test (?>...)
// TODO
// Test (?onflags-offflags)
// Valid flags are i,m,d,s,u,x
// TODO
// Test (?onflags-offflags:...)
// TODO
// Test \Q, \E
regex = Regex("[a-z]+;\\Q[a-z]+;\\Q(foo.*);\\E[0-9]+")
assertTrue(regex.matches("abc;[a-z]+;\\Q(foo.*);411"))
assertFalse(regex.matches("abc;def;foo42;555"))
assertFalse(regex.matches("abc;\\Qdef;\\Qfoo99;\\E123"))
regex = Regex("[a-z]+;(foo[0-9]-\\Q(...)\\E);[0-9]+")
val result = regex.matchEntire("abc;foo5-(...);123")
assertNotNull(result)
assertEquals("foo5-(...)", result!!.groupValues[1])
assertFalse(regex.matches("abc;foo9-(xxx);789"))
regex = Regex("[a-z]+;(bar[0-9]-[a-z\\Q$-\\E]+);[0-9]+")
assertTrue(regex.matches("abc;bar0-def$-;123"))
regex = Regex("[a-z]+;(bar[0-9]-[a-z\\Q-$\\E]+);[0-9]+")
assertTrue(regex.matches("abc;bar0-def$-;123"))
regex = Regex("[a-z]+;(bar[0-9]-[a-z\\Q[0-9]\\E]+);[0-9]+")
assertTrue(regex.matches("abc;bar0-def[99]-]0x[;123"));
regex = Regex("[a-z]+;(bar[0-9]-[a-z\\[0\\-9\\]]+);[0-9]+")
assertTrue(regex.matches("abc;bar0-def[99]-]0x[;123"))
// Test #<comment text>
// TODO
}
@Test fun testCompile1() {
val regex = Regex("[0-9A-Za-z][0-9A-Za-z\\x2e\\x3a\\x2d\\x5f]*")
val name = "iso-8859-1"
assertTrue(regex.matches(name))
}
@Test fun testCompile2() {
val findString = "\\Qimport\\E"
val regex = Regex(findString)
assertTrue(regex in "import a.A;\n\n import b.B;\nclass C {}")
}
@Test fun testCompile3() {
var regex: Regex
var result: MatchResult?
regex = Regex("a$")
result = regex.find("a\n")
assertNotNull(result)
assertEquals("a", result!!.value)
assertNull(result.next())
regex = Regex("(a$)")
result = regex.find("a\n")
assertNotNull(result)
assertEquals("a", result!!.value)
assertEquals("a", result.groupValues[1])
assertNull(result.next())
regex = Regex("^.*$", RegexOption.MULTILINE)
result = regex.find("a\n")
assertNotNull(result)
assertEquals("a", result!!.value)
assertNull(result.next())
result = regex.find("a\nb\n")
assertNotNull(result)
assertEquals("a", result!!.value)
result = result.next()
assertNotNull(result)
assertEquals("b", result!!.value)
assertNull(result.next())
result = regex.find("a\nb")
assertNotNull(result)
assertEquals("a", result!!.value)
result = result.next()
assertNotNull(result)
assertEquals("b", result!!.value)
assertNull(result.next())
result = regex.find("\naa\r\nbb\rcc\n\n")
assertNotNull(result)
assertTrue(result!!.value == "")
result = result.next()
assertNotNull(result)
assertEquals("aa", result!!.value)
result = result.next()
assertNotNull(result)
assertEquals("bb", result!!.value)
result = result.next()
assertNotNull(result)
assertEquals("cc", result!!.value)
result = result.next()
assertNotNull(result)
assertTrue(result!!.value == "")
assertNull(result.next())
result = regex.find("a")
assertNotNull(result)
assertEquals("a", result!!.value)
assertNull(result.next())
result = regex.find("")
assertNull(result)
regex = Regex("^.*$")
result = regex.find("")
assertNotNull(result)
assertTrue(result!!.value == "")
assertNull(result.next())
}
@Test fun testCompile4() {
val findString = "\\Qpublic\\E"
val text = StringBuilder(" public class Class {\n" + " public class Class {")
val regex = Regex(findString)
val result = regex.find(text)
assertNotNull(result)
assertEquals(4, result!!.range.start)
// modify text
text.setLength(0)
text.append("Text have been changed.")
assertNull(regex.find(text))
}
@Test fun testCompile5() {
val p = Regex("^[0-9]")
val s = p.split("12", 0)
assertEquals("", s[0])
assertEquals("2", s[1])
assertEquals(2, s.size)
}
private class UBInfo(var low: Int, var high: Int, var name: String)
// A table representing the unicode categories
// private static UBInfo[] UCategories = {
// Lu
// Ll
// Lt
// Lm
// Lo
// Mn
// Mc
// Me
// Nd
// Nl
// No
// Pc
// Pd
// Ps
// Pe
// Pi
// Pf
// Po
// Sm
// Sc
// Sk
// So
// Zs
// Zl
// Zp
// Cc
// Cf
// Cs
// Co
// Cn
// };
// A table representing the unicode character blocks
private val UBlocks = arrayOf(
/* 0000; 007F; Basic Latin */
UBInfo(0x0000, 0x007F, "BasicLatin"), // Character.UnicodeBlock.BASIC_LATIN
/* 0080; 00FF; Latin-1 Supplement */
UBInfo(0x0080, 0x00FF, "Latin-1Supplement"), // Character.UnicodeBlock.LATIN_1_SUPPLEMENT
/* 0100; 017F; Latin Extended-A */
UBInfo(0x0100, 0x017F, "LatinExtended-A"), // Character.UnicodeBlock.LATIN_EXTENDED_A
/* 0180; 024F; Latin Extended-B */
// new UBInfo (0x0180,0x024F,"InLatinExtended-B"), //
// Character.UnicodeBlock.LATIN_EXTENDED_B
/* 0250; 02AF; IPA Extensions */
UBInfo(0x0250, 0x02AF, "IPAExtensions"), // Character.UnicodeBlock.IPA_EXTENSIONS
/* 02B0; 02FF; Spacing Modifier Letters */
UBInfo(0x02B0, 0x02FF, "SpacingModifierLetters"), // Character.UnicodeBlock.SPACING_MODIFIER_LETTERS
/* 0300; 036F; Combining Diacritical Marks */
UBInfo(0x0300, 0x036F, "CombiningDiacriticalMarks"), // Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS
/* 0370; 03FF; Greek */
UBInfo(0x0370, 0x03FF, "Greek"), // Character.UnicodeBlock.GREEK
/* 0400; 04FF; Cyrillic */
UBInfo(0x0400, 0x04FF, "Cyrillic"), // Character.UnicodeBlock.CYRILLIC
/* 0530; 058F; Armenian */
UBInfo(0x0530, 0x058F, "Armenian"), // Character.UnicodeBlock.ARMENIAN
/* 0590; 05FF; Hebrew */
UBInfo(0x0590, 0x05FF, "Hebrew"), // Character.UnicodeBlock.HEBREW
/* 0600; 06FF; Arabic */
UBInfo(0x0600, 0x06FF, "Arabic"), // Character.UnicodeBlock.ARABIC
/* 0700; 074F; Syriac */
UBInfo(0x0700, 0x074F, "Syriac"), // Character.UnicodeBlock.SYRIAC
/* 0780; 07BF; Thaana */
UBInfo(0x0780, 0x07BF, "Thaana"), // Character.UnicodeBlock.THAANA
/* 0900; 097F; Devanagari */
UBInfo(0x0900, 0x097F, "Devanagari"), // Character.UnicodeBlock.DEVANAGARI
/* 0980; 09FF; Bengali */
UBInfo(0x0980, 0x09FF, "Bengali"), // Character.UnicodeBlock.BENGALI
/* 0A00; 0A7F; Gurmukhi */
UBInfo(0x0A00, 0x0A7F, "Gurmukhi"), // Character.UnicodeBlock.GURMUKHI
/* 0A80; 0AFF; Gujarati */
UBInfo(0x0A80, 0x0AFF, "Gujarati"), // Character.UnicodeBlock.GUJARATI
/* 0B00; 0B7F; Oriya */
UBInfo(0x0B00, 0x0B7F, "Oriya"), // Character.UnicodeBlock.ORIYA
/* 0B80; 0BFF; Tamil */
UBInfo(0x0B80, 0x0BFF, "Tamil"), // Character.UnicodeBlock.TAMIL
/* 0C00; 0C7F; Telugu */
UBInfo(0x0C00, 0x0C7F, "Telugu"), // Character.UnicodeBlock.TELUGU
/* 0C80; 0CFF; Kannada */
UBInfo(0x0C80, 0x0CFF, "Kannada"), // Character.UnicodeBlock.KANNADA
/* 0D00; 0D7F; Malayalam */
UBInfo(0x0D00, 0x0D7F, "Malayalam"), // Character.UnicodeBlock.MALAYALAM
/* 0D80; 0DFF; Sinhala */
UBInfo(0x0D80, 0x0DFF, "Sinhala"), // Character.UnicodeBlock.SINHALA
/* 0E00; 0E7F; Thai */
UBInfo(0x0E00, 0x0E7F, "Thai"), // Character.UnicodeBlock.THAI
/* 0E80; 0EFF; Lao */
UBInfo(0x0E80, 0x0EFF, "Lao"), // Character.UnicodeBlock.LAO
/* 0F00; 0FFF; Tibetan */
UBInfo(0x0F00, 0x0FFF, "Tibetan"), // Character.UnicodeBlock.TIBETAN
/* 1000; 109F; Myanmar */
UBInfo(0x1000, 0x109F, "Myanmar"), // Character.UnicodeBlock.MYANMAR
/* 10A0; 10FF; Georgian */
UBInfo(0x10A0, 0x10FF, "Georgian"), // Character.UnicodeBlock.GEORGIAN
/* 1100; 11FF; Hangul Jamo */
UBInfo(0x1100, 0x11FF, "HangulJamo"), // Character.UnicodeBlock.HANGUL_JAMO
/* 1200; 137F; Ethiopic */
UBInfo(0x1200, 0x137F, "Ethiopic"), // Character.UnicodeBlock.ETHIOPIC
/* 13A0; 13FF; Cherokee */
UBInfo(0x13A0, 0x13FF, "Cherokee"), // Character.UnicodeBlock.CHEROKEE
/* 1400; 167F; Unified Canadian Aboriginal Syllabics */
UBInfo(0x1400, 0x167F, "UnifiedCanadianAboriginalSyllabics"), // Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS
/* 1680; 169F; Ogham */
UBInfo(0x1680, 0x169F, "Ogham"), // Character.UnicodeBlock.OGHAM
/* 16A0; 16FF; Runic */
UBInfo(0x16A0, 0x16FF, "Runic"), // Character.UnicodeBlock.RUNIC
/* 1780; 17FF; Khmer */
UBInfo(0x1780, 0x17FF, "Khmer"), // Character.UnicodeBlock.KHMER
/* 1800; 18AF; Mongolian */
UBInfo(0x1800, 0x18AF, "Mongolian"), // Character.UnicodeBlock.MONGOLIAN
/* 1E00; 1EFF; Latin Extended Additional */
UBInfo(0x1E00, 0x1EFF, "LatinExtendedAdditional"), // Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL
/* 1F00; 1FFF; Greek Extended */
UBInfo(0x1F00, 0x1FFF, "GreekExtended"), // Character.UnicodeBlock.GREEK_EXTENDED
/* 2000; 206F; General Punctuation */
UBInfo(0x2000, 0x206F, "GeneralPunctuation"), // Character.UnicodeBlock.GENERAL_PUNCTUATION
/* 2070; 209F; Superscripts and Subscripts */
UBInfo(0x2070, 0x209F, "SuperscriptsandSubscripts"), // Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS
/* 20A0; 20CF; Currency Symbols */
UBInfo(0x20A0, 0x20CF, "CurrencySymbols"), // Character.UnicodeBlock.CURRENCY_SYMBOLS
/* 20D0; 20FF; Combining Marks for Symbols */
UBInfo(0x20D0, 0x20FF, "CombiningMarksforSymbols"), // Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS
/* 2100; 214F; Letterlike Symbols */
UBInfo(0x2100, 0x214F, "LetterlikeSymbols"), // Character.UnicodeBlock.LETTERLIKE_SYMBOLS
/* 2150; 218F; Number Forms */
UBInfo(0x2150, 0x218F, "NumberForms"), // Character.UnicodeBlock.NUMBER_FORMS
/* 2190; 21FF; Arrows */
UBInfo(0x2190, 0x21FF, "Arrows"), // Character.UnicodeBlock.ARROWS
/* 2200; 22FF; Mathematical Operators */
UBInfo(0x2200, 0x22FF, "MathematicalOperators"), // Character.UnicodeBlock.MATHEMATICAL_OPERATORS
/* 2300; 23FF; Miscellaneous Technical */
UBInfo(0x2300, 0x23FF, "MiscellaneousTechnical"), // Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL
/* 2400; 243F; Control Pictures */
UBInfo(0x2400, 0x243F, "ControlPictures"), // Character.UnicodeBlock.CONTROL_PICTURES
/* 2440; 245F; Optical Character Recognition */
UBInfo(0x2440, 0x245F, "OpticalCharacterRecognition"), // Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION
/* 2460; 24FF; Enclosed Alphanumerics */
UBInfo(0x2460, 0x24FF, "EnclosedAlphanumerics"), // Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS
/* 2500; 257F; Box Drawing */
UBInfo(0x2500, 0x257F, "BoxDrawing"), // Character.UnicodeBlock.BOX_DRAWING
/* 2580; 259F; Block Elements */
UBInfo(0x2580, 0x259F, "BlockElements"), // Character.UnicodeBlock.BLOCK_ELEMENTS
/* 25A0; 25FF; Geometric Shapes */
UBInfo(0x25A0, 0x25FF, "GeometricShapes"), // Character.UnicodeBlock.GEOMETRIC_SHAPES
/* 2600; 26FF; Miscellaneous Symbols */
UBInfo(0x2600, 0x26FF, "MiscellaneousSymbols"), // Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS
/* 2700; 27BF; Dingbats */
UBInfo(0x2700, 0x27BF, "Dingbats"), // Character.UnicodeBlock.DINGBATS
/* 2800; 28FF; Braille Patterns */
UBInfo(0x2800, 0x28FF, "BraillePatterns"), // Character.UnicodeBlock.BRAILLE_PATTERNS
/* 2E80; 2EFF; CJK Radicals Supplement */
UBInfo(0x2E80, 0x2EFF, "CJKRadicalsSupplement"), // Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT
/* 2F00; 2FDF; Kangxi Radicals */
UBInfo(0x2F00, 0x2FDF, "KangxiRadicals"), // Character.UnicodeBlock.KANGXI_RADICALS
/* 2FF0; 2FFF; Ideographic Description Characters */
UBInfo(0x2FF0, 0x2FFF, "IdeographicDescriptionCharacters"), // Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS
/* 3000; 303F; CJK Symbols and Punctuation */
UBInfo(0x3000, 0x303F, "CJKSymbolsandPunctuation"), // Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
/* 3040; 309F; Hiragana */
UBInfo(0x3040, 0x309F, "Hiragana"), // Character.UnicodeBlock.HIRAGANA
/* 30A0; 30FF; Katakana */
UBInfo(0x30A0, 0x30FF, "Katakana"), // Character.UnicodeBlock.KATAKANA
/* 3100; 312F; Bopomofo */
UBInfo(0x3100, 0x312F, "Bopomofo"), // Character.UnicodeBlock.BOPOMOFO
/* 3130; 318F; Hangul Compatibility Jamo */
UBInfo(0x3130, 0x318F, "HangulCompatibilityJamo"), // Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO
/* 3190; 319F; Kanbun */
UBInfo(0x3190, 0x319F, "Kanbun"), // Character.UnicodeBlock.KANBUN
/* 31A0; 31BF; Bopomofo Extended */
UBInfo(0x31A0, 0x31BF, "BopomofoExtended"), // Character.UnicodeBlock.BOPOMOFO_EXTENDED
/* 3200; 32FF; Enclosed CJK Letters and Months */
UBInfo(0x3200, 0x32FF, "EnclosedCJKLettersandMonths"), // Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS
/* 3300; 33FF; CJK Compatibility */
UBInfo(0x3300, 0x33FF, "CJKCompatibility"), // Character.UnicodeBlock.CJK_COMPATIBILITY
/* 3400; 4DB5; CJK Unified Ideographs Extension A */
UBInfo(0x3400, 0x4DB5, "CJKUnifiedIdeographsExtensionA"), // Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
/* 4E00; 9FFF; CJK Unified Ideographs */
UBInfo(0x4E00, 0x9FFF, "CJKUnifiedIdeographs"), // Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
/* A000; A48F; Yi Syllables */
UBInfo(0xA000, 0xA48F, "YiSyllables"), // Character.UnicodeBlock.YI_SYLLABLES
/* A490; A4CF; Yi Radicals */
UBInfo(0xA490, 0xA4CF, "YiRadicals"), // Character.UnicodeBlock.YI_RADICALS
/* AC00; D7A3; Hangul Syllables */
UBInfo(0xAC00, 0xD7A3, "HangulSyllables"), // Character.UnicodeBlock.HANGUL_SYLLABLES
/* D800; DB7F; High Surrogates */
/* DB80; DBFF; High Private Use Surrogates */
/* DC00; DFFF; Low Surrogates */
/* E000; F8FF; Private Use */
/* F900; FAFF; CJK Compatibility Ideographs */
UBInfo(0xF900, 0xFAFF, "CJKCompatibilityIdeographs"), // Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
/* FB00; FB4F; Alphabetic Presentation Forms */
UBInfo(0xFB00, 0xFB4F, "AlphabeticPresentationForms"), // Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS
/* FB50; FDFF; Arabic Presentation Forms-A */
UBInfo(0xFB50, 0xFDFF, "ArabicPresentationForms-A"), // Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A
/* FE20; FE2F; Combining Half Marks */
UBInfo(0xFE20, 0xFE2F, "CombiningHalfMarks"), // Character.UnicodeBlock.COMBINING_HALF_MARKS
/* FE30; FE4F; CJK Compatibility Forms */
UBInfo(0xFE30, 0xFE4F, "CJKCompatibilityForms"), // Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS
/* FE50; FE6F; Small Form Variants */
UBInfo(0xFE50, 0xFE6F, "SmallFormVariants"), // Character.UnicodeBlock.SMALL_FORM_VARIANTS
/* FE70; FEFE; Arabic Presentation Forms-B */
// new UBInfo (0xFE70,0xFEFE,"InArabicPresentationForms-B"), //
// Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B
/* FEFF; FEFF; Specials */
UBInfo(0xFEFF, 0xFEFF, "Specials"), // Character.UnicodeBlock.SPECIALS
/* FF00; FFEF; Halfwidth and Fullwidth Forms */
UBInfo(0xFF00, 0xFFEF, "HalfwidthandFullwidthForms"), // Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
/* FFF0; FFFD; Specials */
UBInfo(0xFFF0, 0xFFFD, "Specials") // Character.UnicodeBlock.SPECIALS
)
}
| apache-2.0 | c312e1f6d8d0d90234c48d3004f209ce | 36.605021 | 137 | 0.55877 | 3.750459 | false | true | false | false |
WillowChat/Kale | src/main/kotlin/chat/willow/kale/irc/message/extension/cap/CapMessage.kt | 2 | 14133 | package chat.willow.kale.irc.message.extension.cap
import chat.willow.kale.core.ICommand
import chat.willow.kale.core.message.*
import chat.willow.kale.irc.CharacterCodes
import chat.willow.kale.irc.message.*
import chat.willow.kale.irc.prefix.Prefix
import chat.willow.kale.irc.prefix.PrefixParser
import chat.willow.kale.irc.prefix.PrefixSerialiser
object CapMessage : ICommand {
override val command = "CAP"
object Parser : IMessageParser<CapMessage> {
override fun parse(message: IrcMessage): CapMessage? {
TODO("not implemented")
}
}
object Ls : ISubcommand {
override val subcommand = "LS"
// CAP LS <version>
data class Command(val version: String?) {
object Descriptor : KaleDescriptor<Command>(matcher = subcommandMatcher(command, subcommand, subcommandPosition = 0), parser = Parser)
object Parser : SubcommandParser<Command>(subcommand) {
override fun parseFromComponents(components: IrcMessageComponents): Command? {
val version = components.parameters.getOrNull(0)
return Command(version)
}
}
object Serialiser : SubcommandSerialiser<Command>(command, subcommand) {
override fun serialiseToComponents(message: Command): IrcMessageComponents {
val parameters: List<String> = if (message.version == null) {
listOf()
} else {
listOf(message.version)
}
return IrcMessageComponents(parameters = parameters)
}
}
}
data class Message(val source: Prefix?, val target: String, val caps: Map<String, String?>, val isMultiline: Boolean = false) {
// CAP * LS ...
object Descriptor : KaleDescriptor<Message>(matcher = subcommandMatcher(command, subcommand, subcommandPosition = 1), parser = Parser)
object Parser : SubcommandParser<Message>(subcommand, subcommandPosition = 1) {
override fun parseFromComponents(components: IrcMessageComponents): Message? {
if (components.parameters.size < 2) {
return null
}
val source = PrefixParser.parse(components.prefix ?: "")
val target = components.parameters[0]
val asteriskOrCaps = components.parameters[1]
val rawCaps: String
val isMultiline: Boolean
if (asteriskOrCaps == "*") {
rawCaps = components.parameters.getOrNull(2) ?: ""
isMultiline = true
} else {
rawCaps = asteriskOrCaps
isMultiline = false
}
val caps = ParseHelper.parseToKeysAndOptionalValues(rawCaps, CharacterCodes.SPACE, CharacterCodes.EQUALS)
return Message(source, target, caps, isMultiline)
}
}
object Serialiser : SubcommandSerialiser<Message>(command, subcommand, subcommandPosition = 1) {
override fun serialiseToComponents(message: Message): IrcMessageComponents {
val caps = SerialiserHelper.serialiseKeysAndOptionalValues(message.caps, CharacterCodes.EQUALS, CharacterCodes.SPACE)
return if (message.source != null) {
IrcMessageComponents(prefix = PrefixSerialiser.serialise(message.source), parameters = listOf(message.target, caps))
} else {
IrcMessageComponents(parameters = listOf(message.target, caps))
}
}
}
}
}
object Ack : ISubcommand {
override val subcommand = "ACK"
data class Command(val caps: List<String>) {
// CAP ACK :caps
object Descriptor : KaleDescriptor<Command>(matcher = subcommandMatcher(command, subcommand, subcommandPosition = 0), parser = Parser)
object Parser : SubcommandParser<Command>(subcommand) {
override fun parseFromComponents(components: IrcMessageComponents): Command? {
if (components.parameters.isEmpty()) {
return null
}
val rawCaps = components.parameters[0]
val caps = rawCaps.split(delimiters = CharacterCodes.SPACE).filterNot(String::isEmpty)
return Command(caps)
}
}
object Serialiser : SubcommandSerialiser<Command>(command, subcommand) {
override fun serialiseToComponents(message: Command): IrcMessageComponents {
val caps = message.caps.joinToString(separator = " ")
val parameters = listOf(caps)
return IrcMessageComponents(parameters)
}
}
}
data class Message(val source: Prefix?, val target: String, val caps: List<String>) {
// CAP * ACK :
object Descriptor : KaleDescriptor<Message>(matcher = subcommandMatcher(command, subcommand, subcommandPosition = 1), parser = Parser)
object Parser : SubcommandParser<Message>(subcommand, subcommandPosition = 1) {
override fun parseFromComponents(components: IrcMessageComponents): Message? {
if (components.parameters.size < 2) {
return null
}
val prefix = PrefixParser.parse(components.prefix ?: "")
val target = components.parameters[0]
val rawCaps = components.parameters[1]
val caps = rawCaps.split(delimiters = CharacterCodes.SPACE).filterNot(String::isEmpty)
return Message(prefix, target, caps)
}
}
object Serialiser : SubcommandSerialiser<Message>(command, subcommand, subcommandPosition = 1) {
override fun serialiseToComponents(message: Message): IrcMessageComponents {
val caps = message.caps.joinToString(separator = " ")
val parameters = listOf(message.target, caps)
return if (message.source != null) {
IrcMessageComponents(prefix = PrefixSerialiser.serialise(message.source), parameters = parameters)
} else {
IrcMessageComponents(parameters)
}
}
}
}
}
object Del : ISubcommand {
override val subcommand = "DEL"
data class Message(val target: String, val caps: List<String>) {
// CAP * DEL :
object Descriptor : KaleDescriptor<Message>(matcher = subcommandMatcher(command, subcommand, subcommandPosition = 1), parser = Parser)
object Parser : SubcommandParser<Message>(subcommand, subcommandPosition = 1) {
override fun parseFromComponents(components: IrcMessageComponents): Message? {
if (components.parameters.size < 2) {
return null
}
val target = components.parameters[0]
val rawCaps = components.parameters[1]
val caps = ParseHelper.parseToKeysAndOptionalValues(rawCaps, CharacterCodes.SPACE, CharacterCodes.EQUALS).keys.toList()
return Message(target, caps)
}
}
object Serialiser : SubcommandSerialiser<Message>(command, subcommand, subcommandPosition = 1) {
override fun serialiseToComponents(message: Message): IrcMessageComponents {
val capsToValues = message.caps.associate { (it to null) }
val caps = SerialiserHelper.serialiseKeysAndOptionalValues(capsToValues, CharacterCodes.EQUALS, CharacterCodes.SPACE)
return IrcMessageComponents(parameters = listOf(message.target, caps))
}
}
}
}
object End : ISubcommand {
override val subcommand = "END"
object Command {
// CAP END
object Descriptor : KaleDescriptor<Command>(matcher = subcommandMatcher(command, subcommand, subcommandPosition = 0), parser = Parser)
object Parser : SubcommandParser<Command>(subcommand) {
override fun parseFromComponents(components: IrcMessageComponents): Command? {
return Command
}
}
object Serialiser : SubcommandSerialiser<Command>(command, subcommand) {
override fun serialiseToComponents(message: Command): IrcMessageComponents {
return IrcMessageComponents()
}
}
}
}
object Nak : ISubcommand {
override val subcommand = "NAK"
data class Message(val source: Prefix?, val target: String, val caps: List<String>) {
// CAP * NAK :
// TODO: Same as DEL
object Descriptor : KaleDescriptor<Message>(matcher = subcommandMatcher(command, subcommand, subcommandPosition = 1), parser = Parser)
object Parser : SubcommandParser<Message>(subcommand, subcommandPosition = 1) {
override fun parseFromComponents(components: IrcMessageComponents): Message? {
if (components.parameters.size < 2) {
return null
}
val prefix = PrefixParser.parse(components.prefix ?: "")
val target = components.parameters[0]
val rawCaps = components.parameters[1]
val caps = ParseHelper.parseToKeysAndOptionalValues(rawCaps, CharacterCodes.SPACE, CharacterCodes.EQUALS).keys.toList()
return Message(prefix, target, caps)
}
}
object Serialiser : SubcommandSerialiser<Message>(command, subcommand, subcommandPosition = 1) {
override fun serialiseToComponents(message: Message): IrcMessageComponents {
val capsToValues = message.caps.associate { (it to null) }
val caps = SerialiserHelper.serialiseKeysAndOptionalValues(capsToValues, CharacterCodes.EQUALS, CharacterCodes.SPACE)
return if (message.source != null) {
IrcMessageComponents(prefix = PrefixSerialiser.serialise(message.source), parameters = listOf(message.target, caps))
} else {
IrcMessageComponents(parameters = listOf(message.target, caps))
}
}
}
}
}
object New : ISubcommand {
override val subcommand = "NEW"
data class Message(val source: Prefix?, val target: String, val caps: Map<String, String?>) {
// CAP * NEW :
// TODO: Same as DEL
object Descriptor : KaleDescriptor<Message>(matcher = subcommandMatcher(command, subcommand, subcommandPosition = 1), parser = Parser)
object Parser : SubcommandParser<Message>(subcommand, subcommandPosition = 1) {
override fun parseFromComponents(components: IrcMessageComponents): Message? {
if (components.parameters.size < 2) {
return null
}
val prefix = PrefixParser.parse(components.prefix ?: "")
val target = components.parameters[0]
val rawCaps = components.parameters[1]
val caps = ParseHelper.parseToKeysAndOptionalValues(rawCaps, CharacterCodes.SPACE, CharacterCodes.EQUALS)
return Message(prefix, target, caps)
}
}
object Serialiser : SubcommandSerialiser<Message>(command, subcommand, subcommandPosition = 1) {
override fun serialiseToComponents(message: Message): IrcMessageComponents {
val caps = SerialiserHelper.serialiseKeysAndOptionalValues(message.caps, CharacterCodes.EQUALS, CharacterCodes.SPACE)
return if (message.source != null) {
IrcMessageComponents(prefix = PrefixSerialiser.serialise(message.source), parameters = listOf(message.target, caps))
} else {
IrcMessageComponents(parameters = listOf(message.target, caps))
}
}
}
}
}
object Req : ISubcommand {
override val subcommand = "REQ"
data class Command(val caps: List<String>) {
// CAP REQ :
// TODO: Same as ACK
object Descriptor : KaleDescriptor<Command>(matcher = subcommandMatcher(command, subcommand, subcommandPosition = 0), parser = Parser)
object Parser : SubcommandParser<Command>(subcommand) {
override fun parseFromComponents(components: IrcMessageComponents): Command? {
if (components.parameters.isEmpty()) {
return null
}
val rawCaps = components.parameters[0]
val caps = rawCaps.split(delimiters = CharacterCodes.SPACE).filterNot(String::isEmpty)
return Command(caps)
}
}
object Serialiser : SubcommandSerialiser<Command>(command, subcommand) {
override fun serialiseToComponents(message: Command): IrcMessageComponents {
val caps = message.caps.joinToString(separator = " ")
val parameters = listOf(caps)
return IrcMessageComponents(parameters)
}
}
}
}
} | isc | 9edef13319f29a4ebe8187564c809f10 | 33.985149 | 146 | 0.57065 | 5.7851 | false | false | false | false |
Coding/Coding-Android | widget-pick-photo/src/main/java/net/coding/program/pickphoto/AllPhotoAdapter.kt | 1 | 1930 | package net.coding.program.pickphoto
import android.content.Context
import android.database.Cursor
import android.view.View
import android.view.ViewGroup
/**
* Created by chenchao on 15/5/6.
* 第一个item是照相机
*/
class AllPhotoAdapter(context: Context, c: Cursor, autoRequery: Boolean, activity: PhotoPickActivity) : GridPhotoAdapter(context, c, autoRequery, activity) {
private val SCREEN_WIDTH: Int
init {
SCREEN_WIDTH = context.resources.displayMetrics.widthPixels
}
override fun getCount(): Int = super.getCount() + 1
override fun getItem(position: Int): Any {
return if (position > 0) {
super.getItem(position - 1)
} else {
super.getItem(position)
}
}
override fun getItemId(position: Int): Long {
return if (position > 0) {
super.getItemId(position - 1)
} else {
-1
}
}
override fun getDropDownView(position: Int, convertView: View, parent: ViewGroup): View {
return if (position > 0) {
super.getDropDownView(position - 1, convertView, parent)
} else {
getView(position, convertView, parent)
}
}
override fun getViewTypeCount(): Int = 2
override fun getItemViewType(position: Int): Int = if (position == 0) 0 else 1
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
if (position > 0) {
return super.getView(position - 1, convertView, parent)
} else {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.photopick_gridlist_item_camera2, parent, false)
convertView!!.layoutParams.height = SCREEN_WIDTH / 3
convertView.setOnClickListener { mActivity.camera() }
}
return convertView
}
}
}
| mit | 96bf228fd41ffa369f8730ce09da5da5 | 28.9375 | 157 | 0.616388 | 4.404598 | false | false | false | false |
mhshams/yekan | vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/core/http/HttpServerResponse.kt | 2 | 3505 | package io.vertx.kotlin.core.http
import io.vertx.core.AsyncResult
import io.vertx.kotlin.core.MultiMap
import io.vertx.kotlin.core.buffer.Buffer
import io.vertx.kotlin.core.internal.KotlinAsyncHandler
import io.vertx.kotlin.core.internal.KotlinHandler
import io.vertx.kotlin.core.streams.WriteStream
/**
*/
class HttpServerResponse(override val delegate: io.vertx.core.http.HttpServerResponse) : WriteStream<Buffer> {
override fun writeQueueFull(): Boolean = delegate.writeQueueFull()
override fun exceptionHandler(handler: (Throwable) -> Unit): HttpServerResponse {
delegate.exceptionHandler(handler)
return this
}
override fun write(data: Buffer): HttpServerResponse {
delegate.write(data.delegate)
return this
}
override fun setWriteQueueMaxSize(maxSize: Int): HttpServerResponse {
delegate.setWriteQueueMaxSize(maxSize)
return this
}
override fun drainHandler(handler: (Unit) -> Unit): HttpServerResponse {
delegate.drainHandler(KotlinHandler(handler, {}))
return this
}
fun getStatusCode(): Int = delegate.getStatusCode()
fun setStatusCode(statusCode: Int): HttpServerResponse {
delegate.setStatusCode(statusCode)
return this
}
fun getStatusMessage(): String = delegate.getStatusMessage()
fun setStatusMessage(statusMessage: String): HttpServerResponse {
delegate.setStatusMessage(statusMessage)
return this
}
fun setChunked(chunked: Boolean): HttpServerResponse {
delegate.setChunked(chunked)
return this
}
fun isChunked(): Boolean = delegate.isChunked()
fun headers(): MultiMap = MultiMap(delegate.headers())
fun putHeader(name: String, value: String): HttpServerResponse {
delegate.putHeader(name, value)
return this
}
fun trailers(): MultiMap = MultiMap(delegate.trailers())
fun putTrailer(name: String, value: String): HttpServerResponse {
delegate.putTrailer(name, value)
return this
}
fun closeHandler(handler: (Unit) -> Unit): HttpServerResponse {
delegate.closeHandler(KotlinHandler(handler, {}))
return this
}
fun write(chunk: String, enc: String): HttpServerResponse {
delegate.write(chunk, enc)
return this
}
fun write(chunk: String): HttpServerResponse {
delegate.write(chunk)
return this
}
fun end(chunk: String) {
delegate.end(chunk)
}
fun end(chunk: String, enc: String) {
delegate.end(chunk, enc)
}
fun end(chunk: Buffer) {
delegate.end(chunk.delegate)
}
fun end() {
delegate.end()
}
fun sendFile(filename: String): HttpServerResponse {
delegate.sendFile(filename)
return this
}
fun sendFile(filename: String, resultHandler: (AsyncResult<Unit>) -> Unit): HttpServerResponse {
delegate.sendFile(filename, KotlinAsyncHandler(resultHandler, {}))
return this
}
fun close() {
delegate.close()
}
fun ended(): Boolean = delegate.ended()
fun headWritten(): Boolean = delegate.headWritten()
fun headersEndHandler(handler: (Unit) -> Unit): HttpServerResponse {
delegate.headersEndHandler(KotlinHandler(handler, {}))
return this
}
fun bodyEndHandler(handler: (Unit) -> Unit): HttpServerResponse {
delegate.bodyEndHandler(KotlinHandler(handler, {}))
return this
}
}
| apache-2.0 | ab0d7708c25a3f0f557425407846b5fc | 26.170543 | 110 | 0.669044 | 4.546044 | false | false | false | false |
orhanobut/logger | logger/src/test/java/com.orhanobut.logger/LoggerPrinterTest.kt | 1 | 5520 | package com.orhanobut.logger
import com.orhanobut.logger.Logger.*
import org.junit.Before
import org.junit.Test
import org.mockito.Matchers.any
import org.mockito.Matchers.contains
import org.mockito.Matchers.eq
import org.mockito.Matchers.isNull
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyZeroInteractions
import org.mockito.MockitoAnnotations.initMocks
import java.util.*
class LoggerPrinterTest {
private val printer = LoggerPrinter()
@Mock private lateinit var adapter: LogAdapter
@Before fun setup() {
initMocks(this)
`when`(adapter!!.isLoggable(any(Int::class.java), any(String::class.java))).thenReturn(true)
printer.addAdapter(adapter!!)
}
@Test fun logDebug() {
printer.d("message %s", "sent")
verify(adapter).log(DEBUG, null, "message sent")
}
@Test fun logError() {
printer.e("message %s", "sent")
verify(adapter).log(ERROR, null, "message sent")
}
@Test fun logErrorWithThrowable() {
val throwable = Throwable("exception")
printer.e(throwable, "message %s", "sent")
verify(adapter).log(eq(ERROR), isNull(String::class.java), contains("message sent : java.lang.Throwable: exception"))
}
@Test fun logWarning() {
printer.w("message %s", "sent")
verify(adapter).log(WARN, null, "message sent")
}
@Test fun logInfo() {
printer.i("message %s", "sent")
verify(adapter).log(INFO, null, "message sent")
}
@Test fun logWtf() {
printer.wtf("message %s", "sent")
verify(adapter).log(ASSERT, null, "message sent")
}
@Test fun logVerbose() {
printer.v("message %s", "sent")
verify(adapter).log(VERBOSE, null, "message sent")
}
@Test fun oneTimeTag() {
printer.t("tag").d("message")
verify(adapter).log(DEBUG, "tag", "message")
}
@Test fun logObject() {
val `object` = "Test"
printer.d(`object`)
verify(adapter).log(DEBUG, null, "Test")
}
@Test fun logArray() {
val `object` = intArrayOf(1, 6, 7, 30, 33)
printer.d(`object`)
verify(adapter).log(DEBUG, null, "[1, 6, 7, 30, 33]")
}
@Test fun logStringArray() {
val `object` = arrayOf("a", "b", "c")
printer.d(`object`)
verify(adapter).log(DEBUG, null, "[a, b, c]")
}
@Test fun logMultiDimensionArray() {
val doubles = arrayOf(doubleArrayOf(1.0, 6.0), doubleArrayOf(1.2, 33.0))
printer.d(doubles)
verify(adapter).log(DEBUG, null, "[[1.0, 6.0], [1.2, 33.0]]")
}
@Test fun logList() {
val list = Arrays.asList("foo", "bar")
printer.d(list)
verify(adapter).log(DEBUG, null, list.toString())
}
@Test fun logMap() {
val map = HashMap<String, String>()
map["key"] = "value"
map["key2"] = "value2"
printer.d(map)
verify(adapter).log(DEBUG, null, map.toString())
}
@Test fun logSet() {
val set = HashSet<String>()
set.add("key")
set.add("key1")
printer.d(set)
verify(adapter).log(DEBUG, null, set.toString())
}
@Test fun logJsonObject() {
printer.json(" {\"key\":3}")
verify(adapter).log(DEBUG, null, "{\"key\": 3}")
}
@Test fun logJsonArray() {
printer.json("[{\"key\":3}]")
verify(adapter).log(DEBUG, null, "[{\"key\": 3}]")
}
@Test fun logInvalidJsonObject() {
printer.json("no json")
printer.json("{ missing end")
verify(adapter, times(2)).log(ERROR, null, "Invalid Json")
}
@Test fun jsonLogEmptyOrNull() {
printer.json(null)
printer.json("")
verify(adapter, times(2)).log(DEBUG, null, "Empty/Null json content")
}
@Test fun xmlLog() {
printer.xml("<xml>Test</xml>")
verify(adapter).log(DEBUG, null,
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xml>Test</xml>\n")
}
@Test fun invalidXmlLog() {
printer.xml("xml>Test</xml>")
verify(adapter).log(ERROR, null, "Invalid xml")
}
@Test fun xmlLogNullOrEmpty() {
printer.xml(null)
printer.xml("")
verify(adapter, times(2)).log(DEBUG, null, "Empty/Null xml content")
}
@Test fun clearLogAdapters() {
printer.clearLogAdapters()
printer.d("")
verifyZeroInteractions(adapter)
}
@Test fun addAdapter() {
printer.clearLogAdapters()
val adapter1 = mock(LogAdapter::class.java)
val adapter2 = mock(LogAdapter::class.java)
printer.addAdapter(adapter1)
printer.addAdapter(adapter2)
printer.d("message")
verify(adapter1).isLoggable(DEBUG, null)
verify(adapter2).isLoggable(DEBUG, null)
}
@Test fun doNotLogIfNotLoggable() {
printer.clearLogAdapters()
val adapter1 = mock(LogAdapter::class.java)
`when`(adapter1.isLoggable(DEBUG, null)).thenReturn(false)
val adapter2 = mock(LogAdapter::class.java)
`when`(adapter2.isLoggable(DEBUG, null)).thenReturn(true)
printer.addAdapter(adapter1)
printer.addAdapter(adapter2)
printer.d("message")
verify(adapter1, never()).log(DEBUG, null, "message")
verify(adapter2).log(DEBUG, null, "message")
}
@Test fun logWithoutMessageAndThrowable() {
printer.log(DEBUG, null, null, null)
verify(adapter).log(DEBUG, null, "Empty/NULL log message")
}
@Test fun logWithOnlyThrowableWithoutMessage() {
val throwable = Throwable("exception")
printer.log(DEBUG, null, null, throwable)
verify(adapter).log(eq(DEBUG), isNull(String::class.java), contains("java.lang.Throwable: exception"))
}
} | apache-2.0 | 422fa5a278c52559f0a63a9cd296cb75 | 22.100418 | 121 | 0.648007 | 3.454318 | false | true | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/misc/CurlImportActivity.kt | 1 | 2873 | package ch.rmy.android.http_shortcuts.activities.misc
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import ch.rmy.android.framework.extensions.consume
import ch.rmy.android.framework.extensions.createIntent
import ch.rmy.android.framework.extensions.doOnTextChanged
import ch.rmy.android.framework.extensions.focus
import ch.rmy.android.framework.extensions.getSerializable
import ch.rmy.android.framework.ui.BaseActivityResultContract
import ch.rmy.android.framework.ui.BaseIntentBuilder
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.BaseActivity
import ch.rmy.android.http_shortcuts.databinding.ActivityCurlImportBinding
import ch.rmy.curlcommand.CurlCommand
import ch.rmy.curlcommand.CurlParser
class CurlImportActivity : BaseActivity() {
private var commandEmpty = true
set(value) {
if (field != value) {
field = value
invalidateOptionsMenu()
}
}
private lateinit var binding: ActivityCurlImportBinding
override fun onCreated(savedState: Bundle?) {
binding = applyBinding(ActivityCurlImportBinding.inflate(layoutInflater))
setTitle(R.string.title_curl_import)
binding.curlImportCommand.doOnTextChanged { text ->
commandEmpty = text.isEmpty()
}
}
override fun onResume() {
super.onResume()
binding.curlImportCommand.focus()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.curl_import_activity_menu, menu)
menu.findItem(R.id.action_create_from_curl).isVisible = !commandEmpty
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.action_create_from_curl -> consume { startImport() }
else -> super.onOptionsItemSelected(item)
}
private fun startImport() {
val commandString = binding.curlImportCommand.text.toString()
val command = CurlParser.parse(commandString)
setResult(
Activity.RESULT_OK,
ImportFromCurl.createResult(command),
)
finish()
}
override val navigateUpIcon = R.drawable.ic_clear
object ImportFromCurl : BaseActivityResultContract<IntentBuilder, CurlCommand?>(::IntentBuilder) {
private const val EXTRA_CURL_COMMAND = "curl_command"
override fun parseResult(resultCode: Int, intent: Intent?): CurlCommand? =
intent?.getSerializable(EXTRA_CURL_COMMAND)
fun createResult(command: CurlCommand): Intent =
createIntent {
putExtra(EXTRA_CURL_COMMAND, command)
}
}
class IntentBuilder : BaseIntentBuilder(CurlImportActivity::class)
}
| mit | cc3f1f84bac2ca942291153d8a396e0e | 32.8 | 102 | 0.707971 | 4.538705 | false | false | false | false |
Darkyenus/FountainSimulator | src/main/kotlin/com/darkyen/Util.kt | 1 | 2141 | @file:Suppress("unused")
package com.darkyen
/**
*
*/
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.utils.ByteArray as Bytes
import com.badlogic.gdx.utils.IntArray as Ints
typealias Objects<T> = com.badlogic.gdx.utils.Array<T>
typealias Floats = com.badlogic.gdx.utils.FloatArray
typealias Bytes = com.badlogic.gdx.utils.ByteArray
typealias Ints = com.badlogic.gdx.utils.IntArray
typealias Shorts = com.badlogic.gdx.utils.ShortArray // (not Oxhorn's)
typealias Index = Int
inline fun <T> Objects<T>.forEach(action:(T) -> Unit) {
val items = this.items
for (i in 0 until this.size) {
action(items[i])
}
}
inline fun Ints.forEach(action:(Int) -> Unit) {
val items = this.items
for (i in 0 until this.size) {
action(items[i])
}
}
inline fun Floats.forEach(action:(Float) -> Unit) {
val items = this.items
for (i in 0 until this.size) {
action(items[i])
}
}
inline fun Bytes.forEach(action:(Byte) -> Unit) {
val items = this.items
for (i in 0 until this.size) {
action(items[i])
}
}
inline fun Ints.forEachIndexed(action:(Int, Index) -> Unit) {
val items = this.items
for (i in 0 until this.size) {
action(items[i], i)
}
}
inline fun Floats.forEachIndexed(action:(Float, Index) -> Unit) {
val items = this.items
for (i in 0 until this.size) {
action(items[i], i)
}
}
inline fun Bytes.forEachIndexed(action:(Byte, Index) -> Unit) {
val items = this.items
for (i in 0 until this.size) {
action(items[i], i)
}
}
/** Returns a re-mapped float value from inRange to outRange. */
fun map(value: Float, inRangeStart: Float, inRangeEnd: Float, outRangeStart: Float, outRangeEnd: Float): Float {
return outRangeStart + (outRangeEnd - outRangeStart) * ((value - inRangeStart) / (inRangeEnd - inRangeStart))
}
fun toString(p:Pixmap):CharSequence {
return "Pixmap "+p.width+" x "+p.height+" in "+p.format
}
fun toString(t: Texture):CharSequence {
return "Texture "+ t.width+" x "+ t.height+" with "+ t.textureData?.type+" data"
} | mit | b387ebad9af2ddb22af07d02fb07cfaa | 25.444444 | 113 | 0.660439 | 3.278714 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/webkit/WebViewAutoScrollManager.kt | 1 | 2229 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.webkit
import android.os.Handler
import android.os.Looper
import jp.hazuki.yuzubrowser.webview.CustomWebView
class WebViewAutoScrollManager {
private var isRunning = false
private var init = false
private var scrollSpeed: Double = 0.0
private var scrollY: Double = 0.0
private var scrollMax: Int = 0
private val handler: Handler = Handler(Looper.getMainLooper())
private var onStopListener: (() -> Unit)? = null
fun start(webView: CustomWebView, speed: Int) {
scrollSpeed = speed * 0.01
isRunning = true
init = true
scrollY = webView.computeVerticalScrollOffsetMethod().toDouble()
scrollMax = webView.computeVerticalScrollRangeMethod() - webView.computeVerticalScrollExtentMethod()
handler.postDelayed({ init = false }, 200)
val runScroll = Runnable {
scrollY += scrollSpeed
if (scrollY > scrollMax) {
scrollY = scrollMax.toDouble()
stop()
}
webView.scrollTo(webView.webScrollX, scrollY.toInt())
}
Thread(Runnable {
while (isRunning) {
try {
Thread.sleep(10)
} catch (e: InterruptedException) {
e.printStackTrace()
}
handler.post(runScroll)
}
}).start()
}
fun stop() {
if (init) return
isRunning = false
onStopListener?.invoke()
}
fun setOnStopListener(listener: (() -> Unit)?) {
onStopListener = listener
}
}
| apache-2.0 | 88dbfd5289fcaac08fee4419771d378f | 29.534247 | 108 | 0.624495 | 4.672956 | false | false | false | false |
square/sqldelight | sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/intentions/QualifyColumnNameIntention.kt | 1 | 2500 | package com.squareup.sqldelight.intellij.intentions
import com.alecstrong.sql.psi.core.psi.SqlColumnExpr
import com.alecstrong.sql.psi.core.psi.SqlColumnName
import com.alecstrong.sql.psi.core.psi.SqlTypes
import com.intellij.codeInsight.intention.BaseElementAtCaretIntentionAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.psi.PsiElement
import com.intellij.psi.util.elementType
import com.intellij.psi.util.parentOfType
class QualifyColumnNameIntention : BaseElementAtCaretIntentionAction() {
override fun getFamilyName(): String {
return INTENTIONS_FAMILY_NAME_REFACTORINGS
}
override fun getText(): String {
return "Qualify identifier"
}
override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean {
val columnName = element.parentOfType<SqlColumnName>(true) ?: return false
return columnName.parent is SqlColumnExpr && columnName.prevSibling.elementType != SqlTypes.DOT
}
override fun invoke(project: Project, editor: Editor, element: PsiElement) {
val columnName = element.parentOfType<SqlColumnName>(true) ?: return
val columnText = columnName.text
val tableNamesOrAliases = columnName.queryAvailable(columnName)
.asSequence()
.filter { result -> result.table != null }
.flatMap { result ->
result.columns.filter { column -> column.element.textMatches(columnText) }
.map { column -> column.element to result.table!! }
}
.groupBy({ it.first }, { it.second })
.values
.flatten()
.map { it.text }
.distinct()
if (tableNamesOrAliases.isEmpty()) {
return
}
val document = editor.document
val columnRange = document.createRangeMarker(columnName.textRange)
val callback = { qualifier: String ->
WriteCommandAction.runWriteCommandAction(project) {
document.replaceString(
columnRange.startOffset, columnRange.endOffset, "$qualifier.$columnText"
)
}
}
if (tableNamesOrAliases.size == 1) {
callback(tableNamesOrAliases.first())
} else {
JBPopupFactory.getInstance()
.createPopupChooserBuilder(tableNamesOrAliases)
.setMovable(true)
.setResizable(true)
.setItemChosenCallback(callback)
.createPopup()
.showInBestPositionFor(editor)
}
}
}
| apache-2.0 | 42bafbc052bba4c565dd0bb572fc79d9 | 33.722222 | 99 | 0.7196 | 4.528986 | false | false | false | false |
d9n/trypp.support | src/test/code/trypp/support/time/DurationTest.kt | 1 | 3230 | package trypp.support.time
import com.google.common.truth.Truth.assertThat
import org.testng.annotations.Test
class DurationTest {
@Test fun testFromSeconds() {
val duration = Duration.ofSeconds(90f)
assertThat(duration.getMinutes()).isWithin(0f).of(1.5f)
assertThat(duration.getSeconds()).isWithin(0f).of(90f)
assertThat(duration.getMilliseconds()).isWithin(0f).of(90000f)
}
@Test fun testFromMinutes() {
val duration = Duration.ofMinutes(1.5f)
assertThat(duration.getMinutes()).isWithin(0f).of(1.5f)
assertThat(duration.getSeconds()).isWithin(0f).of(90f)
assertThat(duration.getMilliseconds()).isWithin(0f).of(90000f)
}
@Test fun testFromMilliseconds() {
val duration = Duration.ofMilliseconds(90000f)
assertThat(duration.getMinutes()).isWithin(0f).of(1.5f)
assertThat(duration.getSeconds()).isWithin(0f).of(90f)
assertThat(duration.getMilliseconds()).isWithin(0f).of(90000f)
}
@Test fun testFromOtherDuration() {
val otherDuration = Duration.ofSeconds(9000f)
val duration = Duration.of(otherDuration)
assertThat(duration.getSeconds()).isWithin(0f).of(9000f)
}
@Test fun testEmptyDuration() {
val duration = Duration.zero()
assertThat(duration.getSeconds()).isWithin(0f).of(0f)
assertThat(duration.isZero).isTrue()
}
@Test fun testSetMethods() {
val duration = Duration.zero()
duration.setSeconds(3f)
assertThat(duration.getSeconds()).isWithin(0f).of(3f)
duration.setMinutes(4f)
assertThat(duration.getMinutes()).isWithin(0f).of(4f)
duration.setMilliseconds(5f)
assertThat(duration.getMilliseconds()).isWithin(0f).of(5f)
val otherDuration = Duration.ofSeconds(6f)
duration.setFrom(otherDuration)
assertThat(duration.getSeconds()).isWithin(0f).of(6f)
duration.setZero()
assertThat(duration.getSeconds()).isWithin(0f).of(0f)
}
@Test fun testAddMethods() {
val duration = Duration.zero()
duration.addSeconds(1f)
assertThat(duration.getSeconds()).isWithin(0f).of(1f)
duration.addMilliseconds(500f)
assertThat(duration.getSeconds()).isWithin(0f).of(1.5f)
duration.addMinutes(2f)
assertThat(duration.getSeconds()).isWithin(.1f).of(121.5f)
val otherDuration = Duration.ofMilliseconds(1500f)
duration.add(otherDuration)
assertThat(duration.getSeconds()).isWithin(.1f).of(123f)
}
@Test fun testSubtractMethods() {
val duration = Duration.ofMinutes(10f)
duration.subtract(Duration.ofMinutes(3f))
assertThat(duration.getMinutes()).isWithin(0f).of(7f)
duration.subtractMinutes(5f)
assertThat(duration.getMinutes()).isWithin(0f).of(2f)
duration.subtractSeconds(30f)
assertThat(duration.getMinutes()).isWithin(0f).of(1.5f)
duration.subtractMilliseconds(1000f)
assertThat(duration.getMinutes()).isWithin(.1f).of(1.4f)
}
@Test fun settingNegativeDurationBecomesZero() {
assertThat(Duration.ofSeconds(-5f).getSeconds()).isWithin(0f).of(0f)
}
} | mit | fa8d1d2aa2e22899c5b8e7968e05be96 | 30.368932 | 76 | 0.666254 | 3.92944 | false | true | false | false |
grote/Transportr | app/src/main/java/de/grobox/transportr/networks/RegionViewHolder.kt | 1 | 3425 | /*
* Transportr
*
* Copyright (c) 2013 - 2021 Torsten Grote
*
* 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 de.grobox.transportr.networks
import android.os.Build
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import de.grobox.transportr.R
import de.grobox.transportr.networks.TransportNetwork.Status.ALPHA
import de.grobox.transportr.networks.TransportNetwork.Status.STABLE
internal abstract class RegionViewHolder<in Reg : Region>(v: View) : RecyclerView.ViewHolder(v) {
protected val name: TextView = v.findViewById(R.id.name)
open fun bind(region: Reg, expanded: Boolean) {
name.text = region.getName(name.context)
}
}
internal class TransportNetworkViewHolder(v: View) : RegionViewHolder<TransportNetwork>(v) {
private val logo: ImageView = v.findViewById(R.id.logo)
private val desc: TextView = v.findViewById(R.id.desc)
private val status: TextView = v.findViewById(R.id.status)
override fun bind(region: TransportNetwork, expanded: Boolean) {
super.bind(region, expanded)
logo.setImageResource(region.logo)
desc.text = region.getDescription(desc.context)
if (region.status == STABLE) {
status.visibility = GONE
} else {
if (region.status == ALPHA) {
status.text = status.context.getString(R.string.alpha)
} else {
status.text = status.context.getString(R.string.beta)
}
status.visibility = VISIBLE
}
}
}
internal abstract class ExpandableRegionViewHolder<in Reg : Region>(v: View) : RegionViewHolder<Reg>(v) {
private val chevron: ImageView = v.findViewById(R.id.chevron)
override fun bind(region: Reg, expanded: Boolean) {
super.bind(region, expanded)
if (expanded)
chevron.rotation = 0f
else
chevron.rotation = 180f
}
}
internal class CountryViewHolder(v: View) : ExpandableRegionViewHolder<Country>(v) {
private val flag: TextView = v.findViewById(R.id.flag)
override fun bind(region: Country, expanded: Boolean) {
super.bind(region, expanded)
if (Build.VERSION.SDK_INT >= 21) {
flag.text = region.flag
flag.visibility = VISIBLE
} else {
flag.visibility = GONE
}
}
}
internal class ContinentViewHolder(v: View) : ExpandableRegionViewHolder<Continent>(v) {
private val contour: ImageView = v.findViewById(R.id.contour)
override fun bind(region: Continent, expanded: Boolean) {
super.bind(region, expanded)
contour.setImageResource(region.contour)
}
}
| gpl-3.0 | a77e3ec4b991d48f913423390ea01751 | 34.677083 | 105 | 0.683796 | 4.043684 | false | false | false | false |
yuttadhammo/BodhiTimer | app/src/androidTest/java/org/yuttadhammo/BodhiTimer/TimerActivityTest.kt | 1 | 3136 | package org.yuttadhammo.BodhiTimer
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import tools.fastlane.screengrab.Screengrab
@LargeTest
@RunWith(AndroidJUnit4::class)
class TimerActivityTest {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(TimerActivity::class.java)
@Test
fun timerActivityTest() {
Screengrab.screenshot("main")
val appCompatImageButton = onView(
allOf(
withId(R.id.setButton), withContentDescription("Set"),
childAtPosition(
allOf(
withId(R.id.mainLayout),
childAtPosition(
withId(android.R.id.content),
0
)
),
4
),
isDisplayed()
)
)
appCompatImageButton.perform(click())
//val gallery = onView()
val button = onView(
allOf(
withId(R.id.btnOk), withText("OK"),
childAtPosition(
allOf(
withId(R.id.button_cont),
childAtPosition(
withId(R.id.container),
6
)
),
2
)
)
)
button.perform(scrollTo(), click())
val textView = onView(
allOf(
withId(R.id.text_top),
withParent(
allOf(
withId(R.id.mainLayout),
withParent(withId(android.R.id.content))
)
),
isDisplayed()
)
)
textView.check(matches(withText("0")))
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int
): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
| gpl-3.0 | 9fbbf402ce4c3e57bab30fced919eab3 | 29.153846 | 80 | 0.53986 | 5.444444 | false | true | false | false |
eurofurence/ef-app_android | app/src/main/kotlin/org/eurofurence/connavigator/ui/activities/NavActivity.kt | 1 | 13001 | package org.eurofurence.connavigator.ui.activities
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Browser
import android.view.Gravity
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.NavHost
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.onNavDestinationSelected
import androidx.navigation.ui.setupWithNavController
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.google.android.material.navigation.NavigationView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposables
import org.eurofurence.connavigator.BuildConfig
import org.eurofurence.connavigator.R
import org.eurofurence.connavigator.database.HasDb
import org.eurofurence.connavigator.database.lazyLocateDb
import org.eurofurence.connavigator.events.ResetReceiver
import org.eurofurence.connavigator.preferences.AnalyticsPreferences
import org.eurofurence.connavigator.preferences.AuthPreferences
import org.eurofurence.connavigator.preferences.BackgroundPreferences
import org.eurofurence.connavigator.preferences.RemotePreferences
import org.eurofurence.connavigator.services.AnalyticsService
import org.eurofurence.connavigator.util.DatetimeProxy
import org.eurofurence.connavigator.util.extensions.setFAIcon
import org.eurofurence.connavigator.util.v2.plus
import org.eurofurence.connavigator.workers.DataUpdateWorker
import org.jetbrains.anko.*
import org.jetbrains.anko.appcompat.v7.toolbar
import org.jetbrains.anko.design.navigationView
import org.jetbrains.anko.support.v4.drawerLayout
import org.joda.time.DateTime
import org.joda.time.Days
class NavActivity : AppCompatActivity(), NavHost, AnkoLogger, HasDb {
override fun getNavController() = navFragment.findNavController()
internal val ui = NavUi()
override val db by lazyLocateDb()
var subscriptions = Disposables.empty()
val navFragment by lazy { NavHostFragment() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
info { "Starting Nav Activity" }
ui.setContentView(this)
navFragment.setInitialSavedState(savedInstanceState?.getParcelable("fragment"))
supportFragmentManager.beginTransaction()
.replace(R.id.nav_graph, navFragment, "navFragment")
.setPrimaryNavigationFragment(navFragment)
.runOnCommit {
navController.restoreState(savedInstanceState?.getBundle("nav"))
navController.setGraph(R.navigation.nav_graph)
}
.commit()
ui.navTitle.text = RemotePreferences.eventTitle
ui.navSubtitle.text = RemotePreferences.eventSubTitle
// Calculate the days between, using the current time.
val firstDay = DateTime(RemotePreferences.nextConStart)
val days = Days.daysBetween(DatetimeProxy.now(), DateTime(firstDay)).days
// On con vs. before con. This should be updated on day changes
if (days <= 0)
ui.navDays.text = getString(R.string.misc_current_day, 1 - days)
else
ui.navDays.text = getString(R.string.misc_days_left, days)
addNavDrawerIcons()
subscriptions += RemotePreferences
.observer
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
updateNavCountdown()
}
subscriptions += AnalyticsPreferences
.observer
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
AnalyticsService.updateSettings()
}
subscriptions += AuthPreferences
.updated
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
updateLoginMenuItem()
}
subscriptions += BackgroundPreferences
.observer
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
setMenuPermissions()
}.apply {
// manually apply menu permissions at least once
setMenuPermissions()
}
WorkManager.getInstance(this).getWorkInfosForUniqueWorkLiveData(DataUpdateWorker.TAG)
.observe(this, androidx.lifecycle.Observer { workInfo ->
if (workInfo != null && workInfo.all { it.state == WorkInfo.State.SUCCEEDED }) {
db.observer.onNext(db)
}
})
info { "Inserted Nav Fragment" }
}
private fun setMenuPermissions() {
if (!BackgroundPreferences.hasLoadedOnce) {
ui.drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
} else {
ui.drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
}
}
private fun updateNavCountdown() {
// Set up dates to EF
// Manually set the first date, since the database is not updated with EF 22
val firstDay = DateTime(RemotePreferences.nextConStart)
// Calculate the days between, using the current time. Todo: timezones
val days = Days.daysBetween(DatetimeProxy.now(), DateTime(firstDay)).days
ui.navTitle.text = RemotePreferences.eventTitle
ui.navSubtitle.text = RemotePreferences.eventSubTitle
// On con vs. before con. This should be updated on day changes
if (days <= 0)
ui.navDays.text = "Day ${1 - days}"
else
ui.navDays.text = "Only $days days left!"
}
private fun updateLoginMenuItem() {
// Find login item, assign new text.
ui.nav.menu.findItem(R.id.navLogin)?.let {
if (AuthPreferences.isLoggedIn)
it.title = "Login details"
else
it.title = "Login"
}
}
private fun addNavDrawerIcons() {
ui.nav.inflateMenu(R.menu.nav_drawer)
ui.nav.menu.apply {
// Main
this.setFAIcon(this@NavActivity, R.id.navHome, R.string.fa_home_solid)
this.setFAIcon(this@NavActivity, R.id.navInfoList, R.string.fa_info_solid)
this.setFAIcon(this@NavActivity, R.id.navEventList, R.string.fa_calendar)
this.setFAIcon(this@NavActivity, R.id.navDealerList, R.string.fa_shopping_cart_solid)
this.setFAIcon(this@NavActivity, R.id.navMapList, R.string.fa_map)
// Personal
this.setFAIcon(this@NavActivity, R.id.navLogin, R.string.fa_user_circle)
this.setFAIcon(this@NavActivity, R.id.navMessages, R.string.fa_envelope)
this.setFAIcon(this@NavActivity, R.id.navFursuitGames, R.string.fa_paw_solid)
this.setFAIcon(this@NavActivity, R.id.navAdditionalServices, R.string.fa_book_open_solid)
// Web
this.setFAIcon(this@NavActivity, R.id.navWebTwitter, R.string.fa_twitter, isBrand = true)
this.setFAIcon(this@NavActivity, R.id.navWebSite, R.string.fa_globe_solid)
// App Management
this.setFAIcon(this@NavActivity, R.id.navDevReload, R.string.fa_cloud_download_alt_solid)
this.setFAIcon(this@NavActivity, R.id.navDevClear, R.string.fa_trash_solid)
this.setFAIcon(this@NavActivity, R.id.navSettings, R.string.fa_cog_solid)
this.setFAIcon(this@NavActivity, R.id.navAbout, R.string.fa_hands_helping_solid)
}
}
override fun onResume() {
info { "setting up nav toolbar" }
val appbarConfig = AppBarConfiguration(navController.graph, ui.drawer)
ui.bar.setupWithNavController(navController, appbarConfig)
ui.nav.setNavigationItemSelectedListener {
ui.drawer.closeDrawers()
onOptionsItemSelected(it)
}
super.onResume()
}
override fun onDestroy() {
super.onDestroy()
subscriptions.dispose()
subscriptions = Disposables.empty()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
info { "Selecting item" }
// Exit if we're either UNINITIALIZED or when there is no data. Make an exception for the settings and update action
if (!BackgroundPreferences.hasLoadedOnce && !listOf(R.id.navSettings, R.id.navDevReload).contains(item.itemId)
) {
longToast("Please wait until we've completed our initial fetch of data")
return true
}
return when (item.itemId) {
R.id.navDevReload -> DataUpdateWorker.execute(this, true).let { true }
R.id.navDevClear -> alert(getString(R.string.clear_app_cache), getString(R.string.clear_database)) {
yesButton { ResetReceiver().clearData(this@NavActivity) }
noButton { }
}.show().let { true }
R.id.navMessages -> navigateToMessages()
R.id.navWebSite -> browse("https://eurofurence.org")
R.id.navWebTwitter -> browse("https://twitter.com/eurofurence")
R.id.navFursuitGames -> navigateToFursuitGames()
R.id.navAdditionalServices -> navigateToAdditionalServices()
else -> item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item)
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putBundle("nav", navController.saveState())
outState.putParcelable("fragment", supportFragmentManager.saveFragmentInstanceState(navFragment))
super.onSaveInstanceState(outState)
}
private fun navigateToMessages(): Boolean {
if (AuthPreferences.isLoggedIn) {
navController.navigate(R.id.navMessageList)
} else {
longToast("You are not logged in yet!")
navController.navigate(R.id.navLogin)
}
return true
}
private fun navigateToFursuitGames(): Boolean {
val url = "https://app.eurofurence.org/${BuildConfig.CONVENTION_IDENTIFIER}/companion/#/login?embedded=false&returnPath=/collect&token=${AuthPreferences.tokenOrEmpty()}"
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(url)
putExtra(Browser.EXTRA_APPLICATION_ID, BuildConfig.CONVENTION_IDENTIFIER)
}
startActivity(intent)
return true
}
private fun navigateToAdditionalServices(): Boolean {
val url = "https://app.eurofurence.org/${BuildConfig.CONVENTION_IDENTIFIER}/companion/#/login?embedded=false&returnPath=/&token=${AuthPreferences.tokenOrEmpty()}"
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(url)
putExtra(Browser.EXTRA_APPLICATION_ID, BuildConfig.CONVENTION_IDENTIFIER)
}
startActivity(intent)
return true
}
}
internal class NavUi : AnkoComponent<NavActivity> {
lateinit var bar: Toolbar
lateinit var drawer: DrawerLayout
lateinit var nav: NavigationView
lateinit var header: View
val navDays get() = header.findViewById<TextView>(R.id.navDays)
val navTitle get() = header.findViewById<TextView>(R.id.navTitle)
val navSubtitle get() = header.findViewById<TextView>(R.id.navSubTitle)
override fun createView(ui: AnkoContext<NavActivity>) = with(ui) {
drawerLayout {
drawer = this
frameLayout {
backgroundResource = R.color.backgroundGrey
verticalLayout {
bar = toolbar {
backgroundResource = R.color.primaryDark
setTitleTextColor(ContextCompat.getColor(context, R.color.textWhite))
setSubtitleTextColor(ContextCompat.getColor(context, R.color.textWhite))
id = R.id.toolbar
}
frameLayout() {
id = R.id.nav_graph
}.lparams(matchParent, matchParent)
}
}.lparams(matchParent, matchParent)
nav = navigationView {
header = inflateHeaderView(R.layout.layout_nav_header)
}.lparams(wrapContent, matchParent) {
gravity = Gravity.START
}
}
}
} | mit | 27992ae57cf3131713a7ecae12e52991 | 38.761755 | 177 | 0.640028 | 4.729356 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/command/payment/PaymentCreateCommand.kt | 1 | 5090 | /*
* Copyright 2021 Ren Binden
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.payments.bukkit.command.payment
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.economy.bukkit.currency.RPKCurrencyName
import com.rpkit.economy.bukkit.currency.RPKCurrencyService
import com.rpkit.payments.bukkit.RPKPaymentsBukkit
import com.rpkit.payments.bukkit.group.RPKPaymentGroupImpl
import com.rpkit.payments.bukkit.group.RPKPaymentGroupName
import com.rpkit.payments.bukkit.group.RPKPaymentGroupService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import java.time.Duration
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit.MILLIS
/**
* Payment create command.
* Creates a payment group.
*/
class PaymentCreateCommand(private val plugin: RPKPaymentsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.payments.command.payment.create")) {
sender.sendMessage(plugin.messages["no-permission-payment-create"])
return true
}
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["payment-create-usage"])
return true
}
val paymentGroupService = Services[RPKPaymentGroupService::class.java]
if (paymentGroupService == null) {
sender.sendMessage(plugin.messages["no-payment-group-service"])
return true
}
val currencyService = Services[RPKCurrencyService::class.java]
if (currencyService == null) {
sender.sendMessage(plugin.messages["no-currency-service"])
return true
}
val currencyName = plugin.config.getString("payment-groups.defaults.currency")
val currency = if (currencyName == null)
currencyService.defaultCurrency
else
currencyService.getCurrency(RPKCurrencyName(currencyName))
val name = args.joinToString(" ")
paymentGroupService.getPaymentGroup(RPKPaymentGroupName(name)).thenAccept getExistingPaymentGroup@{ existingPaymentGroup ->
if (existingPaymentGroup != null) {
sender.sendMessage(plugin.messages["payment-create-invalid-name-already-exists"])
return@getExistingPaymentGroup
}
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return@getExistingPaymentGroup
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return@getExistingPaymentGroup
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages["no-character-service"])
return@getExistingPaymentGroup
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return@getExistingPaymentGroup
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
sender.sendMessage(plugin.messages["no-character"])
return@getExistingPaymentGroup
}
val paymentGroup = RPKPaymentGroupImpl(
plugin,
name = RPKPaymentGroupName(name),
amount = plugin.config.getInt("payment-groups.defaults.amount"),
currency = currency,
interval = Duration.of(plugin.config.getLong("payment-groups.defaults.interval"), MILLIS),
lastPaymentTime = LocalDateTime.now(),
balance = 0
)
paymentGroupService.addPaymentGroup(paymentGroup).thenRun {
paymentGroup.addOwner(character).thenRun {
sender.sendMessage(plugin.messages["payment-create-valid"])
}
}
}
return true
}
}
| apache-2.0 | bb91139026b8a6cf1d22ed09fc79f289 | 44.044248 | 131 | 0.673477 | 5.07984 | false | false | false | false |
AsynkronIT/protoactor-kotlin | examples/src/main/kotlin/actor/proto/examples/remotebenchmark/Node1.kt | 1 | 2165 | package actor.proto.examples.remotebenchmark
import actor.proto.Actor
import actor.proto.Context
import actor.proto.PID
import actor.proto.examples.remotebenchmark.Messages.Ping
import actor.proto.examples.remotebenchmark.Messages.Pong
import actor.proto.fromProducer
import actor.proto.remote.Remote
import actor.proto.remote.Serialization.registerFileDescriptor
import actor.proto.requestAwait
import actor.proto.send
import actor.proto.spawn
import kotlinx.coroutines.runBlocking
import java.lang.System.currentTimeMillis
import java.time.Duration
import java.util.concurrent.CountDownLatch
fun main(args: Array<String>) {
registerFileDescriptor(Messages.getDescriptor())
Remote.start("127.0.0.1", 0)
run()
readLine()
run()
readLine()
run()
}
private fun run() {
val messageCount = 1_000_000
val wg = CountDownLatch(1)
val props = fromProducer { LocalActor(0, messageCount, wg) }
val pid: PID = spawn(props)
val remote = PID("127.0.0.1:12000", "remote")
val startRemote = Messages.StartRemote.newBuilder().setSender(pid).build()
runBlocking {
requestAwait<Messages.Start>(remote, startRemote, Duration.ofSeconds(2))
}
val start = currentTimeMillis()
println("Starting to send")
val msg: Ping = Ping.newBuilder().build()
for (i in 0 until messageCount) {
send(remote, msg)
}
wg.await()
val elapsed = currentTimeMillis() - start
println("Elapsed $elapsed")
val t: Double = messageCount * 2.0 / elapsed * 1000
println("Throughput $t msg / sec")
}
class LocalActor(count: Int, messageCount: Int, wg: CountDownLatch) : Actor {
private var _count: Int = count
private val _messageCount: Int = messageCount
private val _wg: CountDownLatch = wg
override suspend fun Context.receive(msg: Any) {
when (msg) {
is Pong -> {
_count++
if (_count % 50_000 == 0) {
println(_count)
}
if (_count == _messageCount) {
_wg.countDown()
}
}
else -> println(msg)
}
}
}
| apache-2.0 | 7e447404581379bab069629ee9699d3f | 27.866667 | 80 | 0.650346 | 4.039179 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/util/Notifications.kt | 1 | 2939 | @file:Suppress("MemberVisibilityCanBePrivate")
package cn.yiiguxing.plugin.translate.util
import com.intellij.notification.Notification
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.project.Project
import javax.swing.event.HyperlinkEvent
object Notifications {
const val DEFAULT_NOTIFICATION_GROUP_ID = "Translation Plugin"
fun showErrorNotification(
project: Project?,
title: String,
content: String,
vararg actions: AnAction
) {
showErrorNotification(DEFAULT_NOTIFICATION_GROUP_ID, project, title, content, actions = actions)
}
fun showErrorNotification(
groupId: String,
project: Project?,
title: String,
content: String,
vararg actions: AnAction
) {
NotificationGroupManager.getInstance()
.getNotificationGroup(groupId)
.createNotification(content, NotificationType.ERROR)
.setTitle(title)
// actions的折叠是从左往右折叠的
.addActions(actions.toList() as Collection<AnAction>)
.show(project)
}
fun showNotification(
title: String,
message: String,
type: NotificationType,
project: Project? = null,
groupId: String = DEFAULT_NOTIFICATION_GROUP_ID
) {
NotificationGroupManager.getInstance()
.getNotificationGroup(groupId)
.createNotification(message, type)
.setTitle(title)
.show(project)
}
fun showInfoNotification(
title: String,
message: String,
project: Project? = null,
groupId: String = DEFAULT_NOTIFICATION_GROUP_ID
) {
showNotification(title, message, NotificationType.INFORMATION, project, groupId)
}
fun showWarningNotification(
title: String,
message: String,
project: Project? = null,
groupId: String = DEFAULT_NOTIFICATION_GROUP_ID
) {
showNotification(title, message, NotificationType.WARNING, project, groupId)
}
fun showErrorNotification(
title: String,
message: String,
project: Project? = null,
groupId: String = DEFAULT_NOTIFICATION_GROUP_ID
) {
showNotification(title, message, NotificationType.ERROR, project, groupId)
}
open class UrlOpeningListener(expireNotification: Boolean = true) :
NotificationListener.UrlOpeningListener(expireNotification) {
override fun hyperlinkActivated(notification: Notification, hyperlinkEvent: HyperlinkEvent) {
if (!Hyperlinks.handleDefaultHyperlinkActivated(hyperlinkEvent)) {
super.hyperlinkActivated(notification, hyperlinkEvent)
}
}
}
} | mit | 1f81010a8d32d1694d6105affef50cfe | 30.376344 | 104 | 0.668838 | 5.09965 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/tts/GoogleTTSPlayer.kt | 1 | 9163 | package cn.yiiguxing.plugin.translate.tts
import cn.yiiguxing.plugin.translate.message
import cn.yiiguxing.plugin.translate.trans.Lang
import cn.yiiguxing.plugin.translate.trans.google.googleReferer
import cn.yiiguxing.plugin.translate.trans.google.tk
import cn.yiiguxing.plugin.translate.trans.google.userAgent
import cn.yiiguxing.plugin.translate.util.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.util.io.HttpRequests
import javazoom.jl.decoder.Bitstream
import javazoom.spi.mpeg.sampled.convert.DecodedMpegAudioInputStream
import javazoom.spi.mpeg.sampled.convert.MpegFormatConversionProvider
import javazoom.spi.mpeg.sampled.file.MpegAudioFileReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.io.SequenceInputStream
import java.lang.StrictMath.round
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLHandshakeException
import javax.sound.sampled.*
/**
* Google TTS player.
*/
class GoogleTTSPlayer(
project: Project?,
private val text: String,
private val lang: Lang,
private val completeListener: ((TTSPlayer) -> Unit)? = null
) : TTSPlayer {
private val playTask: PlayTask = PlayTask(project).apply {
cancelText = "stop"
cancelTooltipText = "stop"
}
private val playController: ProgressIndicator
override val disposable: Disposable
override val isPlaying: Boolean
get() {
checkThread()
return playController.isRunning
}
@Volatile
private var started = false
private var duration = 0
private val playlist: List<String> by lazy {
text.splitSentence(MAX_TEXT_LENGTH).let {
it.mapIndexed { index, sentence ->
@Suppress("SpellCheckingInspection")
UrlBuilder(TTS_API_URL)
.addQueryParameter("client", "gtx")
.addQueryParameter("ie", "UTF-8")
.addQueryParameter("tl", lang.code)
.addQueryParameter("total", it.size.toString())
.addQueryParameter("idx", index.toString())
.addQueryParameter("textlen", sentence.length.toString())
.addQueryParameter("tk", sentence.tk())
.addQueryParameter("q", sentence)
.build()
}
}
}
init {
playController = BackgroundableProcessIndicator(playTask).apply { isIndeterminate = true }
disposable = playController
}
private inner class PlayTask(project: Project?) : Task.Backgroundable(project, "TTS") {
override fun run(indicator: ProgressIndicator) {
play(indicator)
}
override fun onThrowable(error: Throwable) {
if (error is HttpRequests.HttpStatusException && error.statusCode == 404) {
LOGGER.w("TTS Error: Unsupported language: ${lang.code}.")
Notifications.showWarningNotification(
"TTS",
message("error.unsupportedLanguage", lang.langName),
project
)
} else {
when (error) {
is SocketException,
is SocketTimeoutException,
is SSLHandshakeException,
is UnknownHostException -> {
Notifications.showErrorNotification(
project,
"TTS",
message("error.network")
)
}
else -> LOGGER.e("TTS Error", error)
}
}
}
override fun onFinished() {
Disposer.dispose(disposable)
completeListener?.invoke(this@GoogleTTSPlayer)
}
}
override fun start() {
checkThread()
check(!started) { "Start with wrong state." }
started = true
ProgressManager.getInstance().runProcessWithProgressAsynchronously(playTask, playController)
}
override fun stop() {
checkThread()
playController.cancel()
}
private fun play(indicator: ProgressIndicator) {
with(indicator) {
checkCanceled()
text = message("tts.progress.downloading")
}
playlist
.map { url ->
indicator.checkCanceled()
LOGGER.i("TTS>>> $url")
HttpRequests.request(url)
.userAgent()
.googleReferer()
.readBytes(indicator)
.let {
ByteArrayInputStream(it).apply { duration += getAudioDuration(it.size) }
}
}
.enumeration()
.let {
SequenceInputStream(it).use { sis ->
indicator.checkCanceled()
sis.asAudioInputStream().rawPlay(indicator)
}
}
}
private fun AudioInputStream.rawPlay(indicator: ProgressIndicator) {
val decodedFormat = format.let {
AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, it.sampleRate, 16, it.channels,
it.channels * 2, it.sampleRate, false
)
}
MpegFormatConversionProvider()
.getAudioInputStream(decodedFormat, this)
.rawPlay(decodedFormat, indicator)
}
private fun AudioInputStream.rawPlay(format: AudioFormat, indicator: ProgressIndicator) {
indicator.apply {
checkCanceled()
fraction = 0.0
isIndeterminate = false
text = message("tts.progress.playing")
}
this as DecodedMpegAudioInputStream
format.openLine()?.run {
start()
@Suppress("ConvertTryFinallyToUseCall") try {
val data = ByteArray(2048)
var bytesRead: Int
while (!indicator.isCanceled) {
bytesRead = read(data, 0, data.size)
if (bytesRead != -1) {
write(data, 0, bytesRead)
val currentTime = properties()["mp3.position.microseconds"] as Long / 1000
indicator.fraction = currentTime.toDouble() / duration.toDouble()
} else {
indicator.fraction = 1.0
break
}
}
drain()
stop()
} finally {
duration = 0
close()
}
}
}
companion object {
private const val TTS_API_URL = "https://translate.googleapis.com/translate_tts"
private val LOGGER = Logger.getInstance(GoogleTTSPlayer::class.java)
private const val MAX_TEXT_LENGTH = 200
val SUPPORTED_LANGUAGES: List<Lang> = listOf(
Lang.CHINESE, Lang.ENGLISH, Lang.CHINESE_TRADITIONAL, Lang.ALBANIAN, Lang.ARABIC, Lang.ESTONIAN,
Lang.ICELANDIC, Lang.POLISH, Lang.BOSNIAN, Lang.AFRIKAANS, Lang.DANISH, Lang.GERMAN, Lang.RUSSIAN,
Lang.FRENCH, Lang.FINNISH, Lang.KHMER, Lang.KOREAN, Lang.DUTCH, Lang.CATALAN, Lang.CZECH, Lang.CROATIAN,
Lang.LATIN, Lang.LATVIAN, Lang.ROMANIAN, Lang.MACEDONIAN, Lang.BENGALI, Lang.NEPALI, Lang.NORWEGIAN,
Lang.PORTUGUESE, Lang.JAPANESE, Lang.SWEDISH, Lang.SERBIAN, Lang.ESPERANTO, Lang.SLOVAK, Lang.SWAHILI,
Lang.TAMIL, Lang.THAI, Lang.TURKISH, Lang.WELSH, Lang.UKRAINIAN, Lang.SPANISH, Lang.GREEK,
Lang.HUNGARIAN, Lang.ARMENIAN, Lang.ITALIAN, Lang.HINDI, Lang.SUNDANESE, Lang.INDONESIAN,
Lang.JAVANESE, Lang.VIETNAMESE
)
private fun checkThread() = checkDispatchThread(GoogleTTSPlayer::class.java)
private fun InputStream.asAudioInputStream(): AudioInputStream =
MpegAudioFileReader().getAudioInputStream(this)
private fun InputStream.getAudioDuration(dataLength: Int): Int {
return try {
@Suppress("SpellCheckingInspection")
round(Bitstream(this).readFrame().total_ms(dataLength))
} catch (e: Throwable) {
LOGGER.error(e)
0
} finally {
reset()
}
}
private fun AudioFormat.openLine(): SourceDataLine? = try {
val info = DataLine.Info(SourceDataLine::class.java, this)
(AudioSystem.getLine(info) as? SourceDataLine)?.apply {
open(this@openLine)
}
} catch (e: Exception) {
LOGGER.w("openLine", e)
null
}
}
} | mit | 1d5c7541730c0fac12242731da16779e | 35.07874 | 116 | 0.584743 | 4.825171 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/ide/formatter/blocks/RustFmtBlock.kt | 1 | 3692 | package org.rust.ide.formatter.blocks
import com.intellij.formatting.*
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.TextRange
import com.intellij.psi.formatter.FormatterUtil
import org.rust.ide.formatter.RustFmtContext
import org.rust.ide.formatter.RustFormattingModelBuilder
import org.rust.ide.formatter.impl.*
import org.rust.lang.core.psi.RustCompositeElementTypes.METHOD_CALL_EXPR
import org.rust.lang.core.psi.RustTokenElementTypes.DOT
class RustFmtBlock(
private val node: ASTNode,
private val alignment: Alignment?,
private val indent: Indent?,
private val wrap: Wrap?,
val ctx: RustFmtContext
) : ASTBlock {
override fun getNode(): ASTNode = node
override fun getTextRange(): TextRange = node.textRange
override fun getAlignment(): Alignment? = alignment
override fun getIndent(): Indent? = indent
override fun getWrap(): Wrap? = wrap
override fun getSubBlocks(): List<Block> = mySubBlocks
private val mySubBlocks: List<Block> by lazy { buildChildren() }
private fun buildChildren(): List<Block> {
val sharedAlignment = when (node.elementType) {
in FN_DECLS -> Alignment.createAlignment()
in PARAMS_LIKE -> ctx.sharedAlignment
METHOD_CALL_EXPR ->
if (node.treeParent.elementType == METHOD_CALL_EXPR)
ctx.sharedAlignment
else
Alignment.createAlignment()
else -> null
}
var metLBrace = false
val alignment = getAlignmentStrategy()
val children = node.getChildren(null)
.filter { !it.isWhitespaceOrEmpty() }
.map { childNode: ASTNode ->
if (node.isFlatBlock && childNode.isBlockDelim(node)) {
metLBrace = true
}
val childCtx = ctx.copy(
metLBrace = metLBrace,
sharedAlignment = sharedAlignment)
RustFormattingModelBuilder.createBlock(
node = childNode,
alignment = alignment.getAlignment(childNode, node, childCtx),
indent = computeIndent(childNode, childCtx),
wrap = null,
ctx = childCtx)
}
// Create fake `.sth` block here, so child indentation will
// be relative to it when it starts from new line.
// In other words: foo().bar().baz() => foo().baz()[.baz()]
// We are using dot as our representative.
// The idea is nearly copy-pasted from Kotlin's formatter.
if (node.elementType == METHOD_CALL_EXPR) {
val dotIndex = children.indexOfFirst { it.node.elementType == DOT }
if (dotIndex != -1) {
val dotBlock = children[dotIndex]
val syntheticBlock = SyntheticRustFmtBlock(
representative = dotBlock,
subBlocks = children.subList(dotIndex, children.size),
ctx = ctx)
return children.subList(0, dotIndex).plusElement(syntheticBlock)
}
}
return children
}
override fun getSpacing(child1: Block?, child2: Block): Spacing? = computeSpacing(child1, child2, ctx)
override fun getChildAttributes(newChildIndex: Int): ChildAttributes =
ChildAttributes(newChildIndent(newChildIndex), null)
override fun isLeaf(): Boolean = node.firstChildNode == null
override fun isIncomplete(): Boolean = myIsIncomplete
private val myIsIncomplete: Boolean by lazy { FormatterUtil.isIncomplete(node) }
override fun toString() = "${node.text} $textRange"
}
| mit | d099bcddd8c1f57480a0e58e822ac2c2 | 38.276596 | 106 | 0.62351 | 4.851511 | false | false | false | false |
ujpv/intellij-rust | src/test/kotlin/org/rust/lang/doc/RustDocRemoveDecorationTest.kt | 1 | 3253 | package org.rust.lang.doc
import com.intellij.openapi.util.text.StringUtil
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.rust.lang.doc.psi.RustDocKind
import org.rust.lang.doc.psi.RustDocKind.*
@RunWith(Parameterized::class)
class RustDocRemoveDecorationTest(
private val kind: RustDocKind,
private val comment: String,
private val content: String
) {
@Test
fun test() {
val commentNorm = StringUtil.convertLineSeparators(comment).trim()
val contentNorm = StringUtil.convertLineSeparators(content).trim()
assertEquals(contentNorm,
kind.removeDecoration(commentNorm.splitToSequence('\n')).joinToString("\n").trim())
}
companion object {
@Parameterized.Parameters(name = "{index}: \"{0}\" → \"{1}\"")
@JvmStatic fun data(): Collection<Array<Any>> = listOf(
arrayOf(InnerEol, "//! foo", "foo"),
arrayOf(OuterEol, "/// foo", "foo"),
arrayOf(OuterEol,
//language=Rust
"""/// foo
/// bar""",
"foo\nbar"),
arrayOf(OuterEol,
//language=Rust
"""/// foo
/// bar""",
"foo\nbar"),
arrayOf(OuterEol,
//language=Rust
"""/// foo
/// ```
/// code {
/// bar
/// }
/// ```""",
"""foo
```
code {
bar
}
```"""),
arrayOf(OuterEol,
//language=Rust
"""/// foo
/// ```
/// code {
/// bar
/// }
/// ```""",
"""foo
```
code {
bar
}
```"""),
arrayOf(OuterBlock,
//language=Rust
"""/** foo
* bar
*/""",
"foo\nbar"),
arrayOf(InnerBlock,
//language=Rust
"""/*! foo
* bar
*/""",
"foo\nbar"),
arrayOf(OuterBlock,
//language=Rust
"""/** foo
* ```
* code {
* bar
* }
* ```
*/""",
"""foo
```
code {
bar
}
```"""),
arrayOf(OuterBlock,
//language=Rust
"""/** foo
* ```
* code {
* bar
* }
* ```
*/""",
"""foo
```
code {
bar
}
```"""),
arrayOf(OuterBlock,
//language=Rust
"/** foo */",
"foo"),
arrayOf(OuterBlock,
//language=Rust
"""/** foo
* bar */""",
"foo\nbar"),
arrayOf(Attr, "foo\nbar", "foo\nbar")
)
}
}
| mit | 3f6c39e680529b1105b468082ebdfb3c | 23.261194 | 95 | 0.359582 | 5.252019 | false | false | false | false |
j2ghz/tachiyomi-extensions | src/all/foolslide/src/eu/kanade/tachiyomi/extension/en/foolslide/FoolSlideFactory.kt | 1 | 6720 | package eu.kanade.tachiyomi.extension.all.foolslide
import android.util.Base64
import com.github.salomonbrys.kotson.get
import com.google.gson.JsonParser
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceFactory
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SManga
import okhttp3.Request
import org.jsoup.nodes.Document
class FoolSlideFactory : SourceFactory {
override fun createSources(): List<Source> = getAllFoolSlide()
}
fun getAllFoolSlide(): List<Source> {
return listOf(
JaminisBox(),
ChampionScans(),
HelveticaScans(),
SenseScans(),
SeaOtterScans(),
KireiCake(),
HiranoMoeScansBureau(),
SilentSky(),
Mangatellers(),
IskultripScans(),
PinkFatale(),
AnataNoMotokare(),
HatigarmScans(),
DeathTollScans(),
DKThias(),
MangaichiScanlationDivision(),
WorldThree(),
TheCatScans(),
AngelicScanlations(),
DokiFansubs(),
YuriIsm(),
AjiaNoScantrad(),
OneTimeScans(),
TsubasaSociety(),
Helheim(),
MangaScouts(),
StormInHeaven(),
Lilyreader(),
MidnightHaven(),
Russification(),
NieznaniReader(),
EvilFlowers(),
NaniScans(),
AkaiYuhiMunTeam()
)
}
class JaminisBox : FoolSlide("Jaimini's Box", "https://jaiminisbox.com", "en", "/reader") {
override fun pageListParse(document: Document): List<Page> {
val doc = document.toString()
val base64Json = doc.substringAfter("JSON.parse(atob(\"").substringBefore("\"));")
val decodeJson = String(Base64.decode(base64Json, Base64.DEFAULT))
val json = JsonParser().parse(decodeJson).asJsonArray
val pages = mutableListOf<Page>()
json.forEach {
pages.add(Page(pages.size, "", it["url"].asString))
}
return pages
}
}
class ChampionScans : FoolSlide("Champion Scans", "http://reader.championscans.com", "en")
class HelveticaScans : FoolSlide("Helvetica Scans", "https://helveticascans.com", "en", "/r")
class SenseScans : FoolSlide("Sense-Scans", "https://sensescans.com", "en", "/reader")
class SeaOtterScans : FoolSlide("Sea Otter Scans", "https://reader.seaotterscans.com", "en")
class KireiCake : FoolSlide("Kirei Cake", "https://reader.kireicake.com", "en")
class HiranoMoeScansBureau : FoolSlide("HiranoMoe Scans Bureau", "https://hiranomoe.com", "en", "/r")
class SilentSky : FoolSlide("Silent Sky", "http://reader.silentsky-scans.net", "en")
class Mangatellers : FoolSlide("Mangatellers", "http://www.mangatellers.gr", "en", "/reader/reader") {
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl$urlModifier/list/$page/", headers)
}
}
class IskultripScans : FoolSlide("Iskultrip Scans", "http://www.maryfaye.net", "en", "/reader")
class PinkFatale : FoolSlide("PinkFatale", "http://manga.pinkfatale.net", "en")
class AnataNoMotokare : FoolSlide("Anata no Motokare", "https://motokare.maos.ca", "en")
// Has other languages too but it is difficult to differentiate between them
class HatigarmScans : FoolSlide("Hatigarm Scans", "http://hatigarmscans.eu", "en", "/hs") {
override fun chapterListSelector() = "div.list-group div.list-group-item:not(.active)"
override val chapterDateSelector = "div.label"
override val chapterUrlSelector = ".title > a"
override fun popularMangaSelector() = ".well > a"
override fun latestUpdatesSelector() = "div.latest > div.row"
override val mangaDetailsInfoSelector = "div.col-md-9"
override val mangaDetailsThumbnailSelector = "div.thumb > img"
}
class DeathTollScans : FoolSlide("Death Toll Scans", "https://reader.deathtollscans.net", "en")
class DKThias : FoolSlide("DKThias Scanlations", "http://reader.dkthias.com", "en", "/reader") {
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl$urlModifier/list/$page/", headers)
}
}
class MangaichiScanlationDivision : FoolSlide("Mangaichi Scanlation Division", "http://mangaichiscans.mokkori.fr", "en", "/fs")
class WorldThree : FoolSlide("World Three", "http://www.slide.world-three.org", "en")
class TheCatScans : FoolSlide("The Cat Scans", "https://reader.thecatscans.com", "en")
class AngelicScanlations : FoolSlide("Angelic Scanlations", "http://www.angelicscans.net", "en", "/foolslide") {
override fun latestUpdatesSelector() = "div.list > div.releases"
override fun popularMangaSelector() = ".grouped > .series-block"
override fun mangaDetailsParse(document: Document): SManga {
return SManga.create().apply {
thumbnail_url = document.select(".preview > img").attr("src")
val info = document.select(".data").first()
title = info.select("h2.title").text().trim()
val authorArtist = info.select(".author").text().split("/")
author = authorArtist.getOrNull(0)?.trim()
artist = authorArtist.getOrNull(1)?.trim()
description = info.ownText().trim()
}
}
override fun chapterListSelector() = ".list > .release"
override val chapterDateSelector = ".metadata"
}
class DokiFansubs : FoolSlide("Doki Fansubs", "https://kobato.hologfx.com", "en", "/reader")
class YuriIsm : FoolSlide("Yuri-ism", "https://reader.yuri-ism.com", "en", "/slide")
class AjiaNoScantrad : FoolSlide("Ajia no Scantrad", "https://ajianoscantrad.fr", "fr", "/reader")
class OneTimeScans : FoolSlide("One Time Scans", "https://otscans.com", "en", "/foolslide")
class TsubasaSociety : FoolSlide("Tsubasa Society", "https://www.tsubasasociety.com", "en", "/reader/master/Xreader")
class Helheim : FoolSlide("Helheim", "http://helheim.pl", "pl", "/reader")
class MangaScouts : FoolSlide("MangaScouts", "http://onlinereader.mangascouts.org", "de")
class StormInHeaven : FoolSlide("Storm in Heaven", "http://www.storm-in-heaven.net", "it", "/reader-sih")
class Lilyreader : FoolSlide("Lilyreader", "https://manga.smuglo.li", "en")
class MidnightHaven : FoolSlide("Midnight Haven", "http://midnighthaven.shounen-ai.net", "en", "/reader")
class Russification : FoolSlide("Русификация", "https://rusmanga.ru", "ru")
class NieznaniReader : FoolSlide("Nieznani", "http://reader.nieznani.mynindo.pl", "pl")
class EvilFlowers : FoolSlide("Evil Flowers", "http://reader.evilflowers.com", "en")
class NaniScans : FoolSlide("NANI? SCANS", "https://reader.naniscans.xyz", "en")
class AkaiYuhiMunTeam : FoolSlide("AkaiYuhiMun team", "https://akaiyuhimun.ru", "ru", "/manga")
| apache-2.0 | 8f1763550285871ab31dbd89c21259c3 | 36.066298 | 127 | 0.673573 | 3.381552 | false | false | false | false |
LorittaBot/Loritta | web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/routes/LocalizedRoute.kt | 1 | 1549 | package net.perfectdreams.loritta.cinnamon.showtime.backend.routes
import com.mrpowergamerbr.loritta.utils.locale.BaseLocale
import io.ktor.server.application.*
import io.ktor.server.request.*
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.sequins.ktor.BaseRoute
import net.perfectdreams.loritta.cinnamon.showtime.backend.ShowtimeBackend
abstract class LocalizedRoute(val loritta: ShowtimeBackend, val originalPath: String) : BaseRoute("/{localeId}$originalPath") {
override suspend fun onRequest(call: ApplicationCall) {
val localeIdFromPath = call.parameters["localeId"]
// Pegar a locale da URL e, caso não existir, faça fallback para o padrão BR
val locale = loritta.locales.values.firstOrNull { it.path == localeIdFromPath }
if (locale != null) {
// woo hacks
val i18nContext = when (locale.id) {
"default" -> loritta.languageManager.getI18nContextById("pt")
"en-us" -> loritta.languageManager.getI18nContextById("en")
else -> loritta.languageManager.getI18nContextById(loritta.languageManager.defaultLanguageId)
}
return onLocalizedRequest(
call,
locale,
i18nContext
)
}
}
abstract suspend fun onLocalizedRequest(call: ApplicationCall, locale: BaseLocale, i18nContext: I18nContext)
fun getPathWithoutLocale(call: ApplicationCall) = call.request.path().split("/").drop(2).joinToString("/")
} | agpl-3.0 | 8f1f1a99d02803811833bb56ea9f922d | 41.972222 | 127 | 0.691462 | 4.442529 | false | false | false | false |
ansman/kotshi | compiler/src/main/kotlin/se/ansman/kotshi/model/SealedClassJsonAdapter.kt | 1 | 3248 | package se.ansman.kotshi.model
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeVariableName
import se.ansman.kotshi.*
import se.ansman.kotshi.Errors.nestedSealedClassHasPolymorphicLabel
import se.ansman.kotshi.Errors.nestedSealedClassMissingPolymorphicLabel
import se.ansman.kotshi.Errors.nestedSealedClassMustBePolymorphic
data class SealedClassJsonAdapter(
override val targetPackageName: String,
override val targetSimpleNames: List<String>,
override val targetTypeVariables: List<TypeVariableName>,
val polymorphicLabels: Map<String, String>,
val labelKey: String,
val onMissing: Polymorphic.Fallback,
val onInvalid: Polymorphic.Fallback,
val subtypes: List<Subtype>,
val defaultType: ClassName?,
) : GeneratableJsonAdapter() {
init {
if (defaultType != null) {
require(onMissing == Polymorphic.Fallback.DEFAULT || onInvalid == Polymorphic.Fallback.DEFAULT) {
"Using @JsonDefaultValue in combination with onMissing=$onMissing and onInvalid=$onInvalid makes no sense"
}
}
}
data class Subtype(
val type: TypeName,
val wildcardType: TypeName,
val superClass: TypeName,
val label: String
)
}
fun <T> T.getSealedSubtypes(
getSealedSubclasses: T.() -> Sequence<T>,
isSealed: T.() -> Boolean,
hasAnnotation: T.(Class<out Annotation>) -> Boolean,
getPolymorphicLabelKey: T.() -> String?,
getPolymorphicLabel: T.() -> String?,
error: (String, T) -> Throwable,
labelKey: String = getPolymorphicLabelKey() ?: throw error(Errors.sealedClassMustBePolymorphic, this)
): Sequence<T> = getSealedSubclasses().flatMap {
if (!it.hasAnnotation(JsonSerializable::class.java)) {
throw error(Errors.polymorphicSubclassMustHaveJsonSerializable, it)
}
when {
it.isSealed() -> {
val subclassLabelKey = it.getPolymorphicLabelKey()
?: throw error(nestedSealedClassMustBePolymorphic, it)
val subclassLabel = it.getPolymorphicLabel()
when {
subclassLabelKey == labelKey -> {
if (subclassLabel != null) {
throw error(nestedSealedClassHasPolymorphicLabel, it)
}
it.getSealedSubtypes(
getSealedSubclasses = getSealedSubclasses,
isSealed = isSealed,
hasAnnotation = hasAnnotation,
getPolymorphicLabelKey = getPolymorphicLabelKey,
getPolymorphicLabel = getPolymorphicLabel,
error = error,
labelKey = subclassLabelKey,
)
}
subclassLabel == null -> {
throw error(nestedSealedClassMissingPolymorphicLabel, it)
}
else -> sequenceOf(it)
}
}
!it.hasAnnotation(PolymorphicLabel::class.java) && !it.hasAnnotation(JsonDefaultValue::class.java) ->
throw error(Errors.polymorphicSubclassMustHavePolymorphicLabel, it)
else -> sequenceOf(it)
}
} | apache-2.0 | c99904cdb04a0f6d47135477a1cc7cd6 | 38.621951 | 122 | 0.632389 | 5.155556 | false | false | false | false |
jimulabs/road-trip-mirror | application/src/main/kotlin/org/curiouscreature/android/roadtrip/MainActivity.kt | 1 | 10390 | /**
* Copyright 2013 Romain Guy
*
* 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.curiouscreature.android.roadtrip
import android.app.Activity
import android.content.res.Resources
import android.graphics.*
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.*
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Space
import android.widget.Toast
import java.util.ArrayList
SuppressWarnings("ConstantConditions")
public class MainActivity : Activity() {
private class State(var background: Int, var map: Int, var photos: IntArray) {
val bitmaps: MutableList<Bitmap> = ArrayList()
}
private val mStates = array<State>(State(R.color.az, R.raw.map_az, intArray(R.drawable.photo_01_antelope, R.drawable.photo_09_horseshoe, R.drawable.photo_10_sky)), State(R.color.ut, R.raw.map_ut, intArray(R.drawable.photo_08_arches, R.drawable.photo_03_bryce, R.drawable.photo_04_powell)), State(R.color.ca, R.raw.map_ca, intArray(R.drawable.photo_07_san_francisco, R.drawable.photo_02_tahoe, R.drawable.photo_05_sierra, R.drawable.photo_06_rockaway)))
private var mIntroView: IntroView? = null
private var mActionBarDrawable: Drawable? = null
private var mWindowBackground: Drawable? = null
private var mAccentColor: Int = 0
private var mAccentColor2: Int = 0
private val mTempRect = Rect()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mActionBarDrawable = getResources().getDrawable(R.drawable.ab_solid)
mActionBarDrawable!!.setAlpha(0)
getActionBar()!!.setBackgroundDrawable(mActionBarDrawable)
mAccentColor = getResources().getColor(R.color.accent)
mAccentColor2 = getResources().getColor(R.color.accent2)
mIntroView = findViewById(R.id.intro) as IntroView
mIntroView!!.setSvgResource(R.raw.map_usa)
mIntroView!!.setOnReadyListener(object : IntroView.OnReadyListener {
override fun onReady() {
loadPhotos()
}
})
(findViewById(R.id.scroller) as TrackingScrollView).setOnScrollChangedListener(object : TrackingScrollView.OnScrollChangedListener {
override fun onScrollChanged(source: TrackingScrollView, l: Int, t: Int, oldl: Int, oldt: Int) {
handleScroll(source, t)
}
})
}
private fun handleScroll(source: ViewGroup, top: Int) {
val actionBarHeight = getActionBar()!!.getHeight().toFloat()
val firstItemHeight = findViewById(R.id.scroller).getHeight().toFloat() - actionBarHeight
val alpha = Math.min(firstItemHeight, Math.max(0, top).toFloat()) / firstItemHeight
mIntroView!!.setTranslationY(-firstItemHeight / 3.0.toFloat() * alpha)
mActionBarDrawable!!.setAlpha((255 * alpha).toInt())
val decorView = getWindow().getDecorView()
removeOverdraw(decorView, alpha)
if (ANIMATE_BACKGROUND) {
changeBackgroundColor(decorView, alpha)
}
val container = source.findViewById(R.id.container) as ViewGroup
val count = container.getChildCount()
for (i in 0..count - 1) {
val item = container.getChildAt(i)
val v = item.findViewById(R.id.state)
if (v != null && v.getGlobalVisibleRect(mTempRect)) {
(v as StateView).reveal(source, item.getBottom())
}
}
}
SuppressWarnings("PointlessBitwiseExpression")
private fun changeBackgroundColor(decorView: View, alpha: Float) {
val srcR = ((mAccentColor shr 16) and 255).toFloat() / 255.0.toFloat()
val srcG = ((mAccentColor shr 8) and 255).toFloat() / 255.0.toFloat()
val srcB = ((mAccentColor shr 0) and 255).toFloat() / 255.0.toFloat()
val dstR = ((mAccentColor2 shr 16) and 255).toFloat() / 255.0.toFloat()
val dstG = ((mAccentColor2 shr 8) and 255).toFloat() / 255.0.toFloat()
val dstB = ((mAccentColor2 shr 0) and 255).toFloat() / 255.0.toFloat()
val r = ((srcR + ((dstR - srcR) * alpha)) * 255.0.toFloat()).toInt()
val g = ((srcG + ((dstG - srcG) * alpha)) * 255.0.toFloat()).toInt()
val b = ((srcB + ((dstB - srcB) * alpha)) * 255.0.toFloat()).toInt()
val background = decorView.getBackground() as ColorDrawable
background.setColor(-16777216 or r shl 16 or g shl 8 or b)
}
private fun removeOverdraw(decorView: View, alpha: Float) {
if (alpha >= 1.0.toFloat()) {
// Note: setting a large negative translation Y to move the View
// outside of the screen is an optimization. We could make the view
// invisible/visible instead but this would destroy/create its backing
// layer every time we toggle visibility. Since creating a layer can
// be expensive, especially software layers, we would introduce stutter
// when the view is made visible again.
mIntroView!!.setTranslationY((-mIntroView!!.getHeight()).toFloat() * 2.0.toFloat())
}
if (alpha >= 1.0.toFloat() && decorView.getBackground() != null) {
mWindowBackground = decorView.getBackground()
decorView.setBackground(null)
} else if (alpha < 1.0.toFloat() && decorView.getBackground() == null) {
decorView.setBackground(mWindowBackground)
mWindowBackground = null
}
}
private fun loadPhotos() {
val resources = getResources()
Thread(object : Runnable {
override fun run() {
for (s in mStates) {
for (resId in s.photos) {
s.bitmaps.add(BitmapFactory.decodeResource(resources, resId))
}
}
mIntroView!!.post(object : Runnable {
override fun run() {
finishLoadingPhotos()
}
})
}
}, "Photos Loader").start()
}
private fun finishLoadingPhotos() {
mIntroView!!.stopWaitAnimation()
val container = findViewById(R.id.container) as LinearLayout
val inflater = getLayoutInflater()
val spacer = Space(this)
spacer.setLayoutParams(LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, findViewById(R.id.scroller).getHeight()))
container.addView(spacer)
for (s in mStates) {
addState(inflater, container, s)
}
}
private fun addState(inflater: LayoutInflater, container: LinearLayout, state: State) {
val margin = getResources().getDimensionPixelSize(R.dimen.activity_peek_margin)
val view = inflater.inflate(R.layout.item_state, container, false)
val stateView = view.findViewById(R.id.state) as StateView
stateView.svgResource = state.map
view.setBackgroundResource(state.background)
val subContainer = view.findViewById(R.id.sub_container) as LinearLayout
val spacer = Space(this)
spacer.setLayoutParams(LinearLayout.LayoutParams(container.getWidth() - margin, ViewGroup.LayoutParams.MATCH_PARENT))
subContainer.addView(spacer)
var first: ImageView? = null
for (b in state.bitmaps) {
val image = inflater.inflate(R.layout.item_photo, subContainer, false) as ImageView
if (first == null) first = image
image.setImageBitmap(b)
subContainer.addView(image)
}
val cm = ColorMatrix()
cm.setSaturation(0.0.toFloat())
first!!.setTag(cm)
first!!.setColorFilter(ColorMatrixColorFilter(cm))
val bw = first
val s = view.findViewById(R.id.scroller) as TrackingHorizontalScrollView
s.setOnScrollChangedListener(object : TrackingHorizontalScrollView.OnScrollChangedListener {
override fun onScrollChanged(source: TrackingHorizontalScrollView, l: Int, t: Int, oldl: Int, oldt: Int) {
val width = (source.getWidth() - margin).toFloat()
val alpha = Math.min(width, Math.max(0, l).toFloat()) / width
stateView.setTranslationX(-width / 3.0.toFloat() * alpha)
stateView.parallax = 1.0.toFloat() - alpha
removeStateOverdraw(view, state, alpha)
if (alpha < 1.0.toFloat()) {
val cm = bw!!.getTag() as ColorMatrix
cm.setSaturation(alpha)
bw.setColorFilter(ColorMatrixColorFilter(cm))
} else {
bw!!.setColorFilter(null)
}
}
})
container.addView(view)
}
private fun removeStateOverdraw(stateView: View, state: State, alpha: Float) {
if (alpha >= 1.0.toFloat() && stateView.getBackground() != null) {
stateView.setBackground(null)
stateView.findViewById(R.id.state).setVisibility(View.INVISIBLE)
} else if (alpha < 1.0.toFloat() && stateView.getBackground() == null) {
stateView.setBackgroundResource(state.background)
stateView.findViewById(R.id.state).setVisibility(View.VISIBLE)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
getMenuInflater().inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.getItemId()
if (id == R.id.action_about) {
Toast.makeText(this, R.string.text_about, Toast.LENGTH_LONG).show()
return true
}
return super.onOptionsItemSelected(item)
}
class object {
private val ANIMATE_BACKGROUND = false
}
}
| apache-2.0 | 1fbb3f902a0495a90010fed9d8fdc0d9 | 40.394422 | 456 | 0.637536 | 4.338205 | false | false | false | false |
AlmasB/EasyIO | src/main/kotlin/com/almasb/easyio/IOTask.kt | 1 | 8098 | package com.almasb.easyio
import javafx.concurrent.Task
import org.apache.logging.log4j.LogManager
import java.util.concurrent.Callable
import java.util.concurrent.Executor
import java.util.function.Consumer
/**
* IO Task that wraps some IO or any other operation
* that may potentially fail.
*
* @param T type of the result of this task
* @author Almas Baimagambetov ([email protected])
*/
abstract class IOTask<T>(val name: String) {
companion object {
private val log = LogManager.getLogger(IOTask::class.java)
/* Convenient way of creating small tasks */
@JvmStatic fun <R> of(func: Callable<R>) = of("NoName", func)
@JvmStatic fun <R> of(taskName: String, func: Callable<R>) = object : IOTask<R>(taskName) {
override fun onExecute(): R {
return func.call()
}
}
@JvmStatic fun ofVoid(func: Runnable) = ofVoid("NoName", func)
@JvmStatic fun ofVoid(taskName: String, func: Runnable) = object : IOTask<Void?>(taskName) {
override fun onExecute(): Void? {
func.run()
return null
}
}
}
private var onSuccess: ((T) -> Unit)? = null
private var onFailure: ((Throwable) -> Unit)? = null
constructor() : this("NoName")
@Throws(Exception::class)
protected abstract fun onExecute(): T
/**
* Set consumer action for success scenario.
* Note: the consumer will be invoked on the same thread
* that invoked execute(), so be careful if your code
* needs to be run on a particular thread.
* See [executeAsyncWithDialogFX] for JavaFX.
*
* @param action action to call if the task succeeds
*/
fun onSuccess(action: Consumer<T>): IOTask<T> {
onSuccess = { action.accept(it) }
return this
}
fun onSuccessKt(action: (T) -> Unit): IOTask<T> {
onSuccess = action
return this
}
/**
* Set error consumer for fail scenario.
* Note: the consumer will be invoked on the same thread
* that invoked execute(), so be careful if your code
* needs to be run on a particular thread.
* See [executeAsyncWithDialogFX] for JavaFX.
*
* @param handler exception handler to call if the task fails
*/
fun onFailure(handler: Consumer<Throwable>): IOTask<T> {
onFailure = { handler.accept(it) }
return this
}
fun onFailureKt(handler: (Throwable) -> Unit): IOTask<T> {
onFailure = handler
return this
}
open protected fun succeed(value: T) {
log.debug("Task succeeded: $name")
onSuccess?.invoke(value)
}
open protected fun fail(error: Throwable) {
log.warn("Task failed: $name Error: $error")
if (onFailure == null) {
EasyIO.defaultExceptionHandler.accept(error)
} else {
onFailure!!.invoke(error)
}
}
/**
* Allows chaining IO tasks to be executed sequentially.
*
* @param mapper function that takes result of previous task and returns new task
* @return IO task
*/
fun <R> then(mapper: (T) -> IOTask<R>) = taskOf(name, {
log.debug("Executing task: $name")
val result = [email protected]()
val otherTask = mapper.invoke(result)
log.debug("Executing task: ${otherTask.name}")
return@taskOf otherTask.onExecute()
})
/**
* Executes this task synchronously.
* Note: "Void" tasks will also return null.
*
* @return value IO task resulted in, or null if failed
*/
fun execute(): T? {
log.debug("Executing task: $name")
try {
val value = onExecute()
succeed(value)
return value
} catch (e: Exception) {
fail(e)
return null
}
}
/**
* Executes this task asynchronously with given executor.
* Note: it is up to the caller to ensure that executor is actually async.
*
* @param executor executor to use for async
*/
@JvmOverloads fun executeAsync(executor: Executor = EasyIO.defaultExecutor) {
executor.execute({ execute() })
}
/**
* Executes this task asynchronously with given executor and shows dialog.
* The dialog will be dismissed after task is completed, whether succeeded or failed.
* Note: it is up to the caller to ensure that executor is actually async.
*
* @param executor executor to use for async
* @param dialog dialog to use while task is being executed
*/
@JvmOverloads fun executeAsyncWithDialog(executor: Executor = EasyIO.defaultExecutor,
dialog: UIDialogHandler = EasyIO.defaultUIDialogSupplier.get()) {
log.debug("Showing dialog")
dialog.show()
val task = object : IOTask<T>(name) {
override fun onExecute(): T {
log.debug("Executing task: $name")
return [email protected]()
}
override fun succeed(value: T) {
log.debug("succeed(): Dismissing dialog")
dialog.dismiss()
[email protected](value)
}
override fun fail(error: Throwable) {
log.debug("fail(): Dismissing dialog")
dialog.dismiss()
[email protected](error)
}
}
task.executeAsync(executor)
}
/**
* Executes this task asynchronously with default executor and shows dialog.
* The dialog will be dismissed after task is completed, whether succeeded or failed.
* Note: it is up to the caller to ensure that executor is actually async.
* Unlike [executeAsyncWithDialog], this function hooks into the JavaFX concurrent model
* with its Task as the primitive execution unit.
* Hence, onSuccess and onFailure are executed from the JavaFX App thread.
*
* @param dialog dialog to use while task is being executed
*/
fun executeAsyncWithDialogFX(dialog: UIDialogHandler) {
executeAsyncWithDialogFX(EasyIO.defaultExecutor, dialog)
}
/**
* Executes this task asynchronously with given executor and shows dialog.
* The dialog will be dismissed after task is completed, whether succeeded or failed.
* Note: it is up to the caller to ensure that executor is actually async.
* Unlike [executeAsyncWithDialog], this function hooks into the JavaFX concurrent model
* with its Task as the primitive execution unit.
* Hence, onSuccess and onFailure are executed from the JavaFX App thread.
*
* @param executor executor to use for async
* @param dialog dialog to use while task is being executed
*/
@JvmOverloads fun executeAsyncWithDialogFX(executor: Executor = EasyIO.defaultExecutor,
dialog: UIDialogHandler = EasyIO.defaultUIDialogSupplier.get()) {
log.debug("Showing dialog")
dialog.show()
val task = object : Task<T>() {
override fun call(): T {
log.debug("Executing task: $name")
return onExecute()
}
override fun succeeded() {
log.debug("succeed(): Dismissing dialog")
dialog.dismiss()
succeed(value)
}
override fun failed() {
log.debug("fail(): Dismissing dialog")
dialog.dismiss()
fail(exception)
}
}
executor.execute(task)
}
}
fun <R> taskOf(func: () -> R) = taskOf("NoName", func)
fun <R> taskOf(taskName: String, func: () -> R): IOTask<R> = object : IOTask<R>(taskName) {
override fun onExecute(): R {
return func()
}
}
fun <R> voidTaskOf(func: () -> R) = voidTaskOf("NoName", func)
fun <R> voidTaskOf(taskName: String, func: () -> R) = object : IOTask<Void?>(taskName) {
override fun onExecute(): Void? {
func()
return null
}
} | mit | cb06e8ce87890757e3357c7c7c1cb788 | 31.138889 | 110 | 0.599037 | 4.531617 | false | false | false | false |
Dreamersoul/FastHub | app/src/main/java/com/fastaccess/ui/modules/trending/TrendingActivity.kt | 1 | 7887 | package com.fastaccess.ui.modules.trending
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.os.Handler
import android.support.annotation.ColorInt
import android.support.design.widget.NavigationView
import android.support.v4.widget.DrawerLayout
import android.text.Editable
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import butterknife.OnClick
import butterknife.OnEditorAction
import butterknife.OnTextChanged
import com.evernote.android.state.State
import com.fastaccess.R
import com.fastaccess.helper.*
import com.fastaccess.ui.base.BaseActivity
import com.fastaccess.ui.modules.main.MainActivity
import com.fastaccess.ui.modules.trending.fragment.TrendingFragment
import com.fastaccess.ui.widgets.FontEditText
import com.fastaccess.ui.widgets.bindView
/**
* Created by Kosh on 30 May 2017, 10:57 PM
*/
class TrendingActivity : BaseActivity<TrendingMvp.View, TrendingPresenter>(), TrendingMvp.View {
private var trendingFragment: TrendingFragment? = null
val navMenu: NavigationView by bindView(R.id.navMenu)
val daily: TextView by bindView(R.id.daily)
val weekly: TextView by bindView(R.id.weekly)
val monthly: TextView by bindView(R.id.monthly)
val drawerLayout: DrawerLayout by bindView(R.id.drawer)
val clear: View by bindView(R.id.clear)
val searchEditText: FontEditText by bindView(R.id.searchEditText)
@State var selectedTitle: String = "All Language"
@OnTextChanged(value = R.id.searchEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED) fun onTextChange(s: Editable) {
val text = s.toString()
if (text.isEmpty()) {
AnimHelper.animateVisibility(clear, false)
} else {
AnimHelper.animateVisibility(clear, true)
}
}
@OnEditorAction(R.id.searchEditText) fun onSearch(): Boolean {
presenter.onFilterLanguage(InputHelper.toString(searchEditText))
ViewHelper.hideKeyboard(searchEditText)
return true
}
@OnClick(R.id.daily) fun onDailyClicked() {
Logger.e()
daily.isSelected = true
weekly.isSelected = false
monthly.isSelected = false
setValues()
}
@OnClick(R.id.weekly) fun onWeeklyClicked() {
weekly.isSelected = true
daily.isSelected = false
monthly.isSelected = false
setValues()
}
@OnClick(R.id.monthly) fun onMonthlyClicked() {
monthly.isSelected = true
weekly.isSelected = false
daily.isSelected = false
setValues()
}
@OnClick(R.id.clear) fun onClearSearch() {
ViewHelper.hideKeyboard(searchEditText)
searchEditText.setText("")
onClearMenu()
presenter.onLoadLanguage()
}
override fun layout(): Int = R.layout.trending_activity_layout
override fun isTransparent(): Boolean = true
override fun canBack(): Boolean = true
override fun isSecured(): Boolean = false
override fun providePresenter(): TrendingPresenter = TrendingPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
navMenu.itemIconTintList = null
trendingFragment = supportFragmentManager.findFragmentById(R.id.trendingFragment) as TrendingFragment?
navMenu.setNavigationItemSelectedListener({ item ->
closeDrawerLayout()
onItemClicked(item)
})
setupIntent(savedInstanceState)
if (savedInstanceState == null) {
presenter.onLoadLanguage()
} else {
Handler().postDelayed({
Logger.e(searchEditText.text)
if (InputHelper.isEmpty(searchEditText)) { //searchEditText.text is always empty even tho there is a text in it !!!!!!!
presenter.onLoadLanguage()
} else {
presenter.onFilterLanguage(InputHelper.toString(searchEditText))
}
}, 300)
}
onSelectTrending()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.trending_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.menu -> {
drawerLayout.openDrawer(Gravity.END)
return true
}
android.R.id.home -> {
startActivity(Intent(this, MainActivity::class.java))
finish()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun onAppend(title: String, color: Int) {
navMenu.menu.add(R.id.languageGroup, title.hashCode(), Menu.NONE, title)
.setCheckable(true)
.setIcon(createOvalShape(color))
.isChecked = title.toLowerCase() == selectedTitle.toLowerCase()
}
override fun onClearMenu() {
navMenu.menu.clear()
}
private fun onItemClicked(item: MenuItem?): Boolean {
when (item?.title.toString()) {
"All Language" -> selectedTitle = ""
else -> selectedTitle = item?.title.toString()
}
Logger.e(selectedTitle)
setValues()
return true
}
private fun closeDrawerLayout() {
drawerLayout.closeDrawer(Gravity.END)
}
private fun setValues() {
closeDrawerLayout()
Logger.e(selectedTitle, getSince())
trendingFragment?.onSetQuery(selectedTitle, getSince())
}
private fun getSince(): String {
when {
daily.isSelected -> return "daily"
weekly.isSelected -> return "weekly"
monthly.isSelected -> return "monthly"
else -> return "daily"
}
}
private fun setupIntent(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
if (intent != null && intent.extras != null) {
val bundle = intent.extras
if (bundle != null) {
val lang: String = bundle.getString(BundleConstant.EXTRA)
val query: String = bundle.getString(BundleConstant.EXTRA_TWO)
if (!lang.isNullOrEmpty()) {
selectedTitle = lang
}
if (!query.isNullOrEmpty()) {
when (query.toLowerCase()) {
"daily" -> daily.isSelected = true
"weekly" -> weekly.isSelected = true
"monthly" -> monthly.isSelected = true
}
} else {
daily.isSelected = true
}
} else {
daily.isSelected = true
}
} else {
daily.isSelected = true
}
setValues()
}
}
private fun createOvalShape(@ColorInt color: Int): GradientDrawable {
val drawable = GradientDrawable()
drawable.shape = GradientDrawable.OVAL
drawable.setSize(24, 24)
drawable.setColor(if (color == 0) Color.LTGRAY else color)
return drawable
}
companion object {
fun getTrendingIntent(context: Context, lang: String?, query: String?): Intent {
val intent = Intent(context, TrendingActivity::class.java)
intent.putExtras(Bundler.start()
.put(BundleConstant.EXTRA, lang)
.put(BundleConstant.EXTRA_TWO, query)
.end())
return intent
}
}
} | gpl-3.0 | 9cfe844c146940f30e102cdc4ad12954 | 32.709402 | 136 | 0.612654 | 4.914019 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl-provider-plugins/src/main/kotlin/org/gradle/kotlin/dsl/provider/plugins/precompiled/tasks/GenerateExternalPluginSpecBuilders.kt | 1 | 2053 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.accessors.writeSourceCodeForPluginSpecBuildersFor
import java.io.File
@CacheableTask
abstract class GenerateExternalPluginSpecBuilders : ClassPathSensitiveCodeGenerationTask(), SharedAccessorsPackageAware {
@get:OutputDirectory
abstract val metadataOutputDir: DirectoryProperty
@TaskAction
@Suppress("unused")
internal
fun generate() {
sourceCodeOutputDir.withOutputDirectory { outputDir ->
val packageDir = createPackageDirIn(outputDir)
val outputFile = packageDir.resolve("PluginSpecBuilders.kt")
writeSourceCodeForPluginSpecBuildersFor(
classPath,
outputFile,
packageName()
)
}
metadataOutputDir.withOutputDirectory { outputDir ->
outputDir.resolve("implicit-imports").writeText(
packageName() + ".*"
)
}
}
private
fun createPackageDirIn(outputDir: File) = outputDir.resolve(packagePath()).apply { mkdirs() }
private
fun packagePath() = packageName().split('.').joinToString("/")
private
fun packageName() = sharedAccessorsPackage.get()
}
| apache-2.0 | 67f53e2f509f673786a9130ac1ebcbfc | 31.587302 | 121 | 0.706283 | 4.807963 | false | false | false | false |
Nilhcem/droidconde-2016 | scraper/src/main/kotlin/com/nilhcem/droidconde/scraper/App.kt | 1 | 1082 | package com.nilhcem.droidconde.scraper
import com.nilhcem.droidconde.scraper.model.Session
import com.nilhcem.droidconde.scraper.model.Speaker
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import java.io.File
fun main(args: Array<String>) {
val scraper = Scraper()
val speakers = scraper.getSpeakers()
val sessions = scraper.getSessions(speakers)
createJsons(speakers, sessions)
}
fun createJsons(speakers: List<Speaker>, sessions: List<Session>) {
val moshi = Moshi.Builder().build()
File("output").mkdir()
File("output/speakers.json").printWriter().use { out ->
val adapter: JsonAdapter<List<Speaker>> = moshi.adapter(Types.newParameterizedType(List::class.java, Speaker::class.java))
out.println(adapter.toJson(speakers))
}
File("output/sessions.json").printWriter().use { out ->
val adapter: JsonAdapter<List<Session>> = moshi.adapter(Types.newParameterizedType(List::class.java, Session::class.java))
out.println(adapter.toJson(sessions))
}
}
| apache-2.0 | c42a4efe1a09bbbd1a6445b4d1a19436 | 33.903226 | 130 | 0.727357 | 3.850534 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2021/Day4.kt | 1 | 1855 | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 4: Giant Squid ---
* https://adventofcode.com/2021/day/4
*/
class Day4 : Solver {
override fun solve(lines: List<String>): Result {
val (numbers, boards) = parseData(lines)
return Result("${solve(boards, numbers, false)}", "${solve(boards, numbers, true)}")
}
fun solve(boards: MutableList<BingoBoard>, numbers: List<Long>, partB: Boolean): Long {
for (num in numbers) {
boards.forEach { it.mark(num) }
val toRemove = boards.filter { it.isWon() }.filter { boards.contains(it) }
boards.removeAll(toRemove)
if (partB && boards.isEmpty()) return toRemove[0].unmarkedSum() * num
if (!partB && toRemove.isNotEmpty()) return toRemove[0].unmarkedSum() * num
}
error("No board won")
}
private fun parseData(lines: List<String>): Pair<List<Long>, MutableList<BingoBoard>> {
val numbers = lines[0].split(",").map { it.toLong() }
val boards = mutableListOf<BingoBoard>()
for (line in lines.listIterator(1)) {
if (line.isEmpty()) {
boards.add(BingoBoard(mutableListOf()))
} else {
boards.last().feedLine(line)
}
}
return Pair(numbers, boards)
}
}
class BingoBoard(val values: MutableList<Long>) {
fun feedLine(line: String) {
values.addAll(line.split(" ").filter { it.isNotBlank() }.map { it.toLong() })
}
fun mark(num: Long) {
values.replaceAll { if (it == num) -1 else it }
}
fun get(x: Int, y: Int) = values[y * 5 + x]
fun unmarkedSum() = values.filter { it != -1L }.sum()
fun isWon(): Boolean {
(0..4).forEach { y -> if ((0..4).map { x -> get(x, y) }.count { it == -1L } == 5) return true }
(0..4).forEach { x -> if ((0..4).map { y -> get(x, y) }.count { it == -1L } == 5) return true }
return false
}
} | apache-2.0 | e31f9d1ff250082607ef38976cbbb76d | 31 | 99 | 0.603235 | 3.243007 | false | false | false | false |
xfournet/intellij-community | platform/configuration-store-impl/testSrc/DoNotSaveDefaults.kt | 1 | 4619 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.impl.ComponentManagerImpl
import com.intellij.openapi.components.impl.ServiceManagerImpl
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectImpl
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.testFramework.createOrLoadProject
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.util.io.delete
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Path
import java.nio.file.Paths
private val testData: Path
get() = Paths.get(PathManagerEx.getHomePath(DoNotSaveDefaultsTest::class.java),
FileUtil.toSystemDependentName("platform/configuration-store-impl/testSrc"))
class DoNotSaveDefaultsTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
init {
Paths.get(PathManager.getConfigPath()).delete()
}
}
@JvmField
@Rule
val tempDir = TemporaryDirectory()
@Test
fun testApp() {
doTest(ApplicationManager.getApplication() as ApplicationImpl)
}
@Test
fun testProject() {
createOrLoadProject(tempDir, directoryBased = false) { project ->
doTest(project as ProjectImpl)
}
}
private fun doTest(componentManager: ComponentManagerImpl) {
val useModCountOldValue = System.getProperty("store.save.use.modificationCount")
// wake up (edt, some configurables want read action)
runInEdtAndWait {
val picoContainer = componentManager.picoContainer
ServiceManagerImpl.processAllImplementationClasses(componentManager, { clazz, _ ->
val className = clazz.name
// CvsTabbedWindow calls invokeLater in constructor
if (className != "com.intellij.cvsSupport2.ui.CvsTabbedWindow"
&& className != "com.intellij.lang.javascript.bower.BowerPackagingService"
&& className != "org.jetbrains.plugins.groovy.mvc.MvcConsole") {
picoContainer.getComponentInstance(className)
}
true
})
}
val propertyComponent = PropertiesComponent.getInstance()
// <property name="file.gist.reindex.count" value="54" />
propertyComponent.unsetValue("file.gist.reindex.count")
// <property name="CommitChangeListDialog.DETAILS_SPLITTER_PROPORTION_2" value="1.0" />
propertyComponent.unsetValue("CommitChangeListDialog.DETAILS_SPLITTER_PROPORTION_2")
val app = ApplicationManager.getApplication() as ApplicationImpl
try {
System.setProperty("store.save.use.modificationCount", "false")
app.isSaveAllowed = true
runInEdtAndWait {
StoreUtil.save(componentManager.stateStore, null)
}
}
finally {
System.setProperty("store.save.use.modificationCount", useModCountOldValue ?: "false")
app.isSaveAllowed = false
}
if (componentManager is Project) {
assertThat(Paths.get(componentManager.projectFilePath!!)).doesNotExist()
return
}
val directoryTree = printDirectoryTree(Paths.get(
componentManager.stateStore.storageManager.expandMacros(APP_CONFIG)), setOf(
"path.macros.xml" /* todo EP to register (provide) macro dynamically */,
"stubIndex.xml" /* low-level non-roamable stuff */,
UsageStatisticsPersistenceComponent.USAGE_STATISTICS_XML /* SHOW_NOTIFICATION_ATTR in internal mode */,
"tomee.extensions.xml", "jboss.extensions.xml",
"glassfish.extensions.xml" /* javaee non-roamable stuff, it will be better to fix it */,
"dimensions.xml" /* non-roamable sizes of window, dialogs, etc. */,
"debugger.renderers.xml", "debugger.xml" /* todo */,
"databaseSettings.xml"
))
println(directoryTree)
assertThat(directoryTree).toMatchSnapshot(testData.resolve("DoNotSaveDefaults.snap.txt"))
}
}
| apache-2.0 | 1b9a36f05bdd08b03ddfc75f04cb815e | 38.144068 | 140 | 0.74843 | 4.559724 | false | true | false | false |
brunogabriel/SampleAppKotlin | SampleAppKotlin/app/src/test/java/io/github/brunogabriel/sampleappkotlin/RegisterPresenterTest.kt | 1 | 1639 | package io.github.brunogabriel.sampleappkotlin
import io.github.brunogabriel.sampleappkotlin.register.ImplRegisterPresenter
import io.github.brunogabriel.sampleappkotlin.register.RegisterView
import org.junit.Test
import org.mockito.Mockito
import org.mockito.Mockito.*
/**
* Created by brunogabriel on 16/05/17.
*/
class RegisterPresenterTest {
/**
* Tip: To suppress error Identifier not allowed for Android project...
* displayed by Android Studio you have to got to
* Preferences... -> Editor -> Inspections -> Kotlin and disable Illegal Android Identifier inspection.
*/
@Test
fun `should show name error when has no name`() {
// given
val registerView = Mockito.mock(RegisterView::class.java)
val presenter = ImplRegisterPresenter(registerView)
// when
presenter.saveUser("", "")
// then
verify(registerView).showEmptyNameError()
}
@Test
fun `should show surname error when has no surname`() {
// given
val registerView = Mockito.mock(RegisterView::class.java)
val presenter = ImplRegisterPresenter(registerView)
// when
presenter.saveUser("anyName", "")
// then
verify(registerView).showEmptySurnameError()
}
@Test
fun `should show user saved when has a valid user`() {
// given
val registerView = Mockito.mock(RegisterView::class.java)
val presenter = ImplRegisterPresenter(registerView)
// when
presenter.saveUser("anyName", "anySurname")
// then
verify(registerView).showUserSaved()
}
}
| mit | 8c002b297389321deb7b12727c5b7741 | 27.258621 | 107 | 0.662599 | 4.478142 | false | true | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/tab/tab_list/view/TabListUi.kt | 1 | 13775 | /*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.tab.tab_list.view
import androidx.activity.ComponentActivity
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.animation.slideInVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.FractionalThreshold
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ResistanceConfig
import androidx.compose.material.Surface
import androidx.compose.material.SwipeableState
import androidx.compose.material.Text
import androidx.compose.material.swipeable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.graphics.ColorUtils
import androidx.core.net.toUri
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.TabListViewModel
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.tab.TabAdapter
import jp.toastkid.yobidashi.tab.TabThumbnails
import jp.toastkid.yobidashi.tab.model.Tab
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.burnoutcrew.reorderable.ReorderableItem
import org.burnoutcrew.reorderable.detectReorderAfterLongPress
import org.burnoutcrew.reorderable.rememberReorderableLazyListState
import org.burnoutcrew.reorderable.reorderable
import java.io.File
import kotlin.math.max
import kotlin.math.roundToInt
@Composable
internal fun TabListUi(tabAdapter: TabAdapter) {
val context = LocalContext.current as? ComponentActivity ?: return
val preferenceApplier = PreferenceApplier(context)
val tabThumbnails = TabThumbnails.with(LocalContext.current)
val contentViewModel = viewModel(ContentViewModel::class.java, context)
val tabListViewModel = viewModel(TabListViewModel::class.java, context)
val coroutineScope = rememberCoroutineScope()
val tabs = remember { mutableStateListOf<Tab>() }
refresh(tabAdapter, tabs)
val state = rememberReorderableLazyListState(
onMove = { from, to ->
tabs.add(to.index, tabs.removeAt(from.index))
tabAdapter.swap(to.index, from.index)
},
onDragEnd = { _, _ ->
tabAdapter.saveTabList()
},
listState = rememberLazyListState(max(0, tabAdapter.index() - 1))
)
val sizePx = with(LocalDensity.current) { dimensionResource(R.dimen.tab_list_item_height).toPx() }
val anchors = mapOf(0f to 0, -sizePx to 1)
val initialIndex = tabAdapter.currentTabId()
val deletedTabIds = remember { mutableStateListOf<String>() }
Box {
AsyncImage(
model = preferenceApplier.backgroundImagePath,
contentDescription = stringResource(id = R.string.content_description_background),
alignment = Alignment.Center,
contentScale = ContentScale.Crop,
modifier = Modifier.matchParentSize()
)
Column {
LazyRow(
state = state.listState,
contentPadding = PaddingValues(horizontal = 4.dp),
modifier = Modifier
.reorderable(state)
.detectReorderAfterLongPress(state)
) {
val currentIndex = tabAdapter.index()
itemsIndexed(tabs, { _, tab -> tab.id() }) { position, tab ->
val backgroundColor = if (currentIndex == position)
Color(
ColorUtils.setAlphaComponent(
MaterialTheme.colors.primary.toArgb(),
128
)
)
else
Color.Transparent
ReorderableItem(state, key = tab.id(), defaultDraggingModifier = Modifier) { _ ->
TabItem(
tab,
tabThumbnails.assignNewFile(tab.thumbnailPath()),
backgroundColor,
anchors,
visibility = {
deletedTabIds.contains(it.id()).not()
},
onClick = {
tabAdapter.replace(tab)
closeOnly(coroutineScope, contentViewModel)
},
onClose = {
deletedTabIds.add(tab.id())
tabAdapter.closeTab(tabAdapter.indexOf(tab))
}
)
}
}
}
val tint = Color(preferenceApplier.fontColor)
val backgroundColor = Color(preferenceApplier.color)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End,
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
) {
TabActionFab(
R.drawable.ic_edit,
R.string.title_editor,
tint,
backgroundColor,
Modifier.padding(4.dp)
) {
contentViewModel.openEditorTab()
closeOnly(coroutineScope, contentViewModel)
}
TabActionFab(
R.drawable.ic_pdf,
R.string.title_open_pdf,
tint,
backgroundColor,
Modifier.padding(4.dp)
) {
contentViewModel.openPdf()
closeOnly(coroutineScope, contentViewModel)
}
TabActionFab(
R.drawable.ic_article,
R.string.title_article_viewer,
tint,
backgroundColor,
Modifier.padding(4.dp)
) {
contentViewModel.openArticleList()
closeOnly(coroutineScope, contentViewModel)
}
val browserViewModel = viewModel(BrowserViewModel::class.java, context)
TabActionFab(
R.drawable.ic_web,
R.string.title_browser,
tint,
backgroundColor,
Modifier.padding(4.dp)
) {
browserViewModel.open(preferenceApplier.homeUrl.toUri())
closeOnly(coroutineScope, contentViewModel)
}
TabActionFab(
R.drawable.ic_add_tab,
R.string.open,
tint,
backgroundColor,
Modifier.padding(4.dp)
) {
// For suppressing replace screen.
contentViewModel.setHideBottomSheetAction { }
tabListViewModel.openNewTab()
closeOnly(coroutineScope, contentViewModel)
}
}
}
}
LaunchedEffect(initialIndex, block = {
contentViewModel.setHideBottomSheetAction {
if (initialIndex != tabAdapter.currentTabId()) {
contentViewModel.replaceToCurrentTab()
}
contentViewModel.setHideBottomSheetAction { }
}
})
DisposableEffect(tabAdapter) {
onDispose {
tabAdapter.saveTabList()
}
}
}
private fun closeOnly(
coroutineScope: CoroutineScope,
contentViewModel: ContentViewModel
) {
coroutineScope.launch {
contentViewModel.hideBottomSheet()
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun TabItem(
tab: Tab,
thumbnail: File,
backgroundColor: Color,
anchors: Map<Float, Int>,
visibility: (Tab) -> Boolean,
onClick: (Tab) -> Unit,
onClose: (Tab) -> Unit
) {
val swipeableState = SwipeableState(
initialValue = 0,
confirmStateChange = {
if (it == 1) {
onClose(tab)
}
true
}
)
AnimatedVisibility(
visibility(tab),
enter = slideInVertically(initialOffsetY = { it }),
exit = shrinkHorizontally(shrinkTowards = Alignment.Start)
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.width(dimensionResource(id = R.dimen.tab_list_item_width))
.height(dimensionResource(id = R.dimen.tab_list_item_height))
.clickable {
onClick(tab)
}
.background(backgroundColor)
.offset { IntOffset(0, swipeableState.offset.value.roundToInt()) }
.swipeable(
swipeableState,
anchors = anchors,
thresholds = { _, _ -> FractionalThreshold(0.75f) },
resistance = ResistanceConfig(0.5f),
velocityThreshold = 3000000.dp,
orientation = Orientation.Vertical
)
) {
Surface(
elevation = 4.dp,
modifier = Modifier
.width(112.dp)
.height(152.dp)
) {
Box(
modifier = Modifier
.width(112.dp)
.height(152.dp)
.padding(4.dp)
.align(Alignment.BottomCenter)
) {
AsyncImage(
model = thumbnail,
contentDescription = tab.title(),
contentScale = ContentScale.FillHeight,
placeholder = painterResource(id = R.drawable.ic_yobidashi),
modifier = Modifier
.padding(top = 4.dp)
.align(Alignment.TopCenter)
)
Text(
text = tab.title(),
color = MaterialTheme.colors.onPrimary,
maxLines = 2,
fontSize = 14.sp,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.align(Alignment.BottomCenter)
.fillMaxWidth()
.background(MaterialTheme.colors.primary)
.padding(4.dp)
)
}
}
}
}
}
@Composable
private fun TabActionFab(
iconId: Int,
contentDescriptionId: Int,
iconColor: Color,
buttonColor: Color,
modifier: Modifier,
action: () -> Unit
) {
FloatingActionButton(
onClick = action,
backgroundColor = buttonColor,
modifier = modifier.size(48.dp)
) {
Icon(
painterResource(id = iconId),
stringResource(id = contentDescriptionId),
tint = iconColor
)
}
}
private fun refresh(callback: TabAdapter, tabs: SnapshotStateList<Tab>) {
tabs.clear()
(0 until callback.size()).forEach {
val tab = callback.getTabByIndex(it) ?: return@forEach
tabs.add(tab)
}
} | epl-1.0 | b9589f7a0ea688a1e07178e9b19af5bd | 36.032258 | 102 | 0.58323 | 5.387172 | false | false | false | false |
franciscofranco/Demo-Mode-tile | app/src/main/java/com/franco/demomode/activities/MainActivity.kt | 1 | 1815 | package com.franco.demomode.activities
import android.content.DialogInterface
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.franco.demomode.R
import com.franco.demomode.Utils
import com.franco.demomode.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
supportActionBar!!.setDisplayShowTitleEnabled(false)
val action = intent?.action ?: ""
if (action == Utils.MISSING_PERMISSION) {
Snackbar.make(binding.root, R.string.permissions_need_to_be_granted,
Snackbar.LENGTH_INDEFINITE).apply {
setAction(R.string.ok) { dismiss() }
show()
}
}
lifecycleScope.launch {
val isDemoModeAllowed = Utils().isDemoModeAllowed(this@MainActivity)
if (!isDemoModeAllowed) {
AlertDialog.Builder(this@MainActivity)
.setTitle(R.string.demo_mode_allowed_title)
.setMessage(R.string.demo_mode_allowed_message)
.setPositiveButton(android.R.string.ok) { dialog: DialogInterface, _: Int -> dialog.dismiss() }
.show()
}
}
}
override fun onResume() {
super.onResume()
Utils().setLightNavBar(binding.root)
}
} | apache-2.0 | 966ce394082c09283ab5099e590cbb71 | 34.607843 | 119 | 0.659504 | 4.801587 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/extensions/AppBarLayout.kt | 1 | 3229 | package com.booboot.vndbandroid.extensions
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import com.booboot.vndbandroid.R
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.CollapsingToolbarLayout
fun AppBarLayout.setStatusBarThemeForCollapsingToolbar(activity: AppCompatActivity, collapsingToolbar: CollapsingToolbarLayout, toolbar: Toolbar, contentView: View) =
addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, offset ->
if (collapsingToolbar.height + offset < collapsingToolbar.scrimVisibleHeightTrigger) {
/* Toolbar is collapsing: removing the status bar's translucence and adding the light flag */
activity.window.statusBarColor = ContextCompat.getColor(activity, android.R.color.transparent)
toolbar.setBackgroundColor(ContextCompat.getColor(activity, android.R.color.transparent))
} else {
/* Toolbar is expanding: adding the status bar's translucence and removing the light flag */
activity.window.statusBarColor = ContextCompat.getColor(activity, R.color.tabBackgroundColor)
toolbar.setBackgroundColor(ContextCompat.getColor(activity, R.color.tabBackgroundColor))
}
if (activity.dayNightTheme() == "light") {
if (activity.window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR == 0) {
activity.window.decorView.systemUiVisibility = activity.window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
/* Scroll is broken if we don't refresh layout on the sibling view for some reason */
contentView.requestLayout()
}
}
})
fun AppBarLayout.setStatusBarThemeForToolbar(activity: AppCompatActivity, toolbar: Toolbar) =
addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, offset ->
if (activity.statusBarHeight() + toolbar.height + offset > 0) {
/* Toolbar is collapsing: removing the status bar's translucence and adding the light flag */
activity.window.statusBarColor = ContextCompat.getColor(activity, android.R.color.transparent)
toolbar.setBackgroundColor(ContextCompat.getColor(activity, android.R.color.transparent))
} else {
/* Toolbar is expanding: adding the status bar's translucence and removing the light flag */
activity.window.statusBarColor = ContextCompat.getColor(activity, R.color.tabBackgroundColor)
toolbar.setBackgroundColor(ContextCompat.getColor(activity, R.color.tabBackgroundColor))
}
})
fun AppBarLayout.fixForFastScroll(container: ViewGroup, scrollingChild: View? = null) {
val initialPaddingBottom = container.paddingBottom
val initialPaddingTop = scrollingChild?.paddingTop ?: 0
addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, offset ->
container.setPaddingBottom(initialPaddingBottom + totalScrollRange + offset)
scrollingChild?.setPaddingTop(initialPaddingTop - offset)
})
} | gpl-3.0 | 1f5b794984d03c2de78b4981bb87463b | 59.943396 | 166 | 0.743884 | 5.199678 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/annotator/fixes/SurroundWithUnsafeFix.kt | 2 | 1275 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.lang.core.psi.RsBlock
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsExprStmt
import org.rust.lang.core.psi.RsPsiFactory
class SurroundWithUnsafeFix(val expr: RsExpr) : LocalQuickFixAndIntentionActionOnPsiElement(expr) {
override fun getFamilyName() = text
override fun getText() = "Surround with unsafe block"
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) {
val parent = expr.parent
when (parent) {
is RsExprStmt -> {
val unsafe = RsPsiFactory(project).createUnsafeBlockExpr(expr.parent.text)
expr.parent.replace(unsafe)
}
else -> {
val unsafe = RsPsiFactory(project).createUnsafeBlockExpr(expr.text)
expr.replace(unsafe)
}
}
}
}
| mit | ac50e3d4c818df672c676849a40b681b | 35.428571 | 125 | 0.703529 | 4.381443 | false | false | false | false |
quarkusio/quarkus | integration-tests/mongodb-panache-kotlin/src/main/kotlin/io/quarkus/it/mongodb/panache/book/BookShortView.kt | 1 | 518 | package io.quarkus.it.mongodb.panache.book
import com.fasterxml.jackson.annotation.JsonFormat
import com.fasterxml.jackson.annotation.JsonFormat.Shape
import io.quarkus.mongodb.panache.common.ProjectionFor
import java.time.LocalDate
@ProjectionFor(Book::class)
class BookShortView {
// uses the field name title and not the column name bookTitle
var title: String? = null
var author: String? = null
@JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd")
var creationDate: LocalDate? = null
}
| apache-2.0 | dde86d5839a778819c28ab84ceb11e74 | 31.375 | 66 | 0.766409 | 3.865672 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/lang/utils/QueryUtils.kt | 2 | 837 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.utils
import com.intellij.openapi.util.Condition
import com.intellij.util.*
// Be careful with queries: they are `Iterable`s, so they have Kotlin's
// `map`, `filter` and friends, which convert then to List.
fun <U> Query<U>.filterQuery(condition: Condition<U>): Query<U> = FilteredQuery(this, condition)
inline fun <reified V: Any> Query<*>.filterIsInstanceQuery(): Query<V> = InstanceofQuery(this, V::class.java)
fun <U, V> Query<U>.mapQuery(f: (U) -> V) = object : AbstractQuery<V>() {
override fun processResults(consumer: Processor<V>): Boolean {
return [email protected](Processor<U> { t -> consumer.process(f(t)) })
}
}
val Query<*>.isEmptyQuery get() = findFirst() == null
| mit | 23fbfd30994b4ccdd8d247936d548193 | 33.875 | 109 | 0.696535 | 3.388664 | false | false | false | false |
Jonatino/Vision | src/main/kotlin/org/anglur/vision/capture/Screen.kt | 1 | 1142 | /*
* Vision - free remote desktop software built with Kotlin
* Copyright (C) 2016 Jonathan Beaudoin
*
* 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 org.anglur.vision.capture
import java.awt.Rectangle
class Screen(val bounds: Rectangle, val id: Int, val isPrimary: Boolean = id == 0) {
var active = isPrimary
val orignalBounds = bounds.clone() as Rectangle
val maxWidth = bounds.width
val maxHeight = bounds.height
override fun toString() = "Screen ${id + 1}"
} | gpl-3.0 | d1a909f6141409bc23a4a86e0fe19417 | 32.617647 | 84 | 0.702277 | 4.064057 | false | false | false | false |
jtransc/jtransc | jtransc-core/src/com/jtransc/backend/asm2/TirToStm.kt | 1 | 4979 | package com.jtransc.backend.asm2
import com.jtransc.ast.*
import com.jtransc.ds.cast
import com.jtransc.org.objectweb.asm.Label
class TirToStm(val methodType: AstType.METHOD, val blockContext: BlockContext, val types: AstTypes) {
val locals = hashMapOf<Local, AstLocal>()
val stms = arrayListOf<AstStm>()
var id = 0
fun AstType.convertType(): AstType {
val type = this
return when (type) {
is AstType.COMMON -> {
if (type.single != null) {
type.single!!.convertType()
} else {
if (type.elements.any { it is AstType.Primitive }) {
getCommonTypePrim(type.elements.cast<AstType.Primitive>())
} else {
AstType.OBJECT
}
}
}
else -> type
}
}
val Local.ast: AstLocal get() {
val canonicalLocal = Local(this.type.convertType(), this.index)
if (canonicalLocal.type is AstType.UNKNOWN) {
println("ASSERT UNKNOWN!: $canonicalLocal")
}
return locals.getOrPut(canonicalLocal) { AstLocal(id++, canonicalLocal.type) }
}
val Label.ast: AstLabel get() = blockContext.label(this)
val Local.expr: AstExpr.LOCAL get() = AstExpr.LOCAL(this.ast)
val Operand.expr: AstExpr get() = when (this) {
is Constant -> this.v.lit
is Param -> AstExpr.PARAM(AstArgument(this.index, this.type.convertType()))
is Local -> AstExpr.LOCAL(this.ast)
is This -> AstExpr.THIS(this.clazz.name)
//is CatchException -> AstExpr.CAUGHT_EXCEPTION(this.type)
is CatchException -> AstExpr.CAUGHT_EXCEPTION(AstType.OBJECT)
else -> TODO("$this")
}
fun convert(tirs: List<TIR>) {
for (tir in tirs) {
when (tir) {
is TIR.NOP -> Unit
is TIR.MOV -> stms += tir.dst.expr.setTo(tir.src.expr.castTo(tir.dst.type))
is TIR.INSTANCEOF -> stms += tir.dst.expr.setTo(AstExpr.INSTANCE_OF(tir.src.expr, tir.type as AstType.Reference))
is TIR.CONV -> stms += tir.dst.expr.setTo(tir.src.expr.castTo(tir.dst.type))
is TIR.ARRAYLENGTH -> stms += tir.dst.expr.setTo(AstExpr.ARRAY_LENGTH(tir.obj.expr))
is TIR.NEWARRAY -> stms += tir.dst.expr.setTo(AstExpr.NEW_ARRAY(tir.arrayType, tir.lens.map { it.expr }))
is TIR.UNOP -> stms += tir.dst.expr.setTo(AstExpr.UNOP(tir.op, tir.r.expr))
is TIR.BINOP -> {
val leftType = when (tir.op) {
AstBinop.LCMP, AstBinop.EQ, AstBinop.NE, AstBinop.GE, AstBinop.LE, AstBinop.GT, AstBinop.LT -> tir.l.type
AstBinop.CMPG, AstBinop.CMPL -> AstType.DOUBLE
else -> tir.dst.type
}
val rightType = when (tir.op) {
AstBinop.SHL, AstBinop.SHR, AstBinop.USHR -> AstType.INT
else -> leftType
}
stms += tir.dst.expr.setTo(AstExpr.BINOP(tir.dst.type, tir.l.expr.castTo(leftType), tir.op, tir.r.expr.castTo(rightType)))
}
is TIR.ARRAY_STORE -> {
stms += AstStm.SET_ARRAY(tir.array.expr, tir.index.expr, tir.value.expr.castTo(tir.elementType.convertType()))
}
is TIR.ARRAY_LOAD -> {
stms += tir.dst.expr.setTo(AstExpr.ARRAY_ACCESS(tir.array.expr, tir.index.expr))
}
is TIR.GETSTATIC -> stms += tir.dst.expr.setTo(AstExpr.FIELD_STATIC_ACCESS(tir.field))
is TIR.GETFIELD -> stms += tir.dst.expr.setTo(AstExpr.FIELD_INSTANCE_ACCESS(tir.field, tir.obj.expr.castTo(tir.field.containingTypeRef)))
is TIR.PUTSTATIC -> stms += AstStm.SET_FIELD_STATIC(tir.field, tir.src.expr.castTo(tir.field.type))
is TIR.PUTFIELD -> stms += AstStm.SET_FIELD_INSTANCE(tir.field, tir.obj.expr.castTo(tir.field.containingTypeRef), tir.src.expr.castTo(tir.field.type))
is TIR.INVOKE_COMMON -> {
val method = tir.method
val args = tir.args.zip(method.type.args).map { it.first.expr.castTo(it.second.type) }
val expr = if (tir.obj != null) {
AstExpr.CALL_INSTANCE(tir.obj!!.expr.castTo(tir.method.containingClassType), tir.method, args, isSpecial = tir.isSpecial)
} else {
AstExpr.CALL_STATIC(tir.method, args, isSpecial = tir.isSpecial)
}
if (tir is TIR.INVOKE) {
stms += tir.dst.expr.setTo(expr)
} else {
stms += AstStm.STM_EXPR(expr)
}
}
is TIR.MONITOR -> stms += if (tir.enter) AstStm.MONITOR_ENTER(tir.obj.expr) else AstStm.MONITOR_EXIT(tir.obj.expr)
// control flow:
is TIR.LABEL -> stms += AstStm.STM_LABEL(tir.label.ast)
is TIR.JUMP -> stms += AstStm.GOTO(tir.label.ast)
is TIR.JUMP_IF -> {
val t1 = tir.l.expr.type
stms += AstStm.IF_GOTO(tir.label.ast, AstExpr.BINOP(AstType.BOOL, tir.l.expr, tir.op, tir.r.expr.castTo(t1)))
}
is TIR.SWITCH_GOTO -> stms += AstStm.SWITCH_GOTO(
tir.subject.expr,
tir.deflt.ast,
tir.cases.entries.groupBy { it.value }.map { it.value.map { it.key } to it.key.ast }
)
is TIR.RET -> {
//if (methodType.ret == AstType.REF("j.ClassInfo")) {
// println("go!")
//}
stms += if (tir.v != null) AstStm.RETURN(tir.v.expr.castTo(methodType.ret)) else AstStm.RETURN_VOID()
}
is TIR.THROW -> stms += AstStm.THROW(tir.ex.expr)
//is TIR.PHI_PLACEHOLDER -> stms += AstStm.NOP("PHI_PLACEHOLDER")
else -> TODO("$tir")
}
}
}
}
| apache-2.0 | aa0e1efcf5e1aab157a1712214f70def | 39.811475 | 154 | 0.658164 | 2.790919 | false | false | false | false |
http4k/http4k | http4k-multipart/src/main/kotlin/org/http4k/multipart/TokenBoundedInputStream.kt | 1 | 4170 | package org.http4k.multipart
import java.io.IOException
import java.io.InputStream
import java.nio.charset.Charset
internal class TokenBoundedInputStream @JvmOverloads constructor(inputStream: InputStream, bufSize: Int, private val maxStreamLength: Int = -1) : CircularBufferedInputStream(inputStream, bufSize) {
/**
* Consumes all bytes up to and including the matched endOfToken bytes.
* Fills the buffer with all bytes excluding the endOfToken bytes.
* Returns the number of bytes inserted into the buffer.
*
* @param endOfToken bytes that indicate the end of this token
* @param buffer fills this buffer with bytes _excluding_ the endOfToken
* @param encoding Charset for formatting error messages
* @return number of bytes inserted into buffer
* @throws IOException
*/
fun getBytesUntil(endOfToken: ByteArray, buffer: ByteArray, encoding: Charset): Int {
var bufferIndex = 0
val bufferLength = buffer.size
var b: Int
while (true) {
b = readFromStream()
if (b < 0) {
throw TokenNotFoundException(
"Reached end of stream before finding Token <<${String(endOfToken, encoding)}>>. Last ${endOfToken.size} bytes read were <<${getBytesRead(endOfToken, buffer, bufferIndex, encoding)}>>")
}
if (bufferIndex >= bufferLength) {
throw TokenNotFoundException("Didn't find end of Token <<${String(endOfToken, encoding)}>> within $bufferLength bytes")
}
val originalB = (b and 0x0FF).toByte()
if (originalB == endOfToken[0]) {
mark(endOfToken.size)
if (matchToken(endOfToken, b)) {
return bufferIndex
}
reset()
}
buffer[bufferIndex++] = originalB
}
}
private fun getBytesRead(endOfToken: ByteArray, buffer: ByteArray, bufferIndex: Int, encoding: Charset): String {
val index: Int
val length: Int
if (bufferIndex - endOfToken.size > 0) {
index = bufferIndex - endOfToken.size
length = endOfToken.size
} else {
index = 0
length = bufferIndex
}
return String(buffer, index, length, encoding)
}
private fun matchToken(token: ByteArray, initialCharacter: Int): Boolean {
var initialChar = initialCharacter
var eotIndex = 0
while (initialChar > -1 && initialChar.toByte() == token[eotIndex] && ++eotIndex < token.size) {
initialChar = readFromStream()
}
return eotIndex == token.size
}
/**
* Tries to match the token bytes at the current position. Only consumes bytes
* if there is a match, otherwise the stream is unaffected.
*
* @param token The token being matched
* @return true if the token is found (and the bytes have been consumed),
* false if it isn't found (and the stream is unchanged)
*/
fun matchInStream(token: ByteArray): Boolean {
mark(token.size)
if (matchToken(token, readFromStream())) return true
reset()
return false
}
/**
* returns a single byte from the Stream until the token is found. When the token is found,
* -2 will be returned. The token will be consumed.
*
* @param token bytes that indicate the end of this token
* @return the next byte in the stream, -1 if the underlying stream has finished,
* or -2 if the token is found. The token is consumed when it is matched.
*/
fun readByteFromStreamUnlessTokenMatched(token: ByteArray): Int {
val b = readFromStream()
if (b.toByte() == token[0]) {
mark(token.size)
if (matchToken(token, b)) return -2
reset()
}
return b
}
private fun readFromStream(): Int {
if (maxStreamLength > -1 && cursor >= maxStreamLength) throw StreamTooLongException("Form contents was longer than $maxStreamLength bytes")
return read()
}
fun currentByteIndex(): Long = cursor
}
| apache-2.0 | 5fdeaf0173ac29e76e0b2e89f86566a0 | 35.578947 | 205 | 0.617986 | 4.537541 | false | false | false | false |
VisualDig/visualdig-kotlin | dig/src/main/io/visualdig/BrowserLauncher.kt | 1 | 2483 | package io.visualdig
import java.io.File
import java.net.URI
import java.util.*
import java.util.Locale.ENGLISH
open class BrowserLauncher(val env : Map<String, String>,
val commandRunner: CommandRunner,
val operatingSystem: OperatingSystem) {
private var browserProcess : Process? = null
private val dirsToDelete : MutableList<File> = ArrayList()
open fun launchBrowser(uri : URI, headless: Boolean = false) : Boolean {
if(operatingSystem.isOSX()) {
if(headless) throw NotImplementedError("Headless OSX is not implemented")
val browserPath = env["DIG_BROWSER"] ?: "\"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\""
val url = uri.toURL().toExternalForm()
if(browserPath.toLowerCase(ENGLISH).contains("firefox")) {
return launchFirefox(browserPath, url)
} else if(browserPath.toLowerCase(ENGLISH).contains("chrome")) {
return launchChrome(browserPath, url)
}
} else if(operatingSystem.isLinux()) {
var browserPath = env["DIG_BROWSER"] ?: "google-chrome"
if(headless) {
browserPath = "xvfb-run $browserPath"
}
val url = uri.toURL().toExternalForm()
if(browserPath.toLowerCase(ENGLISH).contains("firefox")) {
return launchFirefox(browserPath, url)
} else if(browserPath.toLowerCase(ENGLISH).contains("chrome")) {
return launchChrome(browserPath, url)
}
}
return false
}
open fun stopBrowser() {
Thread.sleep(100)
browserProcess?.destroy()
browserProcess = null
dirsToDelete.forEach(File::deleteOnExit)
}
private fun launchFirefox(browserCommand: String?, url : String?) : Boolean {
val dir = File("/")
val command = "$browserCommand -safe-mode \"$url\""
browserProcess = commandRunner.runCommand(command, dir)
return true
}
private fun launchChrome(browserCommand: String?, url : String?) : Boolean {
val dir = File("/")
val random = Random().nextInt()
dirsToDelete.add(File("/tmp/$random"))
val switches = "--app=\"$url\" --no-first-run --user-data-dir=/tmp/$random --disk-cache-dir=/dev/null"
browserProcess = commandRunner.runCommand("$browserCommand $switches", dir)
return true
}
} | mit | e1090aeea8ac80230051c5192df86c4d | 36.636364 | 118 | 0.608135 | 4.649813 | false | false | false | false |
androidthings/endtoend-base | companionApp/src/main/java/com/example/androidthings/endtoend/companion/device/GizmoDetailViewModel.kt | 1 | 2951 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.androidthings.endtoend.companion.device
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.ViewModel
import com.example.androidthings.endtoend.companion.auth.AuthProvider
import com.example.androidthings.endtoend.companion.data.ToggleCommand
import com.example.androidthings.endtoend.companion.domain.LoadGizmoDetailUseCase
import com.example.androidthings.endtoend.companion.domain.SendToggleCommandParameters
import com.example.androidthings.endtoend.companion.domain.SendToggleCommandUseCase
import com.example.androidthings.endtoend.companion.util.Event
import com.example.androidthings.endtoend.shared.data.model.Toggle
import com.example.androidthings.endtoend.shared.domain.Result
class GizmoDetailViewModel(
private val authProvider: AuthProvider,
private val loadGizmoDetailUseCase: LoadGizmoDetailUseCase,
private val sendToggleCommandUseCase: SendToggleCommandUseCase
) : ViewModel() {
// We can't load until we have a gizmo ID, so use this to check.
private var gizmoId: String? = null
val gizmoLiveData = loadGizmoDetailUseCase.observe()
// Used to show error events in the UI.
private val sendToggleCommandErrorLiveDataInternal = MediatorLiveData<Event<ToggleCommand>>()
val sendToggleCommandErrorLiveData: LiveData<Event<ToggleCommand>>
get() = sendToggleCommandErrorLiveDataInternal
init {
sendToggleCommandErrorLiveDataInternal.addSource(sendToggleCommandUseCase.observe()) {
if (it.result is Result.Error) {
sendToggleCommandErrorLiveDataInternal.postValue(Event(it.command))
}
}
}
fun setGizmoId(gizmoId: String) {
if (this.gizmoId != gizmoId) {
this.gizmoId = gizmoId
loadGizmoDetailUseCase.execute(gizmoId)
}
}
fun onToggleClicked(toggle: Toggle) {
val gizmoId = gizmoId ?: return
val user = authProvider.userLiveData.value ?: return
// Send toggle command
sendToggleCommandUseCase.execute(
SendToggleCommandParameters(
user.uid,
ToggleCommand(gizmoId, toggle.id, !toggle.on),
TOGGLE_COMMAND_TIMEOUT
)
)
}
}
private const val TOGGLE_COMMAND_TIMEOUT = 1000L * 10 // 10 seconds
| apache-2.0 | 7cec9e452c354fdaa262b14e4a55f268 | 37.828947 | 97 | 0.736361 | 4.526074 | false | false | false | false |
iMeePwni/LCExercise | src/main/kotlin/MergeTwoTrees.kt | 1 | 535 | /**
* Created by guofeng on 2017/6/19.
* https://leetcode.com/problems/merge-two-binary-trees/#/description
*/
class MergeTwoTrees {
fun solution(t1: TreeNode?, t2: TreeNode?): TreeNode? {
if (t1 == null && t2 == null) return null
return TreeNode((t1?.middle ?: 0) + (t2?.middle ?: 0),
solution(t1?.left, t2?.left),
solution(t1?.right, t2?.right))
}
}
data class TreeNode(
var middle: Int,
var left: TreeNode? = null,
var right: TreeNode? = null
) | apache-2.0 | a1cc0603bede63d99f1e5d1087a07d73 | 23.363636 | 69 | 0.564486 | 3.429487 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/event/repository/EventRepository.kt | 1 | 2258 | package mixit.event.repository
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import kotlinx.coroutines.reactor.awaitSingle
import mixit.event.model.Event
import org.slf4j.LoggerFactory
import org.springframework.core.io.ClassPathResource
import org.springframework.data.domain.Sort
import org.springframework.data.mongodb.core.ReactiveMongoTemplate
import org.springframework.data.mongodb.core.count
import org.springframework.data.mongodb.core.find
import org.springframework.data.mongodb.core.findById
import org.springframework.data.mongodb.core.findOne
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.data.mongodb.core.remove
import org.springframework.stereotype.Repository
import java.time.Duration
@Repository
class EventRepository(
private val template: ReactiveMongoTemplate,
private val objectMapper: ObjectMapper
) {
private val logger = LoggerFactory.getLogger(this.javaClass)
fun initData() {
if (count().block() == 0L) {
val eventsResource = ClassPathResource("data/events.json")
val events: List<Event> = objectMapper.readValue(eventsResource.inputStream)
events.forEach { save(it).block(Duration.ofSeconds(10)) }
logger.info("Events data initialization complete")
}
}
fun count() =
template.count<Event>()
fun findAll() =
template.find<Event>(Query().with(Sort.by("year"))).doOnComplete { logger.info("Load all events") }
suspend fun coFindAll() =
findAll().collectList().awaitSingle()
fun findOne(id: String) =
template.findById<Event>(id).doOnSuccess { logger.info("Try to find event $id") }
suspend fun coFindOne(id: String) =
findOne(id).awaitSingle()
fun deleteAll() =
template.remove<Event>(Query())
fun save(event: Event) =
template.save(event)
fun findByYear(year: Int) =
template.findOne<Event>(Query(Criteria.where("year").isEqualTo(year)))
suspend fun coFindByYear(year: Int) =
findByYear(year).awaitSingle()
}
| apache-2.0 | 4be0a89dbfc263a2c6c9d490d1e9ed5a | 33.738462 | 107 | 0.733835 | 4.228464 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/place_name/AddPlaceNameForm.kt | 1 | 3402 | package de.westnordost.streetcomplete.quests.place_name
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import android.view.View
import androidx.core.os.ConfigurationCompat
import de.westnordost.osmfeatures.Feature
import de.westnordost.osmfeatures.StringUtils
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.databinding.QuestPlacenameBinding
import de.westnordost.streetcomplete.ktx.geometryType
import de.westnordost.streetcomplete.ktx.toTypedArray
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.AnswerItem
import de.westnordost.streetcomplete.quests.shop_type.SearchAdapter
import de.westnordost.streetcomplete.util.TextChangedWatcher
class AddPlaceNameForm : AbstractQuestFormAnswerFragment<PlaceNameAnswer>() {
override val contentLayoutResId = R.layout.quest_placename
private val binding by contentViewBinding(QuestPlacenameBinding::bind)
override val otherAnswers = listOf(
AnswerItem(R.string.quest_generic_answer_noSign) { confirmNoName() }
)
private val placeName get() = binding.nameInput.text?.toString().orEmpty().trim()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.nameInput.setAdapter(SearchAdapter(requireContext(), { term -> getFeatures(term) }, { it.name }))
binding.nameInput.addTextChangedListener(TextChangedWatcher { checkIsFormComplete() })
}
override fun onClickOk() {
val feature = getSelectedFeature()
if (feature != null) {
applyAnswer(BrandFeature(feature.addTags))
} else {
applyAnswer(PlaceName(placeName))
}
}
private fun confirmNoName() {
val ctx = context ?: return
AlertDialog.Builder(ctx)
.setTitle(R.string.quest_generic_confirmation_title)
.setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> applyAnswer(NoPlaceNameSign) }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
}
override fun isFormComplete() = placeName.isNotEmpty()
private fun getSelectedFeature(): Feature? {
val input = placeName
return getFeatures(input).firstOrNull()?.takeIf { it.canonicalName == StringUtils.canonicalize(input) }
}
private fun getFeatures(startsWith: String): List<Feature> {
val elementFeature = getOsmElementFeature() ?: return emptyList()
val localeList = ConfigurationCompat.getLocales(requireContext().resources.configuration)
return featureDictionary
.byTerm(startsWith.trim())
.forGeometry(osmElement!!.geometryType)
.inCountry(countryInfo.countryCode)
.forLocale(*localeList.toTypedArray())
.isSuggestion(true)
.find()
// filter to those brands that fit on how the thing is tagged now
.filter { feature ->
elementFeature.tags.all { feature.tags[it.key] == it.value }
}
}
private fun getOsmElementFeature(): Feature? {
return featureDictionary
.byTags(osmElement!!.tags)
.forGeometry(osmElement!!.geometryType)
.isSuggestion(false)
.find()
.firstOrNull()
}
}
| gpl-3.0 | 5199dd9c1eb01e66cfc09b2070bbd90e | 38.55814 | 113 | 0.701058 | 4.853067 | false | false | false | false |
cfig/Nexus_boot_image_editor | bbootimg/src/main/kotlin/avb/alg/Algorithm.kt | 2 | 950 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package avb.alg
data class Algorithm(
val name: String = "NONE",
val algorithm_type: Int = 0,
val hash_name: String = "",
val hash_num_bytes: Int = 0,
val signature_num_bytes: Int = 0,
val public_key_num_bytes: Int = 0,
val padding: ByteArray = byteArrayOf(),
val defaultKey: String ="") | apache-2.0 | b04a37ddb2515f59143e7b9dd5b715f8 | 37.04 | 75 | 0.681053 | 4.094828 | false | false | false | false |
openMF/self-service-app | app/src/main/java/org/mifos/mobile/models/accounts/savings/Currency.kt | 1 | 756 | package org.mifos.mobile.models.accounts.savings
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Currency(
@SerializedName("code")
var code: String? = null,
@SerializedName("name")
var name: String? = null,
@SerializedName("decimalPlaces")
var decimalPlaces: Int? = null,
@SerializedName("inMultiplesOf")
var inMultiplesOf: Int? = null,
@SerializedName("displaySymbol")
var displaySymbol: String? = null,
@SerializedName("nameCode")
var nameCode: String? = null,
@SerializedName("displayLabel")
var displayLabel: String? = null
) : Parcelable | mpl-2.0 | fa1e25b73297b826252a015d609dd700 | 24.233333 | 49 | 0.660053 | 4.447059 | false | false | false | false |
songzhw/Hello-kotlin | AdvancedJ/src/main/kotlin/pitfall/FiltrerDemo.kt | 1 | 277 | package pitfall
fun main(args: Array<String>) {
val list = listOf<Int>(2, 3, 4, 5, 6)
list.filter { it % 2 == 0 }
.forEach{ println(it)} //=> 2, 4, 6
println("=========")
list.takeWhile { it % 2 == 0 }
.forEach{ println(it)} //=> 2
} | apache-2.0 | 4b85c3f1231b0ae12fd7ef1be37c1a07 | 20.384615 | 47 | 0.472924 | 3.183908 | false | false | false | false |
Vlad-Popa/Filtrin | src/main/java/controller/ChartController.kt | 1 | 4680 | /*
* Copyright (C) 2015 Vlad Popa
*
* 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 controller
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.geometry.Insets
import javafx.scene.chart.LineChart
import javafx.scene.chart.NumberAxis
import javafx.scene.input.ScrollEvent
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import javafx.util.converter.NumberStringConverter
import org.apache.commons.math3.util.Precision
import org.controlsfx.control.RangeSlider
import java.net.URL
import java.util.*
/**
* @author Vlad Popa on 7/24/2015.
*/
class ChartController : Initializable {
@FXML private val chart: LineChart<Number, Number>? = null
@FXML private val xAxis: NumberAxis? = null
@FXML private val yAxis: NumberAxis? = null
@FXML private val xSlider: RangeSlider? = null
@FXML private val ySlider: RangeSlider? = null
@FXML private val chartBox: VBox? = null
@FXML private val chartPane: HBox? = null
private var modifier: Boolean = false
private var insets1: Insets? = null
private var insets2: Insets? = null
private var insets3: Insets? = null
private var insets4: Insets? = null
override fun initialize(location: URL, resources: ResourceBundle) {
insets1 = Insets(0.0, 43.0, 0.0, 38.0)
insets2 = Insets(0.0, 57.0, 0.0, 38.0)
insets3 = Insets(0.0, 43.0, 0.0, 40.0)
insets4 = Insets(0.0, 57.0, 0.0, 40.0)
yAxis!!.label = "Beta-Factor Average"
xAxis!!.label = "Residue number"
xAxis.tickLabelFormatter = NumberStringConverter("#")
yAxis.tickLabelFormatter = NumberStringConverter("#0.0")
xSlider!!.lowValueProperty().bindBidirectional(xAxis.lowerBoundProperty())
ySlider!!.lowValueProperty().bindBidirectional(yAxis.lowerBoundProperty())
xSlider.highValueProperty().bindBidirectional(xAxis.upperBoundProperty())
ySlider.highValueProperty().bindBidirectional(yAxis.upperBoundProperty())
chartBox!!.children.remove(xSlider)
chartPane!!.children.remove(ySlider)
}
@FXML
private fun handleScroll(event: ScrollEvent) {
val deltaY = event.deltaY
if (modifier) {
if (deltaY > 0) {
xSlider!!.incrementLowValue()
xSlider.decrementHighValue()
} else {
xSlider!!.decrementLowValue()
xSlider.incrementHighValue()
}
} else if (deltaY < 0) {
if (xAxis!!.upperBound < xSlider!!.max) {
xSlider.incrementLowValue()
xSlider.incrementHighValue()
}
} else if (xAxis!!.lowerBound > xSlider!!.min) {
xSlider.decrementLowValue()
xSlider.decrementHighValue()
}
}
fun getChart(): LineChart<Number, Number>? {
return chart
}
fun setBounds(values: DoubleArray) {
val xTickUnit = Precision.round((0.1 * values[1]), -1)
val yTickUnit = Precision.round((0.2 * values[3]), 0)
xSlider!!.min = values[0]
ySlider!!.min = values[2]
xSlider.max = values[1]
ySlider.max = values[3]
xSlider.lowValue = values[0]
ySlider.lowValue = values[2]
xSlider.highValue = values[1]
ySlider.highValue = values[3]
xAxis!!.tickUnit = xTickUnit
yAxis!!.tickUnit = yTickUnit
}
fun setModifier(value: Boolean) {
modifier = value
}
fun showVSlider(value: Boolean) {
if (value) {
chartPane!!.children.remove(ySlider)
} else {
chartPane!!.children.add(ySlider)
}
}
fun showHSlider(value: Boolean) {
if (value) {
chartBox!!.children.remove(xSlider)
} else {
chartBox!!.children.add(xSlider)
}
}
fun setPadding(b: Boolean, value: Boolean) {
if (value && b) {
xSlider!!.padding = insets2
} else if (value) {
xSlider!!.padding = insets1
} else if (b) {
xSlider!!.padding = insets4
} else {
xSlider!!.padding = insets3
}
}
}
| apache-2.0 | 032e3a54e3b7c113ac3d495171e3c022 | 31.957746 | 82 | 0.628205 | 4.006849 | false | false | false | false |
FHannes/intellij-community | platform/lang-api/src/com/intellij/execution/RunManager.kt | 4 | 9211 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.ConfigurationType
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.configurations.RunProfile
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.text.nullize
import java.util.regex.Pattern
/**
* Manages the list of run/debug configurations in a project.
* @see RunnerRegistry
* @see ExecutionManager
*/
abstract class RunManager {
companion object {
@JvmStatic
fun getInstance(project: Project): RunManager {
if (!(IS_RUN_MANAGER_INITIALIZED.get(project) ?: false)) {
// https://gist.github.com/develar/5bcf39b3f0ec08f507ec112d73375f2b
LOG.debug("Must be not called before project components initialized")
}
return ServiceManager.getService(project, RunManager::class.java)
}
@JvmStatic
fun suggestUniqueName(str: String, currentNames: Collection<String>): String {
if (!currentNames.contains(str)) return str
val matcher = Pattern.compile("(.*?)\\s*\\(\\d+\\)").matcher(str)
val originalName = if (matcher.matches()) matcher.group(1) else str
var i = 1
while (true) {
val newName = String.format("%s (%d)", originalName, i)
if (!currentNames.contains(newName)) return newName
i++
}
}
}
/**
* Returns the list of all registered configuration types.
*/
abstract val configurationFactories: Array<ConfigurationType>
abstract val configurationFactoriesWithoutUnknown: List<ConfigurationType>
/**
* Returns the list of all configurations of a specified type.
* @param type a run configuration type.
* @return all configurations of the type, or an empty array if no configurations of the type are defined.
*/
@Deprecated("", ReplaceWith("getConfigurationsList(type)"))
fun getConfigurations(type: ConfigurationType) = getConfigurationsList(type).toTypedArray()
/**
* Returns the list of all configurations of a specified type.
* @param type a run configuration type.
* @return all configurations of the type, or an empty array if no configurations of the type are defined.
*/
abstract fun getConfigurationsList(type: ConfigurationType): List<RunConfiguration>
/**
* Returns the list of [RunnerAndConfigurationSettings] for all configurations of a specified type.
* @param type a run configuration type.
* @return settings for all configurations of the type, or an empty array if no configurations of the type are defined.
*/
@Deprecated("", ReplaceWith("getConfigurationSettingsList(type)"))
fun getConfigurationSettings(type: ConfigurationType) = getConfigurationSettingsList(type).toTypedArray()
/**
* Returns the list of [RunnerAndConfigurationSettings] for all configurations of a specified type.
*
* Template configuration is not included
* @param type a run configuration type.
* @return settings for all configurations of the type, or an empty array if no configurations of the type are defined.
*/
abstract fun getConfigurationSettingsList(type: ConfigurationType): List<RunnerAndConfigurationSettings>
/**
* Returns the list of all run configurations.
*/
@Deprecated("", ReplaceWith("allConfigurationsList"))
fun getAllConfigurations() = allConfigurationsList.toTypedArray()
/**
* Returns the list of all run configurations.
*/
abstract val allConfigurationsList: List<RunConfiguration>
/**
* Returns the list of all run configurations settings.
*/
abstract val allSettings: List<RunnerAndConfigurationSettings>
/**
* Returns the list of all temporary run configurations settings.
* @see RunnerAndConfigurationSettings.isTemporary
*/
abstract val tempConfigurationsList: List<RunnerAndConfigurationSettings>
/**
* Saves the specified temporary run settings and makes it a permanent one.
* @param settings the temporary settings to save.
*/
abstract fun makeStable(settings: RunnerAndConfigurationSettings)
/**
* The selected item in the run/debug configurations combobox.
*/
abstract var selectedConfiguration: RunnerAndConfigurationSettings?
/**
* Creates a configuration of the specified type with the specified name. Note that you need to call
* [.addConfiguration] if you want the configuration to be persisted in the project.
* @param name the name of the configuration to create (should be unique and not equal to any other existing configuration)
* @param factory the factory instance.
* @see RunManager.suggestUniqueName
*/
abstract fun createConfiguration(name: String, factory: ConfigurationFactory): RunnerAndConfigurationSettings
fun createRunConfiguration(name: String, factory: ConfigurationFactory) = createConfiguration(name, factory)
/**
* Creates a configuration settings object based on a specified [RunConfiguration]. Note that you need to call
* [.addConfiguration] if you want the configuration to be persisted in the project.
* @param runConfiguration the run configuration
* @param factory the factory instance.
*/
abstract fun createConfiguration(runConfiguration: RunConfiguration, factory: ConfigurationFactory): RunnerAndConfigurationSettings
/**
* Returns the template settings for the specified configuration type.
* @param factory the configuration factory.
*/
abstract fun getConfigurationTemplate(factory: ConfigurationFactory): RunnerAndConfigurationSettings
/**
* Adds the specified run configuration to the list of run configurations.
*/
abstract fun addConfiguration(settings: RunnerAndConfigurationSettings)
/**
* Adds the specified run configuration to the list of run configurations stored in the project.
* @param settings the run configuration settings.
* @param isShared true if the configuration is marked as shared (stored in the versioned part of the project files), false if it's local
* * (stored in the workspace file).
*/
abstract fun addConfiguration(settings: RunnerAndConfigurationSettings, isShared: Boolean)
/**
* Marks the specified run configuration as recently used (the temporary run configurations are deleted in LRU order).
* @param profile the run configuration to mark as recently used.
*/
abstract fun refreshUsagesList(profile: RunProfile)
abstract fun hasSettings(settings: RunnerAndConfigurationSettings): Boolean
fun suggestUniqueName(name: String?, type: ConfigurationType?): String {
val settingsList = if (type == null) allSettings else getConfigurationSettingsList(type)
return suggestUniqueName(name.nullize() ?: UNNAMED, settingsList.map { it.name })
}
/**
* Sets unique name if existing one is not 'unique'
* If settings type is not null (for example settings may be provided by plugin that is unavailable after IDE restart, so type would be suddenly null)
* name will be chosen unique for certain type otherwise name will be unique among all configurations
* @return `true` if name was changed
*/
fun setUniqueNameIfNeed(settings: RunnerAndConfigurationSettings): Boolean {
val oldName = settings.name
settings.name = suggestUniqueName(StringUtil.notNullize(oldName, UNNAMED), settings.type)
return oldName != settings.name
}
/**
* Sets unique name if existing one is not 'unique' for corresponding configuration type
* @return `true` if name was changed
*/
fun setUniqueNameIfNeed(configuration: RunConfiguration): Boolean {
val oldName = configuration.name
configuration.name = suggestUniqueName(StringUtil.notNullize(oldName, UNNAMED), configuration.type)
return oldName != configuration.name
}
abstract fun getConfigurationType(typeName: String): ConfigurationType?
abstract fun findConfigurationByName(name: String?): RunnerAndConfigurationSettings?
fun findConfigurationByTypeAndName(typeId: String, name: String) = allSettings.firstOrNull { typeId == it.type.id && name == it.name }
abstract fun removeConfiguration(settings: RunnerAndConfigurationSettings?)
abstract fun setTemporaryConfiguration(tempConfiguration: RunnerAndConfigurationSettings?)
}
private val UNNAMED = "Unnamed"
val IS_RUN_MANAGER_INITIALIZED = Key.create<Boolean>("RunManagerInitialized")
private val LOG = Logger.getInstance(RunManager::class.java) | apache-2.0 | e243ba848bc98a6d00c80154264e8a4b | 40.872727 | 152 | 0.75475 | 5.055434 | false | true | false | false |
myTargetSDK/mytarget-android | myTargetDemo/buildSrc/src/main/kotlin/versions.kt | 1 | 732 | const val KOTLIN_VERSION = "1.5.31"
object Plugins {
const val AGP = "4.2.1"
const val KARUMI = "3.0.0"
const val VERSIONS = "0.39.0"
}
object AndroidX {
const val multidex = "2.0.1"
const val appcompat = "1.3.1"
const val material = "1.3.0"
const val cardview = "1.0.0"
const val recyclerview = "1.2.1"
const val constraint = "2.1.1"
const val navigation = "2.3.5"
const val preference = "1.1.1"
}
object Google {
const val exoplayer = "2.17.1"
const val play = "17.1.0"
}
object Test{
const val core = "1.4.0"
const val junit = "4.13.2"
const val runner = "1.4.0"
const val rules = "1.4.0"
const val espresso = "3.3.0"
const val barista = "2.7.0"
}
| lgpl-3.0 | e9179b50c48841f8d859e6087e761120 | 21.181818 | 36 | 0.583333 | 2.623656 | false | false | false | false |
d3xter/bo-android | app/src/main/java/org/blitzortung/android/app/WidgetProvider.kt | 1 | 1686 | /*
Copyright 2015 Andreas Würl
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.blitzortung.android.app
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.widget.RemoteViews
import org.blitzortung.android.app.view.AlertView
class WidgetProvider : AppWidgetProvider() {
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
val N = appWidgetIds.size
for (i in 0..N - 1) {
val appWidgetId = appWidgetIds[i]
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
private fun updateAppWidget(context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int) {
val alertView = AlertView(context)
alertView.measure(150, 150)
alertView.layout(0, 0, 150, 150)
alertView.isDrawingCacheEnabled = true
val bitmap = alertView.drawingCache
val remoteViews = RemoteViews(context.packageName,
R.layout.widget)
remoteViews.setImageViewBitmap(R.layout.widget, bitmap)
}
}
| apache-2.0 | 6b07fd78b720e9b1ff6ddf27385ca54c | 31.403846 | 105 | 0.712166 | 4.786932 | false | false | false | false |
NextFaze/dev-fun | test/src/test/java/com/nextfaze/devfun/test/tests/TestCategories.kt | 1 | 5434 | package com.nextfaze.devfun.test.tests
import com.nextfaze.devfun.internal.log.*
import com.nextfaze.devfun.internal.splitSimpleName
import com.nextfaze.devfun.test.AbstractKotlinKapt3Tester
import com.nextfaze.devfun.test.TestContext
import com.nextfaze.devfun.test.combine
import com.nextfaze.devfun.test.singleFileTests
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
import tested.categories.CategoriesWithGroups
import tested.categories.CategoryOrderOverloading
import tested.categories.CategoryOrdering
import tested.categories.ContextAware
import tested.categories.FunctionDefinedCategory
import tested.categories.IgnoreEmptyCategories
import tested.categories.co_ExpectedCategoryOrdering
import tested.categories.coo_ExpectedCategoryOrdering
import java.lang.reflect.Method
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.expect
@Test(groups = ["kapt", "compile", "supported", "category"])
class TestCategories : AbstractKotlinKapt3Tester() {
private val log = logger()
//
// IgnoreEmptyCategories
//
@DataProvider(name = "testCategoriesIgnoreEmptyData")
fun testCategoriesIgnoreEmptyData(testMethod: Method) = singleFileTests(testMethod, IgnoreEmptyCategories::class, useSdkInt = 10)
@Test(dataProvider = "testCategoriesIgnoreEmptyData", enabled = false, groups = ["requiresApi"])
fun testCategoriesIgnoreEmpty(test: TestContext) {
test.testInvocations(log)
// generated
val funCats = test.funDefs.map { it.clazz }.toSet()
val catDefNames = test.catDefs.map { it.name }.toSet()
val allCats = (test.catDefs.map { it.clazz } + funCats).toSet()
// processed
val actualCats = test.devFun.categories
// Loop all generated/possibly generated categories
allCats.forEach { cat ->
log.d { "cat=$cat" }
// Find all function definitions that have this category
val functionsWithCat = funCats.filter { it == cat }
// If no functions have this, then it should not be present in the final output
if (functionsWithCat.isEmpty()) {
log.d { "Category $cat is not referenced by any function definitions" }
val simpleName = cat?.splitSimpleName // todo
assertTrue("Category $cat is not referenced in any generated functions but is seen in final item set") {
actualCats.none { it.name == simpleName } &&
actualCats.all { ac -> catDefNames.none { it == ac.name } }
}
} else {
log.d { "Category $cat is referenced by ${functionsWithCat.size} function definitions: $functionsWithCat" }
// TODO...
}
}
}
//
// CategoryOrdering
//
@DataProvider(name = "testCategoryOrderingData")
fun testCategoryOrderingData(testMethod: Method) = singleFileTests(testMethod, CategoryOrdering::class)
@Test(dataProvider = "testCategoryOrderingData")
fun testCategoryOrdering(test: TestContext) {
val actualCats = test.devFun.categories.map { it.name }
actualCats.combine(co_ExpectedCategoryOrdering.order).forEach {
expect(it.second, "Ordering inconsistent") { it.first }
}
}
//
// CategoryOrderOverloading
//
@DataProvider(name = "testCategoryOrderOverloadingData")
fun testCategoryOrderOverloadingData(testMethod: Method) = singleFileTests(testMethod, CategoryOrderOverloading::class)
@Test(dataProvider = "testCategoryOrderOverloadingData")
fun testCategoryOrderOverloading(test: TestContext) {
val actualCats = test.devFun.categories.map { it.name }
val actualCatsAsStrList = actualCats.joinToString("\n")
val expectedCatsAsStrList = coo_ExpectedCategoryOrdering.order.joinToString("\n")
assertEquals(
actualCats.size,
coo_ExpectedCategoryOrdering.order.size,
"actualCats:\n$actualCatsAsStrList\n=== vs ===\ncoo_ExpectedCategoryOrdering.order:\n$expectedCatsAsStrList"
)
actualCats.combine(coo_ExpectedCategoryOrdering.order).forEach {
expect(it.second, "Ordering inconsistent:\n$actualCatsAsStrList\n=== vs ===\n$expectedCatsAsStrList") { it.first }
}
test.testInvocations(log)
}
//
// Functions with Category
//
@DataProvider(name = "testFunctionsWithCategoryData")
fun testFunctionsWithCategoryData(testMethod: Method) = singleFileTests(testMethod, FunctionDefinedCategory::class)
@Test(dataProvider = "testFunctionsWithCategoryData")
fun testFunctionsWithCategory(test: TestContext) = test.testInvocations(log)
//
// Categories with Groups
//
@DataProvider(name = "testCategoriesWithGroupsData")
fun testCategoriesWithGroupsData(testMethod: Method) = singleFileTests(testMethod, CategoriesWithGroups::class)
@Test(dataProvider = "testCategoriesWithGroupsData")
fun testCategoriesWithGroups(test: TestContext) = test.testInvocations(log)
//
// Context-aware Categories
//
@DataProvider(name = "testContextAwareData")
fun testContextAwareData(testMethod: Method) = singleFileTests(testMethod, ContextAware::class)
@Test(dataProvider = "testContextAwareData")
fun testContextAwareData(test: TestContext) = test.testInvocations(log)
}
| apache-2.0 | 8c1982cb1894902c7b882ff1e37cae44 | 37.814286 | 133 | 0.705374 | 4.385795 | false | true | false | false |
cwoolner/flex-poker | src/main/kotlin/com/flexpoker/table/command/aggregate/PotHandler.kt | 1 | 7484 | package com.flexpoker.table.command.aggregate
import com.flexpoker.table.command.events.PotAmountIncreasedEvent
import com.flexpoker.table.command.events.PotClosedEvent
import com.flexpoker.table.command.events.PotCreatedEvent
import com.flexpoker.table.command.events.TableEvent
import com.flexpoker.util.toPMap
import com.flexpoker.util.toPSet
import org.pcollections.PMap
import org.pcollections.PSet
import java.util.UUID
import java.util.function.Consumer
fun removePlayerFromAllPots(pots: PSet<PotState>, playerId: UUID): PSet<PotState> {
require(pots
.filter { it.handEvaluations.any { x -> x.playerId == playerId } }
.all { it.isOpen }) { "cannot remove player from a closed pot" }
return pots
.map { it.copy(handEvaluations = it.handEvaluations.filter { he -> he.playerId != playerId }.toPSet()) }
.toPSet()
}
fun addToPot(pots: PSet<PotState>, potId: UUID, amountToAdd: Int): PSet<PotState> {
return pots.map {
if (it.id == potId) {
require(it.isOpen) { "cannot add chips to a closed pot" }
it.copy(amount = it.amount + amountToAdd)
} else {
it
}
}.toPSet()
}
fun closePot(pots: PSet<PotState>, potId: UUID): PSet<PotState> {
val updatedPots = pots.map { if (it.id == potId) it.copy(isOpen = false) else it }.toPSet()
require(updatedPots.isNotEmpty()) { "attempting to close pot that does not exist" }
return updatedPots
}
fun addNewPot(pots: PSet<PotState>, handEvaluationList: List<HandEvaluation>,
potId: UUID, playersInvolved: Set<UUID?>): PSet<PotState> {
val handEvaluationsOfPlayersInPot = handEvaluationList.filter { playersInvolved.contains(it.playerId) }.toPSet()
require(handEvaluationsOfPlayersInPot.isNotEmpty()) { "trying to add a new pot with players that are not part of the hand" }
return pots.plus(PotState(potId, 0, true, handEvaluationsOfPlayersInPot))
}
fun fetchPlayersRequiredToShowCards(pots: PSet<PotState>, playersStillInHand: Set<UUID>): Set<UUID> {
return pots.fold(HashSet(), { acc, pot ->
acc.addAll(playersStillInHand.filter { forcePlayerToShowCards(pot, it) })
acc
})
}
fun fetchChipsWon(pots: PSet<PotState>, playersStillInHand: Set<UUID>): PMap<UUID, Int> {
val playersToChipsWonMap = HashMap<UUID, Int>()
pots.forEach(Consumer { pot: PotState ->
playersStillInHand.forEach(Consumer { playerInHand: UUID ->
val numberOfChipsWonForPlayer = chipsWon(pot, playerInHand)
val existingChipsWon = playersToChipsWonMap.getOrDefault(playerInHand, 0)
val newTotalOfChipsWon = numberOfChipsWonForPlayer + existingChipsWon
playersToChipsWonMap[playerInHand] = newTotalOfChipsWon
})
})
return playersToChipsWonMap.toPMap()
}
fun forcePlayerToShowCards(pot: PotState, playerInHand: UUID): Boolean {
return chipsWon(pot, playerInHand) > 0 && playersInvolved(pot).size > 1
}
private fun chipsWon(pot: PotState, playerInHand: UUID): Int {
return recalculateWinners(pot).getOrDefault(playerInHand, 0)
}
private fun playersInvolved(pot: PotState): PSet<UUID> {
return pot.handEvaluations.map { it.playerId!! }.toPSet()
}
private fun recalculateWinners(pot: PotState): PMap<UUID, Int> {
val chipsForPlayerToWin = mutableMapOf<UUID, Int>()
val playersInvolved = playersInvolved(pot)
val relevantHandEvaluationsForPot = pot.handEvaluations
.filter { playersInvolved.contains(it.playerId) }
.sortedDescending()
val winners = relevantHandEvaluationsForPot
.fold(ArrayList<HandEvaluation>(), { acc, handEvaluation ->
if (acc.isEmpty() || acc.first() <= handEvaluation ) {
acc.add(handEvaluation)
}
acc
})
.map { it.playerId!! }
.sorted()
val numberOfWinners = winners.size
val baseNumberOfChips = pot.amount / numberOfWinners
val bonusChips = pot.amount % numberOfWinners
winners.forEach { chipsForPlayerToWin[it] = baseNumberOfChips }
if (bonusChips >= 1) {
val randomNumber = DefaultRandomNumberGenerator().pseudoRandomIntBasedOnUUID(pot.id, winners.size)
chipsForPlayerToWin.compute(winners[randomNumber]) { _: UUID, chips: Int? -> chips!! + bonusChips }
}
return chipsForPlayerToWin.toPMap()
}
/**
* The general approach to calculating pots is as follows:
*
* 1. Discover all of the distinct numbers of chips in front of each player.
* For example, if everyone has 30 chips in front, 30 would be the only
* number in the distinct set. If two players had 10 and one person had 20,
* then 10 and 20 would be in the set.
*
* 2. Loop through each chip count, starting with the smallest, and shave
* off the number of chips from each stack in front of each player, and
* place them into an open pot.
*
* 3. If an open pot does not exist, create a new one.
*
* 4. If it's determined that a player is all-in, then the pot for that
* player's all-in should be closed. Multiple closed pots can exist, but
* only one open pot should ever exist at any given time.
*/
fun calculatePots(gameId: UUID, tableId: UUID, handId: UUID, pots: PSet<PotState>,
handEvaluationList: List<HandEvaluation>, chipsInFrontMap: Map<UUID, Int>,
chipsInBackMap: Map<UUID, Int>): Pair<List<TableEvent>, PSet<PotState>> {
var updatedPots = pots
val newPotEvents = ArrayList<TableEvent>()
val distinctChipsInFrontAmounts = chipsInFrontMap.values.filter { it != 0 }.distinct().sorted()
var totalOfPreviousChipLevelIncreases = 0
for (chipsPerLevel in distinctChipsInFrontAmounts) {
val openPotOptional = updatedPots.firstOrNull { it.isOpen }
val openPotId = openPotOptional?.id ?: UUID.randomUUID()
val playersAtThisChipLevel = chipsInFrontMap.filterValues { it >= chipsPerLevel }.map { it.key }.toSet()
if (openPotOptional == null) {
val potCreatedEvent = PotCreatedEvent(tableId, gameId, handId, openPotId, playersAtThisChipLevel)
newPotEvents.add(potCreatedEvent)
updatedPots = addNewPot(updatedPots, handEvaluationList, potCreatedEvent.potId, potCreatedEvent.playersInvolved)
}
// subtract the total of the previous levels from the current level
// before multiplying by the number of player, which will have the
// same effect as actually reducing that amount from each player
val increaseInChips = (chipsPerLevel - totalOfPreviousChipLevelIncreases) * playersAtThisChipLevel.size
totalOfPreviousChipLevelIncreases += chipsPerLevel
val potAmountIncreasedEvent = PotAmountIncreasedEvent(tableId, gameId, handId, openPotId, increaseInChips)
newPotEvents.add(potAmountIncreasedEvent)
updatedPots = addToPot(updatedPots, potAmountIncreasedEvent.potId, potAmountIncreasedEvent.amountIncreased)
// if a player bet, but no longer has any chips, then they are all
// in and the pot should be closed
if (playersAtThisChipLevel
.filter { chipsInFrontMap[it]!! >= 1 }
.filter { chipsInBackMap[it] == 0 }
.count() > 0) {
val potClosedEvent = PotClosedEvent(tableId, gameId, handId, openPotId)
newPotEvents.add(potClosedEvent)
updatedPots = closePot(updatedPots, potClosedEvent.potId)
}
}
return Pair(newPotEvents, updatedPots)
} | gpl-2.0 | ea1c75aa32a19ba03311b9492b91688c | 44.363636 | 128 | 0.698691 | 3.904017 | false | false | false | false |
neo4j-contrib/neo4j-apoc-procedures | extended/src/test/kotlin/apoc/nlp/azure/AzureVirtualKeyPhrasesGraphTest.kt | 1 | 8244 | package apoc.nlp.azure
import apoc.nlp.NodeMatcher
import apoc.nlp.RelationshipMatcher
import apoc.result.VirtualNode
import junit.framework.Assert.assertEquals
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.hasItem
import org.junit.Test
import org.neo4j.graphdb.Label
import org.neo4j.graphdb.RelationshipType
class AzureVirtualKeyPhrasesGraphTest {
@Test
fun `create virtual graph from result with one key phrase`() {
val sourceNode = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val res = listOf(
mapOf("id" to sourceNode.id.toString(), "keyPhrases" to listOf("foo")
))
val virtualGraph = AzureVirtualKeyPhrasesGraph(res, listOf(sourceNode), RelationshipType { "KEY_PHRASE" }).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(2, nodes.size)
assertThat(nodes, hasItem(sourceNode))
val barLabels = listOf( Label { "KeyPhrase" })
val barProperties = mapOf("text" to "foo")
assertThat(nodes, hasItem(NodeMatcher(barLabels, barProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(1, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, VirtualNode(barLabels.toTypedArray(), barProperties), "KEY_PHRASE")))
}
@Test
fun `create virtual graph from result with multiple key phrases`() {
val sourceNode = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val res = listOf(
mapOf("id" to sourceNode.id.toString(), "keyPhrases" to listOf("The Matrix", "The Notebook"))
)
val virtualGraph = AzureVirtualKeyPhrasesGraph(res, listOf(sourceNode), RelationshipType { "KEY_PHRASE" }).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(3, nodes.size)
assertThat(nodes, hasItem(sourceNode))
val matrixNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Matrix"))
val notebookNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Notebook"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(2, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, matrixNode, "KEY_PHRASE")))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, notebookNode, "KEY_PHRASE")))
}
@Test
fun `create virtual graph from result with duplicate entities`() {
val sourceNode = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val res = listOf(
mapOf("id" to sourceNode.id.toString(), "keyPhrases" to listOf("The Matrix", "The Matrix"))
)
val virtualGraph = AzureVirtualKeyPhrasesGraph(res, listOf(sourceNode), RelationshipType { "KEY_PHRASE" }).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(2, nodes.size)
assertThat(nodes, hasItem(sourceNode))
val matrixNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Matrix"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(1, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode, matrixNode, "KEY_PHRASE")))
}
@Test
fun `create virtual graph from result with multiple source nodes`() {
val sourceNode1 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val sourceNode2 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 5678L))
val res = listOf(
mapOf("id" to sourceNode1.id.toString(), "keyPhrases" to listOf("The Matrix", "The Notebook")),
mapOf("id" to sourceNode2.id.toString(), "keyPhrases" to listOf("Toy Story", "Titanic"))
)
val virtualGraph = AzureVirtualKeyPhrasesGraph(res, listOf(sourceNode1, sourceNode2), RelationshipType { "KEY_PHRASE" }).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(6, nodes.size)
assertThat(nodes, hasItem(sourceNode1))
assertThat(nodes, hasItem(sourceNode2))
val matrixNode = VirtualNode(arrayOf( Label{"KeyPhrase"}), mapOf("text" to "The Matrix"))
val notebookNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Notebook"))
val toyStoryNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "Toy Story"))
val titanicNode = VirtualNode(arrayOf( Label{"KeyPhrase"}), mapOf("text" to "Titanic"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(toyStoryNode.labels.toList(), toyStoryNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(titanicNode.labels.toList(), titanicNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(4, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, matrixNode, "KEY_PHRASE" )))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, notebookNode, "KEY_PHRASE")))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, toyStoryNode, "KEY_PHRASE")))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, titanicNode, "KEY_PHRASE")))
}
@Test
fun `create virtual graph from result with multiple source nodes with overlapping entities`() {
val sourceNode1 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 1234L))
val sourceNode2 = VirtualNode(arrayOf(Label {"Person"}), mapOf("id" to 5678L))
val res = listOf(
mapOf("id" to sourceNode1.id.toString(), "keyPhrases" to listOf("The Matrix", "The Notebook")),
mapOf("id" to sourceNode2.id.toString(), "keyPhrases" to listOf("Titanic", "The Matrix", "Top Boy")))
val virtualGraph = AzureVirtualKeyPhrasesGraph(res, listOf(sourceNode1, sourceNode2), RelationshipType { "KEY_PHRASE" }).create()
val nodes = virtualGraph.graph["nodes"] as Set<*>
assertEquals(6, nodes.size)
assertThat(nodes, hasItem(sourceNode1))
assertThat(nodes, hasItem(sourceNode2))
val matrixNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Matrix"))
val notebookNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "The Notebook"))
val titanicNode = VirtualNode(arrayOf(Label{"KeyPhrase"}), mapOf("text" to "Titanic"))
val topBoyNode = VirtualNode(arrayOf( Label{"KeyPhrase"}), mapOf("text" to "Top Boy"))
assertThat(nodes, hasItem(NodeMatcher(matrixNode.labels.toList(), matrixNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(notebookNode.labels.toList(), notebookNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(titanicNode.labels.toList(), titanicNode.allProperties)))
assertThat(nodes, hasItem(NodeMatcher(topBoyNode.labels.toList(), topBoyNode.allProperties)))
val relationships = virtualGraph.graph["relationships"] as Set<*>
assertEquals(5, relationships.size)
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, matrixNode, "KEY_PHRASE")))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode1, notebookNode, "KEY_PHRASE")))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, titanicNode, "KEY_PHRASE")))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, matrixNode, "KEY_PHRASE")))
assertThat(relationships, hasItem(RelationshipMatcher(sourceNode2, topBoyNode, "KEY_PHRASE")))
}
}
| apache-2.0 | 534d001186fe497a78445080539d115c | 49.268293 | 143 | 0.694687 | 4.327559 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/ReleasePropertyType.kt | 1 | 3813 | package net.nemerosa.ontrack.extension.general
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.extension.support.AbstractPropertyType
import net.nemerosa.ontrack.model.form.Form
import net.nemerosa.ontrack.model.form.Text
import net.nemerosa.ontrack.model.security.PromotionRunCreate
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.structure.ProjectEntity
import net.nemerosa.ontrack.model.structure.ProjectEntityType
import net.nemerosa.ontrack.model.structure.PropertySearchArguments
import net.nemerosa.ontrack.model.structure.SearchIndexService
import org.springframework.stereotype.Component
import java.util.*
import java.util.function.Function
@Component
class ReleasePropertyType(
extensionFeature: GeneralExtensionFeature,
private val searchIndexService: SearchIndexService,
private val releaseSearchExtension: ReleaseSearchExtension
) : AbstractPropertyType<ReleaseProperty>(extensionFeature) {
override fun getName(): String = "Release"
override fun getDescription(): String = "Release indicator on the build."
override fun getSupportedEntityTypes(): Set<ProjectEntityType> = EnumSet.of(ProjectEntityType.BUILD)
/**
* If one can promote a build, he can also attach a release label to a build.
*/
override fun canEdit(entity: ProjectEntity, securityService: SecurityService): Boolean {
return securityService.isProjectFunctionGranted(entity, PromotionRunCreate::class.java)
}
override fun canView(entity: ProjectEntity, securityService: SecurityService): Boolean = true
override fun onPropertyChanged(entity: ProjectEntity, value: ReleaseProperty) {
searchIndexService.createSearchIndex(releaseSearchExtension, ReleaseSearchItem(entity, value))
}
override fun onPropertyDeleted(entity: ProjectEntity, oldValue: ReleaseProperty) {
searchIndexService.deleteSearchIndex(releaseSearchExtension, ReleaseSearchItem(entity, oldValue).id)
}
override fun getEditionForm(entity: ProjectEntity, value: ReleaseProperty?): Form {
return Form.create()
.with(
Text.of("name")
.label("Release name")
.length(20)
.value(value?.name)
)
}
override fun fromClient(node: JsonNode): ReleaseProperty {
return fromStorage(node)
}
override fun fromStorage(node: JsonNode): ReleaseProperty {
return ReleaseProperty(
node.path("name").asText()
)
}
override fun replaceValue(value: ReleaseProperty, replacementFunction: Function<String, String>): ReleaseProperty {
return value
}
override fun containsValue(value: ReleaseProperty, propertyValue: String): Boolean =
if ("*" in propertyValue) {
val regex = propertyValue.replace("*", ".*").toRegex(RegexOption.IGNORE_CASE)
regex.matches(value.name)
} else {
value.name.equals(propertyValue, ignoreCase = true)
}
override fun getSearchArguments(token: String): PropertySearchArguments? {
return if (token.isNotBlank()) {
if ("*" in token) {
PropertySearchArguments(
null,
"pp.json->>'name' ilike :token",
mapOf("token" to token.replace("*", "%"))
)
} else {
PropertySearchArguments(
null,
"UPPER(pp.json->>'name') = UPPER(:token)",
mapOf("token" to token)
)
}
} else {
null
}
}
} | mit | 288dbd46ec39d4f1445bc006b545eb32 | 37.918367 | 119 | 0.65198 | 5.166667 | false | false | false | false |
goodwinnk/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/SingleWorkerProcessExecutor.kt | 1 | 2289 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Computable
import com.intellij.util.EventDispatcher
import com.intellij.util.concurrency.AppExecutorUtil
import org.jetbrains.annotations.CalledInAwt
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.Future
abstract class SingleWorkerProcessExecutor(private val progressManager: ProgressManager, name: String) : Disposable {
private val executor = AppExecutorUtil.createBoundedApplicationPoolExecutor(name, 1)
private var progressIndicator: EmptyProgressIndicator = NonReusableEmptyProgressIndicator()
private val processStateEventDispatcher = EventDispatcher.create(ProcessStateListener::class.java)
@CalledInAwt
protected fun <T> submit(task: (indicator: ProgressIndicator) -> T): Future<T> {
val indicator = progressIndicator
return executor.submit(Callable {
indicator.checkCanceled()
try {
runInEdt { processStateEventDispatcher.multicaster.processStarted() }
progressManager.runProcess(Computable { task(indicator) }, indicator)
}
finally {
runInEdt { processStateEventDispatcher.multicaster.processFinished() }
}
})
}
@CalledInAwt
protected fun cancelCurrentTasks() {
progressIndicator.cancel()
progressIndicator = NonReusableEmptyProgressIndicator()
}
fun addProcessListener(listener: ProcessStateListener, disposable: Disposable) =
processStateEventDispatcher.addListener(listener, disposable)
override fun dispose() {
progressIndicator.cancel()
executor.shutdownNow()
}
private class NonReusableEmptyProgressIndicator : EmptyProgressIndicator() {
override fun start() {
checkCanceled()
super.start()
}
}
interface ProcessStateListener : EventListener {
fun processStarted() {}
fun processFinished() {}
}
} | apache-2.0 | 1a14c35e6cd248dcc69eea5a1f2adc68 | 34.78125 | 140 | 0.777195 | 5.14382 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/data/server/model/AmpacheArtist.kt | 1 | 727 | package be.florien.anyflow.data.server.model
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
/**
* Server-side data structures that relates to artists
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
class AmpacheArtist {
var id: Long = 0
var name: String = ""
var albums: String = ""
var art: String = ""
var songs: String = ""
var tag: List<AmpacheTagName> = mutableListOf()
var preciserating: Int = 0
var rating: Double = 0.0
}
class AmpacheAlbumArtist {
var id: Long = 0
var name: String = ""
}
class AmpacheArtistName {
var id: Long = 0
var name: String = ""
}
| gpl-3.0 | 52604102008d891d42036b855dd8cc00 | 22.451613 | 60 | 0.691884 | 3.867021 | false | false | false | false |
ivan-osipov/Clabo | src/main/kotlin/com/github/ivan_osipov/clabo/api/model/Video.kt | 1 | 621 | package com.github.ivan_osipov.clabo.api.model
import com.google.gson.annotations.SerializedName
class Video : AbstractFileDescriptor() {
@SerializedName("width")
private var _width: Int? = null
val width: Int
get() = _width!!
@SerializedName("height")
private var _height: Int? = null
val height: Int
get() = _height!!
@SerializedName("duration")
private var _duration: Int? = null
val duration: Int
get() = _duration!!
@SerializedName("thumb")
var thumb: PhotoSize? = null
@SerializedName("mime_type")
var mimeType: String? = null
} | apache-2.0 | c3d49dcae93589e75c4bd022c6364602 | 19.064516 | 49 | 0.634461 | 4.058824 | false | false | false | false |
androidx/androidx | compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/internal/LiveLiteral.kt | 3 | 3221 | /*
* 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.runtime.internal
import androidx.compose.runtime.ComposeCompilerApi
import androidx.compose.runtime.InternalComposeApi
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
/**
* This annotation is applied to functions on the LiveLiteral classes created by the Compose
* Compiler. It is intended to be used to provide information useful to tooling.
*
* @param key The unique identifier for the literal.
* @param offset The startOffset of the literal in the source file at the time of compilation.
*/
@ComposeCompilerApi
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class LiveLiteralInfo(
val key: String,
val offset: Int
)
/**
* This annotation is applied to LiveLiteral classes by the Compose Compiler. It is intended to
* be used to provide information useful to tooling.
*
* @param file The file path of the file the associate LiveLiterals class was produced for
*/
@ComposeCompilerApi
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class LiveLiteralFileInfo(
val file: String
)
private val liveLiteralCache = HashMap<String, MutableState<Any?>>()
@InternalComposeApi
@ComposeCompilerApi
var isLiveLiteralsEnabled: Boolean = false
private set
/**
* When called, all live literals will start to use their values backed by [MutableState].
*
* Caution: This API is intended to be used by tooling only. Use at your own risk.
*/
@InternalComposeApi
fun enableLiveLiterals() {
isLiveLiteralsEnabled = true
}
/**
* Constructs a [State] object identified by the provided global [key] and initialized to the
* provided [value]. This value may then be updated from tooling with the
* [updateLiveLiteralValue] API. Only a single [State] object will be created for any given [key].
*
* Caution: This API is intended to be used by tooling only. Use at your own risk.
*/
@InternalComposeApi
@ComposeCompilerApi
fun <T> liveLiteral(key: String, value: T): State<T> {
@Suppress("UNCHECKED_CAST")
return liveLiteralCache.getOrPut(key) {
mutableStateOf<Any?>(value)
} as State<T>
}
/**
* Updates the value of a [State] object that was created by [liveLiteral] with the same key.
*/
@InternalComposeApi
fun updateLiveLiteralValue(key: String, value: Any?) {
var needToUpdate = true
val stateObj = liveLiteralCache.getOrPut(key) {
needToUpdate = false
mutableStateOf<Any?>(value)
}
if (needToUpdate) {
stateObj.value = value
}
} | apache-2.0 | cc4d8e96c25d17e7266d8b72c4e221e0 | 31.545455 | 98 | 0.750078 | 4.232589 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/intentions/InlineDebugIntention.kt | 1 | 3811 | package org.elm.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.*
import org.elm.lang.core.psi.elements.*
import org.elm.utils.getIndent
/**
* This intention is built to easily allow users to add log statements on values.
* It is currently restricted from working fully with pipelines and function composition.
* For pipelined operations, you can only log the complete statement (so logging the final output, in other words),
* and function composition is ignored entirely
* (since a composition produces a function, which can't be sensibly logged).
*
* Ideally, we would support inserting Debug.log statements inside a pipeline/composition,
* to allow users to print the data getting piped along.
*/
class InlineDebugIntention : ElmAtCaretIntentionActionBase<InlineDebugIntention.Context>() {
data class Context(val valueToDebug: ElmPsiElement)
override fun getText() = "Log this value to console"
override fun getFamilyName() = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
element.ancestors.forEach {
when (it) {
is ElmValueExpr -> {
val functionCallParent = it.parentOfType<ElmFunctionCallExpr>()
val binOpParent = it.parentOfType<ElmBinOpExpr>()
return when {
functionCallParent != null && functionCallParent.target == it -> {
Context(functionCallParent)
}
binOpParent != null -> {
if (isFunComposition(binOpParent)) {
null
} else {
Context(binOpParent)
}
}
else -> {
Context(it)
}
}
}
is ElmCaseOfExpr -> {
return Context(it)
}
is ElmAtomTag -> {
return Context(it)
}
is ElmBinOpExpr -> {
return if (isFunComposition(it)) {
null
} else {
Context(it)
}
}
}
}
return null
}
private fun isFunComposition(opExpr: ElmBinOpExpr): Boolean =
opExpr.parts
.filterIsInstance<ElmOperator>()
.map { it.referenceName }
.any { it == "<<" || it == ">>" }
override fun invoke(project: Project, editor: Editor, context: Context) {
val factory = ElmPsiFactory(project)
val valueExpr = context.valueToDebug
val itemsText = valueExpr.text
val textLines = itemsText.lines()
val debuggedText =
if (textLines.size > 1) {
val baseIndent = editor.getIndent(valueExpr.startOffset)
val indentation = " "
val indentedLines = textLines.mapIndexed { index, line -> baseIndent + indentation.repeat(index) + line }
"""Debug.log
$baseIndent "${textLines.first().escapeDoubleQuotes()} ..."
$baseIndent (
$baseIndent ${indentedLines.joinToString("\n")}
$baseIndent )"""
} else {
"""Debug.log "${itemsText.escapeDoubleQuotes()}" ($itemsText)"""
}
valueExpr.replace(factory.createParens(debuggedText))
}
}
private fun String.escapeDoubleQuotes(): String = replace("\"", "\\\"")
| mit | fb51e5a1de74f57d424b94d992c07cae | 38.28866 | 125 | 0.540016 | 5.185034 | false | false | false | false |
mvosske/comlink | app/src/main/java/org/tnsfit/dragon/comlink/matrix/MessagePacket.kt | 1 | 1494 | package org.tnsfit.dragon.comlink.matrix
import org.tnsfit.dragon.comlink.AroCoordinates
/**
* Created by dragon on 08.10.16.
*
*/
class MessagePacket (val type:String, val message:String, val source:Int = NONE) {
companion object {
// Source Types
val NONE = 0
val MATRIX = 1
val COMLINK = 2
}
val aroCoordinates: AroCoordinates by lazy {
AroCoordinates(message)
}
fun pack(): ByteArray {
var result = type
result += message.replace(';',',') + ";" // semicolon is the devider/end of message
return result.toByteArray(Charsets.UTF_8)
}
fun checkOK(): Boolean {
return when (type) {
MatrixConnection.SEND,
MatrixConnection.TEXT_MESSAGE -> { if (message.equals("")) false else true}
MatrixConnection.MARKER,
MatrixConnection.PING -> {if (message.contains(",")) true else false}
MatrixConnection.HELLO,
MatrixConnection.ANSWER -> { true }
else -> false
}
}
}
fun MessagePacketFactory(input:ByteArray, source:Int = MessagePacket.NONE): MessagePacket {
val stringed = input.toString(Charsets.UTF_8)
val type:String = stringed.subSequence(0,10).toString()
val messageEnding = stringed.indexOf(';')
if (messageEnding > 10) {
return MessagePacket(type, stringed.substring(10,messageEnding), source)
} else {
return MessagePacket("", "", source)
}
}
| gpl-3.0 | b32d1429f843eadffca7e1517cd3e42f | 25.210526 | 91 | 0.615797 | 4.070845 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/forge/inspections/sideonly/LocalVariableDeclarationSideOnlyInspection.kt | 1 | 5429 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.inspections.sideonly
import com.demonwav.mcdev.util.findContainingClass
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiLocalVariable
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import org.jetbrains.annotations.Nls
class LocalVariableDeclarationSideOnlyInspection : BaseInspection() {
@Nls
override fun getDisplayName() = "Invalid usage of local variable declaration annotated with @SideOnly"
override fun buildErrorString(vararg infos: Any): String {
val error = infos[0] as Error
return error.getErrorString(*SideOnlyUtil.getSubArray(infos))
}
override fun getStaticDescription() =
"A variable whose class declaration is annotated with @SideOnly for one side cannot be declared in a class" +
" or method that does not match the same side."
override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
val annotation = infos[3] as PsiAnnotation
return if (annotation.isWritable) {
RemoveAnnotationInspectionGadgetsFix(
annotation,
"Remove @SideOnly annotation from variable class declaration"
)
} else {
null
}
}
override fun buildVisitor(): BaseInspectionVisitor {
return object : BaseInspectionVisitor() {
override fun visitLocalVariable(variable: PsiLocalVariable) {
val psiClass = variable.findContainingClass() ?: return
if (!SideOnlyUtil.beginningCheck(variable)) {
return
}
val type = variable.type as? PsiClassType ?: return
val variableClass = type.resolve() ?: return
val (variableAnnotation, variableSide) = SideOnlyUtil.getSideForClass(variableClass)
if (variableAnnotation == null || variableSide === Side.NONE || variableSide === Side.INVALID) {
return
}
val (containingClassAnnotation, containingClassSide) = SideOnlyUtil.getSideForClass(psiClass)
val (methodAnnotation, methodSide) = SideOnlyUtil.checkElementInMethod(variable)
var classAnnotated = false
if (containingClassAnnotation != null &&
containingClassSide !== Side.NONE && containingClassSide !== Side.INVALID
) {
if (variableSide !== containingClassSide) {
registerVariableError(
variable,
Error.VAR_CROSS_ANNOTATED_CLASS,
variableAnnotation.renderSide(variableSide),
containingClassAnnotation.renderSide(containingClassSide),
variableClass.getAnnotation(variableAnnotation.annotationName)
)
}
classAnnotated = true
}
if (methodAnnotation == null || methodSide === Side.INVALID) {
return
}
if (variableSide !== methodSide) {
if (methodSide === Side.NONE) {
if (!classAnnotated) {
registerVariableError(
variable,
Error.VAR_UNANNOTATED_METHOD,
variableAnnotation.renderSide(variableSide),
methodAnnotation.renderSide(methodSide),
variableClass.getAnnotation(variableAnnotation.annotationName)
)
}
} else {
registerVariableError(
variable,
Error.VAR_CROSS_ANNOTATED_METHOD,
variableAnnotation.renderSide(variableSide),
methodAnnotation.renderSide(methodSide),
variableClass.getAnnotation(variableAnnotation.annotationName)
)
}
}
}
}
}
enum class Error {
VAR_CROSS_ANNOTATED_CLASS {
override fun getErrorString(vararg infos: Any): String {
return "A local variable whose class is annotated with ${infos[0]} " +
"cannot be used in a class annotated with ${infos[1]}"
}
},
VAR_CROSS_ANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "A local variable whose class is annotated with ${infos[0]} " +
"cannot be used in a method annotated with ${infos[1]}"
}
},
VAR_UNANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "A local variable whose class is annotated with ${infos[0]} " +
"cannot be used in an un-annotated method."
}
};
abstract fun getErrorString(vararg infos: Any): String
}
}
| mit | 021cf4fca122ac6e53c3179288ef07bd | 38.34058 | 117 | 0.557745 | 5.933333 | false | false | false | false |
C6H2Cl2/SolidXp | src/main/java/c6h2cl2/solidxp/event/XpBoostEventHandler.kt | 1 | 2139 | @file:Suppress("UNUSED")
package c6h2cl2.solidxp.event
import c6h2cl2.solidxp.SolidXpRegistry
import net.minecraft.block.BlockCrops
import net.minecraft.enchantment.EnchantmentHelper
import net.minecraft.enchantment.EnumEnchantmentType.DIGGER
import net.minecraft.enchantment.EnumEnchantmentType.WEAPON
import net.minecraft.item.ItemHoe
import net.minecraft.item.ItemStack
import net.minecraftforge.event.entity.living.LivingExperienceDropEvent
import net.minecraftforge.event.world.BlockEvent.BreakEvent
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
/**
* @author C6H2Cl2
*/
class XpBoostEventHandler {
@SubscribeEvent
fun onLivingDropExperience(event: LivingExperienceDropEvent) {
val player = event.attackingPlayer ?: return
val itemStack = player.heldItemMainhand
if (itemStack == ItemStack.EMPTY || itemStack.enchantmentTagList == null || itemStack.enchantmentTagList?.tagCount() != 0) return
val xpBoostLevel = EnchantmentHelper.getEnchantmentLevel(SolidXpRegistry.xpBoost[WEAPON], itemStack)
if (xpBoostLevel == 0) return
val rand = player.world.rand
val boost = 1.0f + (rand.nextFloat() * xpBoostLevel * rand.nextFloat() * xpBoostLevel)
event.droppedExperience = Math.round(event.originalExperience * boost)
}
@SubscribeEvent
fun onBlockBreak(event: BreakEvent) {
var xp = event.expToDrop
val player = event.player ?: return
val itemStack = player.heldItemMainhand
if (itemStack == ItemStack.EMPTY) return
val xpBoostLevel = EnchantmentHelper.getEnchantmentLevel(SolidXpRegistry.xpBoost[DIGGER], itemStack)
val rand = event.world.rand
val boost = 1.0f + (rand.nextFloat() * xpBoostLevel * rand.nextFloat() * xpBoostLevel)
xp = Math.round(xp * boost)
if (itemStack.item is ItemHoe || itemStack.item.getToolClasses(itemStack).contains("hoe")) {
val block = event.state.block
if (block is BlockCrops && block.isMaxAge(event.state)) {
xp += xpBoostLevel
}
}
event.expToDrop = xp
}
} | mpl-2.0 | 9ed739f652807c69d495da4a5e20b9a6 | 41.8 | 137 | 0.717158 | 4.105566 | false | false | false | false |
pbauerochse/youtrack-worklog-viewer | application/src/main/java/de/pbauerochse/worklogviewer/datasource/api/domain/adapters/WorkItemAdapter.kt | 1 | 920 | package de.pbauerochse.worklogviewer.datasource.api.domain.adapters
import de.pbauerochse.worklogviewer.datasource.api.domain.YouTrackIssueWorkItem
import de.pbauerochse.worklogviewer.timereport.User
import de.pbauerochse.worklogviewer.timereport.WorkItem
import de.pbauerochse.worklogviewer.timereport.WorkItemType
import java.time.ZonedDateTime
class WorkItemAdapter(
youtrackWorkItem: YouTrackIssueWorkItem,
override val belongsToCurrentUser: Boolean
): WorkItem {
override val id: String = youtrackWorkItem.id
override val owner: User = UserAdapter(youtrackWorkItem.author!!)
override val workDate: ZonedDateTime = youtrackWorkItem.date
override val durationInMinutes: Long = youtrackWorkItem.duration.minutes
override val description: String = youtrackWorkItem.text ?: ""
override val workType: WorkItemType? = youtrackWorkItem.type?.let { WorkItemType(it.id, it.name ?: it.id) }
} | mit | cb7d40b65332c99ce42c92e9823f4067 | 47.473684 | 111 | 0.809783 | 4.36019 | false | false | false | false |
yichiuan/Moedict-Android | moedict-android/app/src/main/java/com/yichiuan/moedict/common/VoicePlayer.kt | 1 | 3318 | package com.yichiuan.moedict.common
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.OnLifecycleEvent
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
import android.media.MediaPlayer
import android.os.Build
import timber.log.Timber
import java.io.IOException
class VoicePlayer(context: Context, lifecycle: Lifecycle) : AudioManager.OnAudioFocusChangeListener {
internal val mediaPlayer = MediaPlayer()
internal val audioManager: AudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
private val audioAttributes: AudioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
private var onLoadedListener: OnLoadedListener? = null
val isPlaying: Boolean
get() = mediaPlayer.isPlaying
init {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mediaPlayer.setAudioAttributes(audioAttributes)
} else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
}
mediaPlayer.setOnCompletionListener { mp -> audioManager.abandonAudioFocus(this) }
lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
internal fun onStop() {
stopVoice()
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
internal fun onRelease() {
mediaPlayer.release()
}
})
}
fun playVoice(url: String) {
try {
mediaPlayer.reset()
mediaPlayer.setDataSource(url)
mediaPlayer.setOnPreparedListener { mp ->
val result = audioManager.requestAudioFocus(this,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mediaPlayer.start()
if (onLoadedListener != null) {
onLoadedListener!!.onLoaded()
}
}
}
mediaPlayer.prepareAsync()
} catch (e: IOException) {
Timber.e(e)
}
}
fun stopVoice() {
if (mediaPlayer.isPlaying) {
mediaPlayer.stop()
audioManager.abandonAudioFocus(this)
}
}
override fun onAudioFocusChange(focusChange: Int) {
if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {
if (mediaPlayer.isPlaying) {
mediaPlayer.pause()
}
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
mediaPlayer.start()
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
audioManager.abandonAudioFocus(this)
if (mediaPlayer.isPlaying) {
mediaPlayer.stop()
}
}
}
fun setOnLoadedListener(onLoadedListener: OnLoadedListener) {
this.onLoadedListener = onLoadedListener
}
interface OnLoadedListener {
fun onLoaded()
}
}
| apache-2.0 | f61f919961dfc71db02785768cc85e0a | 29.440367 | 109 | 0.625075 | 5.291866 | false | false | false | false |
elect86/jAssimp | src/main/kotlin/assimp/format/X/ConvertToLHProcess.kt | 2 | 5550 | package assimp.format.X
import assimp.*
object MakeLeftHandedProcess {
fun IsActive(pFlags: Int): Boolean {
return 0 != (pFlags.and(AiPostProcessStep.MakeLeftHanded.i))
}
fun Execute(pScene: AiScene) {
// Check for an existent root node to proceed
debug("MakeLeftHandedProcess: MakeLeftHandedProcess begin")
// recursively convert all the nodes
ProcessNode(pScene.rootNode, AiMatrix4x4())
// process the meshes accordingly
for (a in 0 until pScene.numMeshes)
ProcessMesh(pScene.meshes[a])
// process the materials accordingly
for (a in 0 until pScene.numMaterials)
ProcessMaterial(pScene.materials[a])
// transform all animation channels as well
for (a in 0 until pScene.numAnimations) {
var anim = pScene.animations[a]
for (b in 0 until anim.numChannels) {
var nodeAnim = anim.channels[b]
if(nodeAnim!=null) ProcessAnimation(nodeAnim)
}
}
debug("MakeLeftHandedProcess: MakeLeftHandedProcess finished")
}
fun ProcessNode(pNode: AiNode, pParentGlobalRotation: AiMatrix4x4) {
// mirror all base vectors at the local Z axis
pNode.transformation.a2 = -pNode.transformation.a2
pNode.transformation.b2 = -pNode.transformation.b2
pNode.transformation.c2 = -pNode.transformation.c2
pNode.transformation.d2 = -pNode.transformation.d2
// now invert the Z axis again to keep the matrix determinant positive.
// The local meshes will be inverted accordingly so that the result should look just fine again.
pNode.transformation.c0 = -pNode.transformation.c0
pNode.transformation.c1 = -pNode.transformation.c1
pNode.transformation.c2 = -pNode.transformation.c2
pNode.transformation.c3 = -pNode.transformation.c3 // useless, but anyways...
// continue for all children
for (a in 0 until pNode.numChildren) {
ProcessNode(pNode.children[a], pParentGlobalRotation * pNode.transformation)
}
}
fun ProcessMesh(pMesh: AiMesh) {
// mirror positions, normals and stuff along the Z axis
for (a in 0 until pMesh.numVertices) {
pMesh.vertices[a].z *= -1.0f
if (pMesh.hasNormals)
pMesh.normals[a].z *= -1.0f
if (pMesh.hasTangentsAndBitangents) {
pMesh.tangents[a].z *= -1.0f
pMesh.bitangents[a].z *= -1.0f
}
}
// mirror offset matrices of all bones
for (a in 0 until pMesh.numBones) {
val bone = pMesh.bones[a]
bone.offsetMatrix.c0 = -bone.offsetMatrix.c0
bone.offsetMatrix.c1 = -bone.offsetMatrix.c1
bone.offsetMatrix.c2 = -bone.offsetMatrix.c2
bone.offsetMatrix.a2 = -bone.offsetMatrix.a2
bone.offsetMatrix.b2 = -bone.offsetMatrix.b2
bone.offsetMatrix.d2 = -bone.offsetMatrix.d2
}
// mirror bitangents as well as they're derived from the texture coords
if (pMesh.hasTangentsAndBitangents) {
for (a in 0 until pMesh.numVertices)
pMesh.bitangents[a] = pMesh.bitangents[a] * -1.0f
}
}
fun ProcessMaterial(_mat: AiMaterial) {
var mat = _mat
for (a in 0 until mat.textures.size) {
var prop = mat.textures[a]
// Mapping axis for UV mappings?
if (prop.mapAxis != null) {
//assert( prop.mDataLength >= sizeof(aiVector3D)); /* something is wrong with the validation if we end up here */
var pff = prop.mapAxis!!
pff.z *= -1.0F
}
}
}
fun ProcessAnimation(pAnim : AiNodeAnim) {
// position keys
for(a in 0 until pAnim.numPositionKeys)
pAnim.positionKeys[a].value.z *= -1.0f
// rotation keys
for(a in 0 until pAnim.numRotationKeys)
{
/* That's the safe version, but the float errors add up. So we try the short version instead
aiMatrix3x3 rotmat = pAnim.mRotationKeys[a].mValue.GetMatrix();
rotmat.d0 = -rotmat.d0; rotmat.d1 = -rotmat.d1;
rotmat.b3 = -rotmat.b3; rotmat.c2 = -rotmat.c2;
aiQuaternion rotquat( rotmat);
pAnim.mRotationKeys[a].mValue = rotquat;
*/
pAnim.rotationKeys[a].value.x *= -1.0f
pAnim.rotationKeys[a].value.y *= -1.0f
}
}
}
object FlipWindingOrderProcess {
fun IsActive(pFlags : Int) : Boolean {
return 0 != (pFlags.and(AiPostProcessStep.FlipWindingOrder.i))
}
fun Execute(pScene : AiScene) {
debug("FlipWindingOrderProcess: FlipWindingOrderProcess begin")
for (i in 0 until pScene.numMeshes)
ProcessMesh(pScene.meshes[i])
debug("FlipWindingOrderProcess: FlipWindingOrderProcess finished")
}
fun ProcessMesh(pMesh : AiMesh) {
// invert the order of all faces in this mesh
for(a in 0 until pMesh.numFaces)
{
var face = pMesh.faces[a]
for(b in 0 until (face.size/2)) {
var _b = face[b]
var _mb = face[face.size - 1 - b]
face[b] = _mb
face[face.size - 1 - b] = _b
}
}
}
} | mit | 52e076748a217429c8bda3002615fb5e | 35.513514 | 129 | 0.578198 | 3.9057 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/about/AboutFragment.kt | 1 | 5809 | package de.westnordost.streetcomplete.about
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri
import androidx.core.widget.TextViewCompat
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.recyclerview.widget.RecyclerView
import de.westnordost.streetcomplete.BuildConfig
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.ktx.tryStartActivity
import de.westnordost.streetcomplete.util.sendEmail
import de.westnordost.streetcomplete.view.ListAdapter
import kotlinx.android.synthetic.main.cell_labeled_icon_select_right.view.*
import java.util.*
/** Shows the about screen */
class AboutFragment : PreferenceFragmentCompat() {
interface Listener {
fun onClickedChangelog()
fun onClickedCredits()
fun onClickedPrivacyStatement()
}
private val listener: Listener? get() = parentFragment as? Listener ?: activity as? Listener
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.about)
findPreference<Preference>("version")?.summary = getString(R.string.about_summary_current_version, "v" + BuildConfig.VERSION_NAME)
findPreference<Preference>("version")?.setOnPreferenceClickListener {
listener?.onClickedChangelog()
true
}
findPreference<Preference>("license")?.setOnPreferenceClickListener {
openUrl("https://www.gnu.org/licenses/gpl-3.0.html")
}
findPreference<Preference>("authors")?.setOnPreferenceClickListener {
listener?.onClickedCredits()
true
}
findPreference<Preference>("privacy")?.setOnPreferenceClickListener {
listener?.onClickedPrivacyStatement()
true
}
findPreference<Preference>("repository")?.setOnPreferenceClickListener {
openUrl("https://github.com/westnordost/StreetComplete/")
}
findPreference<Preference>("translate")?.summary = resources.getString(
R.string.about_description_translate,
Locale.getDefault().displayLanguage,
resources.getInteger(R.integer.translation_completeness)
)
findPreference<Preference>("translate")?.setOnPreferenceClickListener {
openUrl("https://poeditor.com/join/project/IE4GC127Ki")
}
findPreference<Preference>("report_error")?.setOnPreferenceClickListener {
openUrl("https://github.com/westnordost/StreetComplete/issues/")
}
findPreference<Preference>("email_feedback")?.setOnPreferenceClickListener {
sendFeedbackEmail()
}
findPreference<Preference>("rate")?.isVisible = isInstalledViaGooglePlay()
findPreference<Preference>("rate")?.setOnPreferenceClickListener {
openGooglePlayStorePage()
}
findPreference<Preference>("donate")?.setOnPreferenceClickListener {
showDonateDialog()
true
}
}
override fun onStart() {
super.onStart()
activity?.setTitle(R.string.action_about2)
}
private fun isInstalledViaGooglePlay(): Boolean {
val appCtx = context?.applicationContext ?: return false
val installerPackageName = appCtx.packageManager.getInstallerPackageName(appCtx.packageName)
return installerPackageName == "com.android.vending"
}
private fun openUrl(url: String): Boolean {
val intent = Intent(Intent.ACTION_VIEW, url.toUri())
tryStartActivity(intent)
return true
}
private fun sendFeedbackEmail(): Boolean {
sendEmail(requireActivity(),"[email protected]", "Feedback")
return true
}
private fun openGooglePlayStorePage(): Boolean {
val appPackageName = context?.applicationContext?.packageName ?: return false
return openUrl("market://details?id=$appPackageName")
}
private fun showDonateDialog() {
val ctx = context ?: return
val view = LayoutInflater.from(ctx).inflate(R.layout.dialog_donate, null)
val listView = view.findViewById<RecyclerView>(R.id.donateList)
listView.adapter = DonationPlatformAdapter(DonationPlatform.values().asList())
AlertDialog.Builder(ctx)
.setTitle(R.string.about_title_donate)
.setView(view)
.show()
}
private inner class DonationPlatformAdapter(list: List<DonationPlatform>): ListAdapter<DonationPlatform>(list) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.cell_labeled_icon_select_right, parent, false))
inner class ViewHolder(itemView: View) : ListAdapter.ViewHolder<DonationPlatform>(itemView) {
override fun onBind(with: DonationPlatform) {
itemView.imageView.setImageResource(with.iconId)
itemView.textView.text = with.title
itemView.setOnClickListener { openUrl(with.url) }
TextViewCompat.setTextAppearance(itemView.textView, R.style.TextAppearance_Title)
}
}
}
}
private enum class DonationPlatform(val title: String, @DrawableRes val iconId: Int, val url: String) {
GITHUB("GitHub Sponsors", R.drawable.ic_github, "https://github.com/sponsors/westnordost"),
LIBERAPAY("Liberapay", R.drawable.ic_liberapay, "https://liberapay.com/westnordost"),
PATREON("Patreon", R.drawable.ic_patreon, "https://patreon.com/westnordost")
}
| gpl-3.0 | fa2977b760b65a6f7129c8dcf034cf21 | 38.517007 | 138 | 0.6953 | 5.113556 | false | false | false | false |
robfletcher/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/RunTaskHandlerTest.kt | 2 | 69441 | /*
* 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.spectator.api.NoopRegistry
import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService
import com.netflix.spinnaker.orca.DefaultStageResolver
import com.netflix.spinnaker.orca.TaskExecutionInterceptor
import com.netflix.spinnaker.orca.TaskResolver
import com.netflix.spinnaker.orca.api.pipeline.Task
import com.netflix.spinnaker.orca.api.pipeline.TaskResult
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.PAUSED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.STOPPED
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.pipeline.models.PipelineExecution.PausedDetails
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.api.test.task
import com.netflix.spinnaker.orca.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow
import com.netflix.spinnaker.orca.pipeline.model.DefaultTrigger
import com.netflix.spinnaker.orca.pipeline.model.StageExecutionImpl.STAGE_TIMEOUT_OVERRIDE_KEY
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.tasks.WaitTask
import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor
import com.netflix.spinnaker.orca.pipeline.util.StageNavigator
import com.netflix.spinnaker.orca.q.CompleteTask
import com.netflix.spinnaker.orca.q.DummyCloudProviderAwareTask
import com.netflix.spinnaker.orca.q.DummyTask
import com.netflix.spinnaker.orca.q.DummyTimeoutOverrideTask
import com.netflix.spinnaker.orca.q.InvalidTask
import com.netflix.spinnaker.orca.q.InvalidTaskType
import com.netflix.spinnaker.orca.q.PauseTask
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.orca.q.StageDefinitionBuildersProvider
import com.netflix.spinnaker.orca.q.TasksProvider
import com.netflix.spinnaker.orca.q.singleTaskStage
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.spek.and
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.anyOrNull
import com.nhaarman.mockito_kotlin.check
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.doThrow
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.isA
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions
import com.nhaarman.mockito_kotlin.whenever
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.time.ZoneId
import java.time.temporal.ChronoUnit
import kotlin.collections.set
import kotlin.reflect.jvm.jvmName
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import org.threeten.extra.Minutes
object RunTaskHandlerTest : SubjectSpek<RunTaskHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val stageNavigator: StageNavigator = mock()
val task: DummyTask = mock {
on { extensionClass } doReturn DummyTask::class.java
on { aliases() } doReturn emptyList<String>()
}
val cloudProviderAwareTask: DummyCloudProviderAwareTask = mock {
on { extensionClass } doReturn DummyCloudProviderAwareTask::class.java
}
val timeoutOverrideTask: DummyTimeoutOverrideTask = mock {
on { extensionClass } doReturn DummyTimeoutOverrideTask::class.java
on { aliases() } doReturn emptyList<String>()
}
val tasks = mutableListOf(task, cloudProviderAwareTask, timeoutOverrideTask)
val exceptionHandler: ExceptionHandler = mock()
// Stages store times as ms-since-epoch, and we do a lot of tests to make sure things run at the
// appropriate time, so we need to make sure
// clock.instant() == Instant.ofEpochMilli(clock.instant())
val clock = Clock.fixed(Instant.now().truncatedTo(ChronoUnit.MILLIS), ZoneId.systemDefault())
val contextParameterProcessor = ContextParameterProcessor()
val dynamicConfigService: DynamicConfigService = mock()
val taskExecutionInterceptors: List<TaskExecutionInterceptor> = listOf(mock())
val stageResolver = DefaultStageResolver(StageDefinitionBuildersProvider(emptyList()))
subject(GROUP) {
whenever(dynamicConfigService.getConfig(eq(Int::class.java), eq("tasks.warningInvocationTimeMs"), any())) doReturn 0
RunTaskHandler(
queue,
repository,
stageNavigator,
DefaultStageDefinitionBuilderFactory(stageResolver),
contextParameterProcessor,
TaskResolver(TasksProvider(mutableListOf(task, timeoutOverrideTask, cloudProviderAwareTask) as Collection<Task>)),
clock,
listOf(exceptionHandler),
taskExecutionInterceptors,
NoopRegistry(),
dynamicConfigService
)
}
fun resetMocks() = reset(queue, repository, task, timeoutOverrideTask, cloudProviderAwareTask, exceptionHandler)
describe("running a task") {
describe("that completes successfully") {
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
and("has no context updates outputs") {
val taskResult = TaskResult.SUCCEEDED
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("executes the task") {
verify(task).execute(pipeline.stages.first())
}
it("completes the task") {
verify(queue).push(
check<CompleteTask> {
assertThat(it.status).isEqualTo(SUCCEEDED)
}
)
}
it("does not update the stage or global context") {
verify(repository, never()).storeStage(any())
}
}
and("has context updates") {
val stageOutputs = mapOf("foo" to "covfefe")
val taskResult = TaskResult.builder(SUCCEEDED).context(stageOutputs).build()
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage context") {
verify(repository).storeStage(
check {
assertThat(stageOutputs).isEqualTo(it.context)
}
)
}
}
and("has outputs") {
val outputs = mapOf("foo" to "covfefe")
val taskResult = TaskResult.builder(SUCCEEDED).outputs(outputs).build()
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage outputs") {
verify(repository).storeStage(
check {
assertThat(it.outputs).isEqualTo(outputs)
}
)
}
}
and("outputs a stageTimeoutMs value") {
val outputs = mapOf(
"foo" to "covfefe",
"stageTimeoutMs" to Long.MAX_VALUE
)
val taskResult = TaskResult.builder(SUCCEEDED).outputs(outputs).build()
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("does not write stageTimeoutMs to outputs") {
verify(repository).storeStage(
check {
assertThat(it.outputs)
.containsKey("foo")
.doesNotContainKey("stageTimeoutMs")
}
)
}
}
}
describe("that completes successfully prefering specified TaskExecution implementingClass") {
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
startTime = clock.instant().toEpochMilli()
implementingClass = task.javaClass.canonicalName
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", WaitTask::class.java)
and("has no context updates outputs") {
val taskResult = TaskResult.SUCCEEDED
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("executes the task") {
verify(task).execute(pipeline.stages.first())
}
it("completes the task") {
verify(queue).push(
check<CompleteTask> {
assertThat(it.status).isEqualTo(SUCCEEDED)
}
)
}
it("does not update the stage or global context") {
verify(repository, never()).storeStage(any())
}
}
and("has context updates") {
val stageOutputs = mapOf("foo" to "covfefe")
val taskResult = TaskResult.builder(SUCCEEDED).context(stageOutputs).build()
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage context") {
verify(repository).storeStage(
check {
assertThat(stageOutputs).isEqualTo(it.context)
}
)
}
}
and("has outputs") {
val outputs = mapOf("foo" to "covfefe")
val taskResult = TaskResult.builder(SUCCEEDED).outputs(outputs).build()
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("updates the stage outputs") {
verify(repository).storeStage(
check {
assertThat(it.outputs).isEqualTo(outputs)
}
)
}
}
and("outputs a stageTimeoutMs value") {
val outputs = mapOf(
"foo" to "covfefe",
"stageTimeoutMs" to Long.MAX_VALUE
)
val taskResult = TaskResult.builder(SUCCEEDED).outputs(outputs).build()
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("does not write stageTimeoutMs to outputs") {
verify(repository).storeStage(
check {
assertThat(it.outputs)
.containsKey("foo")
.doesNotContainKey("stageTimeoutMs")
}
)
}
}
}
describe("that is not yet complete") {
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
val taskResult = TaskResult.RUNNING
val taskBackoffMs = 30_000L
val maxBackOffLimit = 120_000L
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.maxTaskBackoff()) doReturn maxBackOffLimit }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(task.getDynamicBackoffPeriod(any(), any())) doReturn taskBackoffMs
whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.global.backOffPeriod"), any())) doReturn 0L
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("re-queues the command") {
verify(queue).push(message, Duration.ofMillis(taskBackoffMs))
}
}
setOf(TERMINAL, CANCELED).forEach { taskStatus ->
describe("that fails with $taskStatus") {
val pipeline = pipeline {
stage {
refId = "1"
type = "whatever"
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
val taskResult = TaskResult.ofStatus(taskStatus)
and("no overrides are in place") {
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task $taskStatus") {
verify(queue).push(
check<CompleteTask> {
assertThat(it.status).isEqualTo(taskStatus)
}
)
}
}
and("the task should not fail the whole pipeline, only the branch") {
beforeGroup {
pipeline.stageByRef("1").apply {
context["failPipeline"] = false
context["continuePipeline"] = false
}
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
afterGroup { pipeline.stages.first().context.clear() }
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task STOPPED") {
verify(queue).push(
check<CompleteTask> {
assertThat(it.status).isEqualTo(STOPPED)
}
)
}
}
and("the task should allow the pipeline to proceed") {
beforeGroup {
pipeline.stageByRef("1").apply {
context["failPipeline"] = false
context["continuePipeline"] = true
}
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
afterGroup { pipeline.stages.first().context.clear() }
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task FAILED_CONTINUE") {
verify(queue).push(
check<CompleteTask> {
assertThat(it.status).isEqualTo(FAILED_CONTINUE)
}
)
}
}
}
}
describe("that throws an exception") {
val pipeline = pipeline {
stage {
refId = "1"
type = "whatever"
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
val taskResult = TaskResult.ofStatus(TERMINAL)
and("it is not recoverable") {
val exceptionDetails = ExceptionHandler.Response(
RuntimeException::class.qualifiedName,
"o noes",
ExceptionHandler.responseDetails("o noes"),
false
)
and("the task should fail the pipeline") {
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doThrow RuntimeException("o noes") }
whenever(task.execute(any())) doThrow RuntimeException("o noes")
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(exceptionHandler.handles(any())) doReturn true
whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task as terminal") {
verify(queue).push(
check<CompleteTask> {
assertThat(it.status).isEqualTo(TERMINAL)
}
)
}
it("attaches the exception to the stage context") {
verify(repository).storeStage(
check {
assertThat(it.context["exception"]).isEqualTo(exceptionDetails)
}
)
}
}
and("the task should not fail the whole pipeline, only the branch") {
beforeGroup {
pipeline.stageByRef("1").apply {
context["failPipeline"] = false
context["continuePipeline"] = false
}
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(task.execute(any())) doThrow RuntimeException("o noes")
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(exceptionHandler.handles(any())) doReturn true
whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails
}
afterGroup(::resetMocks)
afterGroup { pipeline.stages.first().context.clear() }
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task STOPPED") {
verify(queue).push(
check<CompleteTask> {
assertThat(it.status).isEqualTo(STOPPED)
}
)
}
}
and("the task should allow the pipeline to proceed") {
beforeGroup {
pipeline.stageByRef("1").apply {
context["failPipeline"] = false
context["continuePipeline"] = true
}
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(task.execute(any())) doThrow RuntimeException("o noes")
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(exceptionHandler.handles(any())) doReturn true
whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails
}
afterGroup(::resetMocks)
afterGroup { pipeline.stages.first().context.clear() }
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task FAILED_CONTINUE") {
verify(queue).push(
check<CompleteTask> {
assertThat(it.status).isEqualTo(FAILED_CONTINUE)
}
)
}
}
}
and("it is recoverable") {
val taskBackoffMs = 30_000L
val exceptionDetails = ExceptionHandler.Response(
RuntimeException::class.qualifiedName,
"o noes",
ExceptionHandler.responseDetails("o noes"),
true
)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(task.getDynamicBackoffPeriod(any(), any())) doReturn taskBackoffMs
whenever(task.execute(any())) doThrow RuntimeException("o noes")
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(exceptionHandler.handles(any())) doReturn true
whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("re-runs the task") {
verify(queue).push(eq(message), eq(Duration.ofMillis(taskBackoffMs)))
}
}
}
describe("when the execution has stopped") {
val pipeline = pipeline {
status = TERMINAL
stage {
type = "whatever"
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("emits an event indicating that the task was canceled") {
verify(queue).push(
CompleteTask(
message.executionType,
message.executionId,
"foo",
message.stageId,
message.taskId,
CANCELED,
CANCELED
)
)
}
it("does not execute the task") {
verify(task, times(1)).aliases()
verify(task, times(3)).extensionClass
verifyNoMoreInteractions(task)
}
}
describe("when the execution has been canceled") {
val pipeline = pipeline {
status = RUNNING
isCanceled = true
stage {
type = "whatever"
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task as canceled") {
verify(queue).push(
CompleteTask(
message.executionType,
message.executionId,
"foo",
message.stageId,
message.taskId,
CANCELED,
CANCELED
)
)
}
it("it tries to cancel the task") {
verify(task).onCancel(any())
}
}
describe("when the execution has been paused") {
val pipeline = pipeline {
status = PAUSED
stage {
type = "whatever"
status = RUNNING
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task as paused") {
verify(queue).push(PauseTask(message))
}
it("does not execute the task") {
verify(task, times(1)).aliases()
verify(task, times(3)).extensionClass
verifyNoMoreInteractions(task)
}
}
describe("when the task has exceeded its timeout") {
given("the execution was never paused") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("fails the task") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
given("the execution was marked to continue") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli()
}
context["failPipeline"] = false
context["continuePipeline"] = true
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task as failed but continue") {
verify(queue).push(CompleteTask(message, FAILED_CONTINUE, TERMINAL))
}
}
given("the execution is marked to succeed on timeout") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
stage {
type = "whatever"
context = hashMapOf<String, Any>("markSuccessfulOnTimeout" to true)
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task as succeeded") {
verify(queue).push(CompleteTask(message, SUCCEEDED))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
given("the execution had been paused") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
paused = PausedDetails().apply {
pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli()
resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli()
}
stage {
type = "whatever"
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("executes the task") {
verify(task).execute(any())
}
}
given("the execution had been paused but is timed out anyway") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
paused = PausedDetails().apply {
pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli()
resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli()
}
stage {
type = "whatever"
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.plusMinutes(1).toMillis() + 1).toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("fails the task") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
given("the execution had been paused but only before this task started running") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
paused = PausedDetails().apply {
pauseTime = clock.instant().minus(Minutes.of(10)).toEpochMilli()
resumeTime = clock.instant().minus(Minutes.of(9)).toEpochMilli()
}
stage {
type = "whatever"
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("fails the task") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
given("the stage waited for an execution window") {
val timeout = Duration.ofMinutes(5)
val windowDuration = Duration.ofHours(1)
val windowStartedAt = clock.instant().minus(timeout).minus(windowDuration).plusSeconds(1)
val windowEndedAt = clock.instant().minus(timeout).plusSeconds(1)
val pipeline = pipeline {
stage {
stage {
type = RestrictExecutionDuringTimeWindow.TYPE
status = SUCCEEDED
startTime = windowStartedAt.toEpochMilli()
endTime = windowEndedAt.toEpochMilli()
}
refId = "1"
type = "whatever"
context[STAGE_TIMEOUT_OVERRIDE_KEY] = timeout.toMillis()
startTime = windowStartedAt.toEpochMilli()
task {
id = "1"
startTime = windowEndedAt.toEpochMilli()
status = RUNNING
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, pipeline.application, stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("executes the task") {
verify(task).execute(pipeline.stageByRef("1"))
}
}
given("the stage waited for an execution window but is timed out anyway") {
val timeout = Duration.ofMinutes(5)
val windowDuration = Duration.ofHours(1)
val windowStartedAt = clock.instant().minus(timeout).minus(windowDuration).minusSeconds(1)
val windowEndedAt = clock.instant().minus(timeout).minusSeconds(1)
val pipeline = pipeline {
stage {
stage {
type = RestrictExecutionDuringTimeWindow.TYPE
status = SUCCEEDED
startTime = windowStartedAt.toEpochMilli()
endTime = windowEndedAt.toEpochMilli()
}
refId = "1"
type = "whatever"
context[STAGE_TIMEOUT_OVERRIDE_KEY] = timeout.toMillis()
startTime = windowStartedAt.toEpochMilli()
task {
id = "1"
startTime = windowEndedAt.toEpochMilli()
status = RUNNING
}
}
}
val message = RunTask(pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("fails the task") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
}
describe("handles onTimeout responses") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
given("the task returns fail_continue") {
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
whenever(task.onTimeout(any())) doReturn TaskResult.ofStatus(FAILED_CONTINUE)
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task fail_continue") {
verify(queue).push(CompleteTask(message, FAILED_CONTINUE))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
given("the task returns terminal") {
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
whenever(task.onTimeout(any())) doReturn TaskResult.ofStatus(TERMINAL)
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task terminal") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
given("the task returns succeeded") {
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
whenever(task.onTimeout(any())) doReturn TaskResult.ofStatus(SUCCEEDED)
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
subject
}
it("marks the task terminal") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
}
given("there is a timeout override") {
val timeout = Duration.ofMinutes(5)
val timeoutOverride = Duration.ofMinutes(10)
timeoutOverride.toMillis().let { listOf(it.toInt(), it, it.toDouble()) }.forEach { stageTimeoutMs ->
and("the override is a ${stageTimeoutMs.javaClass.simpleName}") {
and("the stage is between the default and overridden duration") {
val pipeline = pipeline {
stage {
type = "whatever"
context["stageTimeoutMs"] = stageTimeoutMs
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli()
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val taskResult = TaskResult.RUNNING
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("executes the task") {
verify(task).execute(any())
}
}
and("the timeout override has been exceeded by stage") {
and("the stage has never been paused") {
val pipeline = pipeline {
stage {
type = "whatever"
context["stageTimeoutMs"] = stageTimeoutMs
startTime = clock.instant().minusMillis(timeoutOverride.toMillis() + 1).toEpochMilli()
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val taskResult = TaskResult.RUNNING
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("fails the task") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
and("the execution had been paused") {
val pipeline = pipeline {
paused = PausedDetails().apply {
pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli()
resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli()
}
stage {
type = "whatever"
context["stageTimeoutMs"] = stageTimeoutMs
startTime = clock.instant().minusMillis(timeoutOverride.toMillis() + 1).toEpochMilli()
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val taskResult = TaskResult.RUNNING
val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("executes the task") {
verify(task).execute(any())
}
}
and("the execution had been paused but is timed out anyway") {
val pipeline = pipeline {
paused = PausedDetails().apply {
pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli()
resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli()
}
stage {
type = "whatever"
context["stageTimeoutMs"] = stageTimeoutMs
startTime = clock.instant().minusMillis(timeoutOverride.plusMinutes(1).toMillis() + 1).toEpochMilli()
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli()
}
}
}
val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("fails the task") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
and("the execution had been paused but only before this stage started running") {
val pipeline = pipeline {
paused = PausedDetails().apply {
pauseTime = clock.instant().minus(Minutes.of(15)).toEpochMilli()
resumeTime = clock.instant().minus(Minutes.of(14)).toEpochMilli()
}
stage {
type = "whatever"
context["stageTimeoutMs"] = stageTimeoutMs
startTime = clock.instant().minusMillis(timeoutOverride.toMillis() + 1).toEpochMilli()
task {
id = "1"
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() - 1).toEpochMilli()
}
}
}
val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(task.getDynamicTimeout(any())) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("fails the task") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
}
and("the task is an overridabletimeout task that shouldn't time out") {
val pipeline = pipeline {
stage {
type = "whatever"
context["stageTimeoutMs"] = stageTimeoutMs
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() // started 5.1 minutes ago
task {
id = "1"
implementingClass = DummyTimeoutOverrideTask::class.jvmName
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli() // started 5.1 minutes ago
}
}
}
val stage = pipeline.stages.first()
val taskResult = TaskResult.RUNNING
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTimeoutOverrideTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(timeoutOverrideTask, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(timeoutOverrideTask, stage, taskResult)) doReturn taskResult }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
whenever(timeoutOverrideTask.timeout) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("executes the task") {
verify(timeoutOverrideTask).execute(any())
}
}
}
}
}
}
describe("expressions in the context") {
mapOf(
"\${1 == 2}" to false,
"\${1 == 1}" to true,
mapOf("key" to "\${1 == 2}") to mapOf("key" to false),
mapOf("key" to "\${1 == 1}") to mapOf("key" to true),
mapOf("key" to mapOf("key" to "\${1 == 2}")) to mapOf("key" to mapOf("key" to false)),
mapOf("key" to mapOf("key" to "\${1 == 1}")) to mapOf("key" to mapOf("key" to true))
).forEach { expression, expected ->
given("an expression $expression in the stage context") {
val pipeline = pipeline {
stage {
refId = "1"
type = "whatever"
context["expr"] = expression
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val taskResult = TaskResult.SUCCEEDED
val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("parses the expression") {
verify(task).execute(
check {
assertThat(it.context["expr"]).isEqualTo(expected)
}
)
}
}
}
describe("can reference non-existent trigger props") {
mapOf(
"\${trigger.type == 'manual'}" to true,
"\${trigger.buildNumber == null}" to true,
"\${trigger.quax ?: 'no quax'}" to "no quax"
).forEach { expression, expected ->
given("an expression $expression in the stage context") {
val pipeline = pipeline {
stage {
refId = "1"
type = "whatever"
context["expr"] = expression
trigger = DefaultTrigger("manual")
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val taskResult = TaskResult.SUCCEEDED
val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("evaluates the expression") {
verify(task).execute(
check {
assertThat(it.context["expr"]).isEqualTo(expected)
}
)
}
}
}
}
given("a reference to deployedServerGroups in the stage context") {
val pipeline = pipeline {
stage {
refId = "1"
type = "createServerGroup"
context = mapOf(
"deploy.server.groups" to mapOf(
"us-west-1" to listOf(
"spindemo-test-v008"
)
),
"account" to "mgmttest",
"region" to "us-west-1"
)
status = SUCCEEDED
}
stage {
refId = "2"
requisiteStageRefIds = setOf("1")
type = "whatever"
context["command"] = "serverGroupDetails.groovy \${ deployedServerGroups[0].account } \${ deployedServerGroups[0].region } \${ deployedServerGroups[0].serverGroup }"
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stageByRef("2")
val taskResult = TaskResult.SUCCEEDED
val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("2").id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("resolves deployed server groups") {
verify(task).execute(
check {
assertThat(it.context["command"]).isEqualTo("serverGroupDetails.groovy mgmttest us-west-1 spindemo-test-v008")
}
)
}
}
given("parameters in the context and in the pipeline") {
val pipeline = pipeline {
trigger = DefaultTrigger(type = "manual", parameters = mutableMapOf("dummy" to "foo"))
stage {
refId = "1"
type = "jenkins"
context["parameters"] = mutableMapOf(
"message" to "o hai"
)
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stages.first()
val taskResult = TaskResult.SUCCEEDED
val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stageByRef("1").id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("does not overwrite the stage's parameters with the pipeline's") {
verify(task).execute(
check {
assertThat(it.context["parameters"]).isEqualTo(mapOf("message" to "o hai"))
}
)
}
}
given("an expression in the context that refers to a prior stage output") {
val pipeline = pipeline {
stage {
refId = "1"
outputs["foo"] = "bar"
}
stage {
refId = "2"
requisiteStageRefIds = setOf("1")
context["expression"] = "\${foo}"
type = "whatever"
task {
id = "1"
startTime = clock.instant().toEpochMilli()
}
}
}
val stage = pipeline.stageByRef("2")
val taskResult = TaskResult.SUCCEEDED
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
on("receiving $message") {
subject.handle(message)
}
it("passes the decoded expression to the task") {
verify(task).execute(
check {
assertThat(it.context["expression"]).isEqualTo("bar")
}
)
}
}
}
describe("no such task") {
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
implementingClass = InvalidTask::class.jvmName
}
}
}
val message = RunTask(pipeline.type, pipeline.id, "foo", pipeline.stages.first().id, "1", InvalidTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("does not run any tasks") {
verify(task, times(1)).aliases()
verify(task, times(5)).extensionClass
verifyNoMoreInteractions(task)
}
it("emits an error event") {
verify(queue).push(isA<InvalidTaskType>())
}
}
describe("manual skip behavior") {
given("a stage with a manual skip flag") {
val pipeline = pipeline {
stage {
type = singleTaskStage.type
task {
id = "1"
implementingClass = DummyTask::class.jvmName
}
context["manualSkip"] = true
}
}
val stage = pipeline.stageByRef("1")
val taskResult = TaskResult.SUCCEEDED
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyTask::class.java)
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(task, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(task, stage, taskResult)) doReturn taskResult }
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("sets the task's status to SKIPPED and completes the task") {
verify(queue).push(CompleteTask(message, SKIPPED))
}
}
}
describe("max configurable back off value") {
setOf(
BackOff(5_000L, 10_000L, 20_000L, 30_000L, 30_000L),
BackOff(10_000L, 20_000L, 30_000L, 5_000L, 30_000L),
BackOff(20_000L, 30_000L, 5_000L, 10_000L, 30_000L),
BackOff(30_000L, 5_000L, 10_000L, 20_000L, 30_000L),
BackOff(20_000L, 5_000L, 10_000L, 30_002L, 30_001L)
).forEach { backOff ->
given("the back off values $backOff") {
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
implementingClass = DummyCloudProviderAwareTask::class.jvmName
startTime = clock.instant().toEpochMilli()
context["cloudProvider"] = "aws"
context["deploy.account.name"] = "someAccount"
}
}
}
val stage = pipeline.stages.first()
val message = RunTask(pipeline.type, pipeline.id, "foo", stage.id, "1", DummyCloudProviderAwareTask::class.java)
val taskResult = TaskResult.RUNNING
beforeGroup {
tasks.forEach { whenever(it.extensionClass) doReturn it::class.java }
whenever(cloudProviderAwareTask.execute(any())) doReturn taskResult
taskExecutionInterceptors.forEach { whenever(it.maxTaskBackoff()) doReturn backOff.limit }
taskExecutionInterceptors.forEach { whenever(it.beforeTaskExecution(cloudProviderAwareTask, stage)) doReturn stage }
taskExecutionInterceptors.forEach { whenever(it.afterTaskExecution(cloudProviderAwareTask, stage, taskResult)) doReturn taskResult }
whenever(cloudProviderAwareTask.getDynamicBackoffPeriod(any(), any())) doReturn backOff.taskBackOffMs
whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.global.backOffPeriod"), any())) doReturn backOff.globalBackOffMs
whenever(cloudProviderAwareTask.hasCloudProvider(any())) doReturn true
whenever(cloudProviderAwareTask.getCloudProvider(any<StageExecution>())) doReturn "aws"
whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.aws.backOffPeriod"), any())) doReturn backOff.cloudProviderBackOffMs
whenever(cloudProviderAwareTask.hasCredentials(any())) doReturn true
whenever(cloudProviderAwareTask.getCredentials(any<StageExecution>())) doReturn "someAccount"
whenever(dynamicConfigService.getConfig(eq(Long::class.java), eq("tasks.aws.someAccount.backOffPeriod"), any())) doReturn backOff.accountBackOffMs
whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("selects the max value, unless max value is over limit ${backOff.limit} in which case limit is used") {
verify(queue).push(message, Duration.ofMillis(backOff.expectedMaxBackOffMs))
}
}
}
}
})
data class BackOff(
val taskBackOffMs: Long,
val globalBackOffMs: Long,
val cloudProviderBackOffMs: Long,
val accountBackOffMs: Long,
val expectedMaxBackOffMs: Long,
val limit: Long = 30_001L
)
| apache-2.0 | 3b028f86d07f5258f437cbc062c32d5b | 36.515397 | 175 | 0.606745 | 4.920706 | false | false | false | false |
MarkNKamau/JustJava-Android | app/src/main/java/com/marknkamau/justjava/JustJavaApp.kt | 1 | 2360 | package com.marknkamau.justjava
import android.app.Application
import com.google.android.libraries.places.api.Places
import com.marknjunge.core.data.local.PreferencesRepository
import com.marknjunge.core.data.model.Resource
import com.marknjunge.core.data.repository.AuthRepository
import com.marknjunge.core.data.repository.UsersRepository
import com.marknkamau.justjava.utils.ReleaseTree
import com.marknkamau.justjava.utils.toast
import dagger.hilt.android.HiltAndroidApp
import io.sentry.android.core.SentryAndroid
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
@Suppress("unused")
@HiltAndroidApp
open class JustJavaApp : Application() {
@Inject
lateinit var preferencesRepository: PreferencesRepository
@Inject
lateinit var usersRepository: UsersRepository
@Inject
lateinit var authRepository: AuthRepository
private val coroutineScope = CoroutineScope(Dispatchers.Main)
override fun onCreate() {
super.onCreate()
if (BuildConfig.DEBUG) {
Timber.plant(object : Timber.DebugTree() {
override fun createStackElementTag(element: StackTraceElement): String {
return "Timber ${element.methodName} (${element.fileName}:${element.lineNumber})"
}
})
} else {
Timber.plant(ReleaseTree())
SentryAndroid.init(this) { options ->
options.dsn = BuildConfig.sentryDsn
}
}
Places.initialize(this, getString(R.string.google_api_key))
if (preferencesRepository.isSignedIn) {
coroutineScope.launch {
when (val resource = usersRepository.updateFcmToken()) {
is Resource.Success -> usersRepository.getCurrentUser().collect { }
is Resource.Failure -> {
if (resource.response.message == "Invalid session-id") {
Timber.d("Signed out")
authRepository.signOutLocally()
} else {
toast(resource.response.message)
}
}
}
}
}
}
}
| apache-2.0 | 229af745aa19f66283ff0179192a5703 | 34.757576 | 101 | 0.641525 | 5.119306 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt | 1 | 3015 | package info.nightscout.androidaps.plugins.general.automation.actions
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.automation.R
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.interfaces.Loop
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration
import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.JsonHelper
import org.json.JSONObject
import javax.inject.Inject
class ActionLoopSuspend(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var loop: Loop
@Inject lateinit var rxBus: RxBus
@Inject lateinit var uel: UserEntryLogger
var minutes = InputDuration(30, InputDuration.TimeUnit.MINUTES)
override fun friendlyName(): Int = R.string.suspendloop
override fun shortDescription(): String = rh.gs(R.string.suspendloopforXmin, minutes.getMinutes())
@DrawableRes override fun icon(): Int = R.drawable.ic_pause_circle_outline_24dp
override fun doAction(callback: Callback) {
if (!loop.isSuspended) {
loop.suspendLoop(minutes.getMinutes())
rxBus.send(EventRefreshOverview("ActionLoopSuspend"))
uel.log(
UserEntry.Action.SUSPEND, Sources.Automation, title + ": " + rh.gs(R.string.suspendloopforXmin, minutes.getMinutes()),
ValueWithUnit.Minute(minutes.getMinutes())
)
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run()
} else {
callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadysuspended)).run()
}
}
override fun toJSON(): String {
val data = JSONObject().put("minutes", minutes.getMinutes())
return JSONObject()
.put("type", this.javaClass.name)
.put("data", data)
.toString()
}
override fun fromJSON(data: String): Action {
val o = JSONObject(data)
minutes.setMinutes(JsonHelper.safeGetInt(o, "minutes"))
return this
}
override fun hasDialog(): Boolean = true
override fun generateDialog(root: LinearLayout) {
LayoutBuilder()
.add(LabelWithElement(rh, rh.gs(R.string.duration_min_label), "", minutes))
.build(root)
}
override fun isValid(): Boolean = minutes.value > 5
} | agpl-3.0 | 8079f77730ff22442b5ce354f516d31a | 40.888889 | 134 | 0.733665 | 4.527027 | false | false | false | false |
k9mail/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/activity/compose/RecipientPresenter.kt | 1 | 28832 | package com.fsck.k9.activity.compose
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.view.Menu
import androidx.core.content.ContextCompat
import androidx.loader.app.LoaderManager
import com.fsck.k9.Account
import com.fsck.k9.Identity
import com.fsck.k9.K9
import com.fsck.k9.activity.compose.ComposeCryptoStatus.AttachErrorState
import com.fsck.k9.activity.compose.ComposeCryptoStatus.SendErrorState
import com.fsck.k9.autocrypt.AutocryptDraftStateHeader
import com.fsck.k9.autocrypt.AutocryptDraftStateHeaderParser
import com.fsck.k9.helper.Contacts
import com.fsck.k9.helper.MailTo
import com.fsck.k9.helper.ReplyToParser
import com.fsck.k9.mail.Address
import com.fsck.k9.mail.Flag
import com.fsck.k9.mail.Message
import com.fsck.k9.mail.Message.RecipientType
import com.fsck.k9.message.AutocryptStatusInteractor
import com.fsck.k9.message.AutocryptStatusInteractor.RecipientAutocryptStatus
import com.fsck.k9.message.ComposePgpEnableByDefaultDecider
import com.fsck.k9.message.ComposePgpInlineDecider
import com.fsck.k9.message.MessageBuilder
import com.fsck.k9.message.PgpMessageBuilder
import com.fsck.k9.ui.R
import com.fsck.k9.view.RecipientSelectView.Recipient
import org.openintents.openpgp.OpenPgpApiManager
import org.openintents.openpgp.OpenPgpApiManager.OpenPgpApiManagerCallback
import org.openintents.openpgp.OpenPgpApiManager.OpenPgpProviderError
import org.openintents.openpgp.OpenPgpApiManager.OpenPgpProviderState
import timber.log.Timber
private const val STATE_KEY_CC_SHOWN = "state:ccShown"
private const val STATE_KEY_BCC_SHOWN = "state:bccShown"
private const val STATE_KEY_LAST_FOCUSED_TYPE = "state:lastFocusedType"
private const val STATE_KEY_CURRENT_CRYPTO_MODE = "state:currentCryptoMode"
private const val STATE_KEY_CRYPTO_ENABLE_PGP_INLINE = "state:cryptoEnablePgpInline"
private const val CONTACT_PICKER_TO = 1
private const val CONTACT_PICKER_CC = 2
private const val CONTACT_PICKER_BCC = 3
private const val OPENPGP_USER_INTERACTION = 4
private const val REQUEST_CODE_AUTOCRYPT = 5
private const val PGP_DIALOG_DISPLAY_THRESHOLD = 2
class RecipientPresenter(
private val context: Context,
loaderManager: LoaderManager,
private val openPgpApiManager: OpenPgpApiManager,
private val recipientMvpView: RecipientMvpView,
account: Account,
private val composePgpInlineDecider: ComposePgpInlineDecider,
private val composePgpEnableByDefaultDecider: ComposePgpEnableByDefaultDecider,
private val autocryptStatusInteractor: AutocryptStatusInteractor,
private val replyToParser: ReplyToParser,
private val draftStateHeaderParser: AutocryptDraftStateHeaderParser
) {
private lateinit var account: Account
private var alwaysBccAddresses: Array<Address>? = null
private var hasContactPicker: Boolean? = null
private var isReplyToEncryptedMessage = false
private var lastFocusedType = RecipientType.TO
private var currentCryptoMode = CryptoMode.NO_CHOICE
var isForceTextMessageFormat = false
private set
var currentCachedCryptoStatus: ComposeCryptoStatus? = null
private set
val toAddresses: List<Address>
get() = recipientMvpView.toAddresses
val ccAddresses: List<Address>
get() = recipientMvpView.ccAddresses
val bccAddresses: List<Address>
get() = recipientMvpView.bccAddresses
private val allRecipients: List<Recipient>
get() = with(recipientMvpView) { toRecipients + ccRecipients + bccRecipients }
init {
recipientMvpView.setPresenter(this)
recipientMvpView.setLoaderManager(loaderManager)
onSwitchAccount(account)
}
fun checkRecipientsOkForSending(): Boolean {
recipientMvpView.recipientToTryPerformCompletion()
recipientMvpView.recipientCcTryPerformCompletion()
recipientMvpView.recipientBccTryPerformCompletion()
if (recipientMvpView.recipientToHasUncompletedText()) {
recipientMvpView.showToUncompletedError()
return true
}
if (recipientMvpView.recipientCcHasUncompletedText()) {
recipientMvpView.showCcUncompletedError()
return true
}
if (recipientMvpView.recipientBccHasUncompletedText()) {
recipientMvpView.showBccUncompletedError()
return true
}
if (toAddresses.isEmpty() && ccAddresses.isEmpty() && bccAddresses.isEmpty()) {
recipientMvpView.showNoRecipientsError()
return true
}
return false
}
fun initFromReplyToMessage(message: Message?, isReplyAll: Boolean) {
val replyToAddresses = if (isReplyAll) {
replyToParser.getRecipientsToReplyAllTo(message, account)
} else {
replyToParser.getRecipientsToReplyTo(message, account)
}
addToAddresses(*replyToAddresses.to)
addCcAddresses(*replyToAddresses.cc)
val shouldSendAsPgpInline = composePgpInlineDecider.shouldReplyInline(message)
if (shouldSendAsPgpInline) {
isForceTextMessageFormat = true
}
isReplyToEncryptedMessage = composePgpEnableByDefaultDecider.shouldEncryptByDefault(message)
}
fun initFromTrustIdAction(trustId: String?) {
addToAddresses(*Address.parse(trustId))
currentCryptoMode = CryptoMode.CHOICE_ENABLED
}
fun initFromMailto(mailTo: MailTo) {
addToAddresses(*mailTo.to)
addCcAddresses(*mailTo.cc)
addBccAddresses(*mailTo.bcc)
}
fun initFromSendOrViewIntent(intent: Intent) {
val toAddresses = intent.getStringArrayExtra(Intent.EXTRA_EMAIL)?.toAddressArray()
val ccAddresses = intent.getStringArrayExtra(Intent.EXTRA_CC)?.toAddressArray()
val bccAddresses = intent.getStringArrayExtra(Intent.EXTRA_BCC)?.toAddressArray()
if (toAddresses != null) {
addToAddresses(*toAddresses)
}
if (ccAddresses != null) {
addCcAddresses(*ccAddresses)
}
if (bccAddresses != null) {
addBccAddresses(*bccAddresses)
}
}
fun onRestoreInstanceState(savedInstanceState: Bundle) {
recipientMvpView.setCcVisibility(savedInstanceState.getBoolean(STATE_KEY_CC_SHOWN))
recipientMvpView.setBccVisibility(savedInstanceState.getBoolean(STATE_KEY_BCC_SHOWN))
lastFocusedType = RecipientType.valueOf(savedInstanceState.getString(STATE_KEY_LAST_FOCUSED_TYPE)!!)
currentCryptoMode = CryptoMode.valueOf(savedInstanceState.getString(STATE_KEY_CURRENT_CRYPTO_MODE)!!)
isForceTextMessageFormat = savedInstanceState.getBoolean(STATE_KEY_CRYPTO_ENABLE_PGP_INLINE)
updateRecipientExpanderVisibility()
}
fun onSaveInstanceState(outState: Bundle) {
outState.putBoolean(STATE_KEY_CC_SHOWN, recipientMvpView.isCcVisible)
outState.putBoolean(STATE_KEY_BCC_SHOWN, recipientMvpView.isBccVisible)
outState.putString(STATE_KEY_LAST_FOCUSED_TYPE, lastFocusedType.toString())
outState.putString(STATE_KEY_CURRENT_CRYPTO_MODE, currentCryptoMode.toString())
outState.putBoolean(STATE_KEY_CRYPTO_ENABLE_PGP_INLINE, isForceTextMessageFormat)
}
fun initFromDraftMessage(message: Message) {
initRecipientsFromDraftMessage(message)
val draftStateHeader = message.getHeader(AutocryptDraftStateHeader.AUTOCRYPT_DRAFT_STATE_HEADER)
if (draftStateHeader.size == 1) {
initEncryptionStateFromDraftStateHeader(draftStateHeader.first())
} else {
initPgpInlineFromDraftMessage(message)
}
}
private fun initEncryptionStateFromDraftStateHeader(headerValue: String) {
val autocryptDraftStateHeader = draftStateHeaderParser.parseAutocryptDraftStateHeader(headerValue)
if (autocryptDraftStateHeader != null) {
initEncryptionStateFromDraftStateHeader(autocryptDraftStateHeader)
}
}
private fun initRecipientsFromDraftMessage(message: Message) {
addToAddresses(*message.getRecipients(RecipientType.TO))
addCcAddresses(*message.getRecipients(RecipientType.CC))
addBccAddresses(*message.getRecipients(RecipientType.BCC))
}
private fun initEncryptionStateFromDraftStateHeader(draftState: AutocryptDraftStateHeader) {
isForceTextMessageFormat = draftState.isPgpInline
isReplyToEncryptedMessage = draftState.isReply
if (!draftState.isByChoice) {
// TODO if it's not by choice, we're going with our defaults. should we do something here if those differ?
return
}
currentCryptoMode = when {
draftState.isSignOnly -> CryptoMode.SIGN_ONLY
draftState.isEncrypt -> CryptoMode.CHOICE_ENABLED
else -> CryptoMode.CHOICE_DISABLED
}
}
private fun initPgpInlineFromDraftMessage(message: Message) {
isForceTextMessageFormat = message.isSet(Flag.X_DRAFT_OPENPGP_INLINE)
}
private fun addToAddresses(vararg toAddresses: Address) {
addRecipientsFromAddresses(RecipientType.TO, *toAddresses)
}
private fun addCcAddresses(vararg ccAddresses: Address) {
if (ccAddresses.isNotEmpty()) {
addRecipientsFromAddresses(RecipientType.CC, *ccAddresses)
recipientMvpView.setCcVisibility(true)
updateRecipientExpanderVisibility()
}
}
private fun addBccAddresses(vararg bccRecipients: Address) {
if (bccRecipients.isNotEmpty()) {
addRecipientsFromAddresses(RecipientType.BCC, *bccRecipients)
recipientMvpView.setBccVisibility(true)
updateRecipientExpanderVisibility()
}
}
private fun addAlwaysBcc() {
val alwaysBccAddresses = Address.parse(account.alwaysBcc)
this.alwaysBccAddresses = alwaysBccAddresses
if (alwaysBccAddresses.isEmpty()) return
object : RecipientLoader(context, account.openPgpProvider, *alwaysBccAddresses) {
override fun deliverResult(result: List<Recipient>?) {
val recipientArray = result!!.toTypedArray()
recipientMvpView.silentlyAddBccAddresses(*recipientArray)
stopLoading()
abandon()
}
}.startLoading()
}
private fun removeAlwaysBcc() {
alwaysBccAddresses?.let { alwaysBccAddresses ->
recipientMvpView.silentlyRemoveBccAddresses(alwaysBccAddresses)
}
}
fun onPrepareOptionsMenu(menu: Menu) {
val currentCryptoStatus = currentCachedCryptoStatus
if (currentCryptoStatus != null && currentCryptoStatus.isProviderStateOk()) {
val isEncrypting = currentCryptoStatus.isEncryptionEnabled
menu.findItem(R.id.openpgp_encrypt_enable).isVisible = !isEncrypting
menu.findItem(R.id.openpgp_encrypt_disable).isVisible = isEncrypting
val showSignOnly = !account.isOpenPgpHideSignOnly
val isSignOnly = currentCryptoStatus.isSignOnly
menu.findItem(R.id.openpgp_sign_only).isVisible = showSignOnly && !isSignOnly
menu.findItem(R.id.openpgp_sign_only_disable).isVisible = showSignOnly && isSignOnly
val pgpInlineModeEnabled = currentCryptoStatus.isPgpInlineModeEnabled
val showPgpInlineEnable = (isEncrypting || isSignOnly) && !pgpInlineModeEnabled
menu.findItem(R.id.openpgp_inline_enable).isVisible = showPgpInlineEnable
menu.findItem(R.id.openpgp_inline_disable).isVisible = pgpInlineModeEnabled
} else {
menu.findItem(R.id.openpgp_inline_enable).isVisible = false
menu.findItem(R.id.openpgp_inline_disable).isVisible = false
menu.findItem(R.id.openpgp_encrypt_enable).isVisible = false
menu.findItem(R.id.openpgp_encrypt_disable).isVisible = false
menu.findItem(R.id.openpgp_sign_only).isVisible = false
menu.findItem(R.id.openpgp_sign_only_disable).isVisible = false
}
menu.findItem(R.id.add_from_contacts).isVisible = hasContactPermission() && hasContactPicker()
}
fun onSwitchAccount(account: Account) {
this.account = account
if (account.isAlwaysShowCcBcc) {
recipientMvpView.setCcVisibility(true)
recipientMvpView.setBccVisibility(true)
updateRecipientExpanderVisibility()
}
removeAlwaysBcc()
addAlwaysBcc()
val openPgpProvider = account.openPgpProvider
recipientMvpView.setCryptoProvider(openPgpProvider)
openPgpApiManager.setOpenPgpProvider(openPgpProvider, openPgpCallback)
}
fun onSwitchIdentity(identity: Identity) {
// TODO decide what actually to do on identity switch?
asyncUpdateCryptoStatus()
}
fun onClickToLabel() {
recipientMvpView.requestFocusOnToField()
}
fun onClickCcLabel() {
recipientMvpView.requestFocusOnCcField()
}
fun onClickBccLabel() {
recipientMvpView.requestFocusOnBccField()
}
fun onClickRecipientExpander() {
recipientMvpView.setCcVisibility(true)
recipientMvpView.setBccVisibility(true)
updateRecipientExpanderVisibility()
}
private fun hideEmptyExtendedRecipientFields() {
if (recipientMvpView.ccAddresses.isEmpty()) {
recipientMvpView.setCcVisibility(false)
if (lastFocusedType == RecipientType.CC) {
lastFocusedType = RecipientType.TO
}
}
if (recipientMvpView.bccAddresses.isEmpty()) {
recipientMvpView.setBccVisibility(false)
if (lastFocusedType == RecipientType.BCC) {
lastFocusedType = RecipientType.TO
}
}
updateRecipientExpanderVisibility()
}
private fun updateRecipientExpanderVisibility() {
val notBothAreVisible = !(recipientMvpView.isCcVisible && recipientMvpView.isBccVisible)
recipientMvpView.setRecipientExpanderVisibility(notBothAreVisible)
}
fun asyncUpdateCryptoStatus() {
currentCachedCryptoStatus = null
val openPgpProviderState = openPgpApiManager.openPgpProviderState
var accountCryptoKey: Long? = account.openPgpKey
if (accountCryptoKey == Account.NO_OPENPGP_KEY) {
accountCryptoKey = null
}
val composeCryptoStatus = ComposeCryptoStatus(
openPgpProviderState = openPgpProviderState,
openPgpKeyId = accountCryptoKey,
recipientAddresses = allRecipients,
isPgpInlineModeEnabled = isForceTextMessageFormat,
isSenderPreferEncryptMutual = account.autocryptPreferEncryptMutual,
isReplyToEncrypted = isReplyToEncryptedMessage,
isEncryptAllDrafts = account.isOpenPgpEncryptAllDrafts,
isEncryptSubject = account.isOpenPgpEncryptSubject,
cryptoMode = currentCryptoMode
)
if (openPgpProviderState != OpenPgpProviderState.OK) {
currentCachedCryptoStatus = composeCryptoStatus
redrawCachedCryptoStatusIcon()
return
}
val recipientAddresses = composeCryptoStatus.recipientAddressesAsArray
object : AsyncTask<Void?, Void?, RecipientAutocryptStatus?>() {
override fun doInBackground(vararg params: Void?): RecipientAutocryptStatus? {
val openPgpApi = openPgpApiManager.openPgpApi ?: return null
return autocryptStatusInteractor.retrieveCryptoProviderRecipientStatus(openPgpApi, recipientAddresses)
}
override fun onPostExecute(recipientAutocryptStatus: RecipientAutocryptStatus?) {
currentCachedCryptoStatus = if (recipientAutocryptStatus != null) {
composeCryptoStatus.withRecipientAutocryptStatus(recipientAutocryptStatus)
} else {
composeCryptoStatus
}
redrawCachedCryptoStatusIcon()
}
}.execute()
}
private fun redrawCachedCryptoStatusIcon() {
val cryptoStatus = checkNotNull(currentCachedCryptoStatus) { "must have cached crypto status to redraw it!" }
recipientMvpView.setRecipientTokensShowCryptoEnabled(cryptoStatus.isEncryptionEnabled)
recipientMvpView.showCryptoStatus(cryptoStatus.displayType)
recipientMvpView.showCryptoSpecialMode(cryptoStatus.specialModeDisplayType)
}
fun onToTokenAdded() {
asyncUpdateCryptoStatus()
}
fun onToTokenRemoved() {
asyncUpdateCryptoStatus()
}
fun onToTokenChanged() {
asyncUpdateCryptoStatus()
}
fun onCcTokenAdded() {
asyncUpdateCryptoStatus()
}
fun onCcTokenRemoved() {
asyncUpdateCryptoStatus()
}
fun onCcTokenChanged() {
asyncUpdateCryptoStatus()
}
fun onBccTokenAdded() {
asyncUpdateCryptoStatus()
}
fun onBccTokenRemoved() {
asyncUpdateCryptoStatus()
}
fun onBccTokenChanged() {
asyncUpdateCryptoStatus()
}
fun onCryptoModeChanged(cryptoMode: CryptoMode) {
currentCryptoMode = cryptoMode
asyncUpdateCryptoStatus()
}
fun onCryptoPgpInlineChanged(enablePgpInline: Boolean) {
isForceTextMessageFormat = enablePgpInline
asyncUpdateCryptoStatus()
}
private fun addRecipientsFromAddresses(recipientType: RecipientType, vararg addresses: Address) {
object : RecipientLoader(context, account.openPgpProvider, *addresses) {
override fun deliverResult(result: List<Recipient>?) {
val recipientArray = result!!.toTypedArray()
recipientMvpView.addRecipients(recipientType, *recipientArray)
stopLoading()
abandon()
}
}.startLoading()
}
private fun addRecipientFromContactUri(recipientType: RecipientType, uri: Uri?) {
object : RecipientLoader(context, account.openPgpProvider, uri, false) {
override fun deliverResult(result: List<Recipient>?) {
// TODO handle multiple available mail addresses for a contact?
if (result!!.isEmpty()) {
recipientMvpView.showErrorContactNoAddress()
return
}
val recipient = result[0]
recipientMvpView.addRecipients(recipientType, recipient)
stopLoading()
abandon()
}
}.startLoading()
}
fun onToFocused() {
lastFocusedType = RecipientType.TO
}
fun onCcFocused() {
lastFocusedType = RecipientType.CC
}
fun onBccFocused() {
lastFocusedType = RecipientType.BCC
}
fun onMenuAddFromContacts() {
val requestCode = lastFocusedType.toRequestCode()
recipientMvpView.showContactPicker(requestCode)
}
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
CONTACT_PICKER_TO, CONTACT_PICKER_CC, CONTACT_PICKER_BCC -> {
if (resultCode != Activity.RESULT_OK || data == null) return
val recipientType = requestCode.toRecipientType()
addRecipientFromContactUri(recipientType, data.data)
}
OPENPGP_USER_INTERACTION -> {
openPgpApiManager.onUserInteractionResult()
}
REQUEST_CODE_AUTOCRYPT -> {
asyncUpdateCryptoStatus()
}
}
}
fun onNonRecipientFieldFocused() {
if (!account.isAlwaysShowCcBcc) {
hideEmptyExtendedRecipientFields()
}
}
fun onClickCryptoStatus() {
when (openPgpApiManager.openPgpProviderState) {
OpenPgpProviderState.UNCONFIGURED -> {
Timber.e("click on crypto status while unconfigured - this should not really happen?!")
}
OpenPgpProviderState.OK -> {
toggleEncryptionState(false)
}
OpenPgpProviderState.UI_REQUIRED -> {
// TODO show openpgp settings
val pendingIntent = openPgpApiManager.userInteractionPendingIntent
recipientMvpView.launchUserInteractionPendingIntent(pendingIntent, OPENPGP_USER_INTERACTION)
}
OpenPgpProviderState.UNINITIALIZED, OpenPgpProviderState.ERROR -> {
openPgpApiManager.refreshConnection()
}
}
}
private fun toggleEncryptionState(showGotIt: Boolean) {
val currentCryptoStatus = currentCachedCryptoStatus
if (currentCryptoStatus == null) {
Timber.e("click on crypto status while crypto status not available - should not really happen?!")
return
}
if (currentCryptoStatus.isEncryptionEnabled && !currentCryptoStatus.allRecipientsCanEncrypt()) {
recipientMvpView.showOpenPgpEnabledErrorDialog(false)
return
}
if (currentCryptoMode == CryptoMode.SIGN_ONLY) {
recipientMvpView.showErrorIsSignOnly()
return
}
val isEncryptOnNoChoice = currentCryptoStatus.canEncryptAndIsMutualDefault() ||
currentCryptoStatus.isReplyToEncrypted
if (currentCryptoMode == CryptoMode.NO_CHOICE) {
if (currentCryptoStatus.hasAutocryptPendingIntent()) {
recipientMvpView.launchUserInteractionPendingIntent(
currentCryptoStatus.autocryptPendingIntent, REQUEST_CODE_AUTOCRYPT
)
} else if (isEncryptOnNoChoice) {
// TODO warning dialog if we override, especially from reply!
onCryptoModeChanged(CryptoMode.CHOICE_DISABLED)
} else {
onCryptoModeChanged(CryptoMode.CHOICE_ENABLED)
if (showGotIt) {
recipientMvpView.showOpenPgpEncryptExplanationDialog()
}
}
} else if (currentCryptoMode == CryptoMode.CHOICE_DISABLED && !isEncryptOnNoChoice) {
onCryptoModeChanged(CryptoMode.CHOICE_ENABLED)
} else {
onCryptoModeChanged(CryptoMode.NO_CHOICE)
}
}
/**
* Does the device actually have a Contacts application suitable for picking a contact.
* As hard as it is to believe, some vendors ship without it.
*/
private fun hasContactPicker(): Boolean {
return hasContactPicker ?: isContactPickerAvailable().also { hasContactPicker = it }
}
private fun isContactPickerAvailable(): Boolean {
val contacts = Contacts.getInstance(context)
val resolveInfoList = context.packageManager.queryIntentActivities(contacts.contactPickerIntent(), 0)
return resolveInfoList.isNotEmpty()
}
private fun hasContactPermission(): Boolean {
val permissionState = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
return permissionState == PackageManager.PERMISSION_GRANTED
}
fun showPgpSendError(sendErrorState: SendErrorState) {
when (sendErrorState) {
SendErrorState.ENABLED_ERROR -> recipientMvpView.showOpenPgpEnabledErrorDialog(false)
SendErrorState.PROVIDER_ERROR -> recipientMvpView.showErrorOpenPgpConnection()
SendErrorState.KEY_CONFIG_ERROR -> recipientMvpView.showErrorNoKeyConfigured()
else -> throw AssertionError("not all error states handled, this is a bug!")
}
}
fun showPgpAttachError(attachErrorState: AttachErrorState) {
when (attachErrorState) {
AttachErrorState.IS_INLINE -> recipientMvpView.showErrorInlineAttach()
else -> throw AssertionError("not all error states handled, this is a bug!")
}
}
fun builderSetProperties(messageBuilder: MessageBuilder) {
require(messageBuilder !is PgpMessageBuilder) {
"PpgMessageBuilder must be called with ComposeCryptoStatus argument!"
}
messageBuilder.setTo(toAddresses)
messageBuilder.setCc(ccAddresses)
messageBuilder.setBcc(bccAddresses)
}
fun builderSetProperties(pgpMessageBuilder: PgpMessageBuilder, cryptoStatus: ComposeCryptoStatus) {
pgpMessageBuilder.setTo(toAddresses)
pgpMessageBuilder.setCc(ccAddresses)
pgpMessageBuilder.setBcc(bccAddresses)
pgpMessageBuilder.setOpenPgpApi(openPgpApiManager.openPgpApi)
pgpMessageBuilder.setCryptoStatus(cryptoStatus)
}
fun onMenuSetPgpInline(enablePgpInline: Boolean) {
onCryptoPgpInlineChanged(enablePgpInline)
if (enablePgpInline) {
val shouldShowPgpInlineDialog = checkAndIncrementPgpInlineDialogCounter()
if (shouldShowPgpInlineDialog) {
recipientMvpView.showOpenPgpInlineDialog(true)
}
}
}
fun onMenuSetSignOnly(enableSignOnly: Boolean) {
if (enableSignOnly) {
onCryptoModeChanged(CryptoMode.SIGN_ONLY)
val shouldShowPgpSignOnlyDialog = checkAndIncrementPgpSignOnlyDialogCounter()
if (shouldShowPgpSignOnlyDialog) {
recipientMvpView.showOpenPgpSignOnlyDialog(true)
}
} else {
onCryptoModeChanged(CryptoMode.NO_CHOICE)
}
}
fun onMenuToggleEncryption() {
toggleEncryptionState(true)
}
fun onCryptoPgpClickDisable() {
onCryptoModeChanged(CryptoMode.CHOICE_DISABLED)
}
fun onCryptoPgpSignOnlyDisabled() {
onCryptoPgpInlineChanged(false)
onCryptoModeChanged(CryptoMode.NO_CHOICE)
}
private fun checkAndIncrementPgpInlineDialogCounter(): Boolean {
val pgpInlineDialogCounter = K9.pgpInlineDialogCounter
if (pgpInlineDialogCounter < PGP_DIALOG_DISPLAY_THRESHOLD) {
K9.pgpInlineDialogCounter = pgpInlineDialogCounter + 1
K9.saveSettingsAsync()
return true
}
return false
}
private fun checkAndIncrementPgpSignOnlyDialogCounter(): Boolean {
val pgpSignOnlyDialogCounter = K9.pgpSignOnlyDialogCounter
if (pgpSignOnlyDialogCounter < PGP_DIALOG_DISPLAY_THRESHOLD) {
K9.pgpSignOnlyDialogCounter = pgpSignOnlyDialogCounter + 1
K9.saveSettingsAsync()
return true
}
return false
}
fun onClickCryptoSpecialModeIndicator() {
when {
currentCryptoMode == CryptoMode.SIGN_ONLY -> {
recipientMvpView.showOpenPgpSignOnlyDialog(false)
}
isForceTextMessageFormat -> {
recipientMvpView.showOpenPgpInlineDialog(false)
}
else -> {
error("This icon should not be clickable while no special mode is active!")
}
}
}
private val openPgpCallback = object : OpenPgpApiManagerCallback {
override fun onOpenPgpProviderStatusChanged() {
if (openPgpApiManager.openPgpProviderState == OpenPgpProviderState.UI_REQUIRED) {
recipientMvpView.showErrorOpenPgpUserInteractionRequired()
}
asyncUpdateCryptoStatus()
}
override fun onOpenPgpProviderError(error: OpenPgpProviderError) {
when (error) {
OpenPgpProviderError.ConnectionLost -> openPgpApiManager.refreshConnection()
OpenPgpProviderError.VersionIncompatible -> recipientMvpView.showErrorOpenPgpIncompatible()
OpenPgpProviderError.ConnectionFailed -> recipientMvpView.showErrorOpenPgpConnection()
else -> recipientMvpView.showErrorOpenPgpConnection()
}
}
}
private fun Array<String>.toAddressArray(): Array<Address> {
return flatMap { addressString ->
Address.parseUnencoded(addressString).toList()
}.toTypedArray()
}
private fun RecipientType.toRequestCode(): Int = when (this) {
RecipientType.TO -> CONTACT_PICKER_TO
RecipientType.CC -> CONTACT_PICKER_CC
RecipientType.BCC -> CONTACT_PICKER_BCC
else -> throw AssertionError("Unhandled case: $this")
}
private fun Int.toRecipientType(): RecipientType = when (this) {
CONTACT_PICKER_TO -> RecipientType.TO
CONTACT_PICKER_CC -> RecipientType.CC
CONTACT_PICKER_BCC -> RecipientType.BCC
else -> throw AssertionError("Unhandled case: $this")
}
enum class CryptoMode {
SIGN_ONLY, NO_CHOICE, CHOICE_DISABLED, CHOICE_ENABLED
}
}
| apache-2.0 | 0161428c64e9ed77607ec6217c1535d7 | 36.444156 | 118 | 0.68306 | 4.786983 | false | false | false | false |
Appyx/AlexaHome | skill/src/main/kotlin/at/rgstoettner/alexahome/skill/endpoints/rest/v2/Control.kt | 1 | 1263 | package at.rgstoettner.alexahome.skill.endpoints.rest.v2
import at.rgstoettner.alexahome.skill.endpoints.websocket.ExecutorController
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
@Component
class Control {
private val logger = LoggerFactory.getLogger(this.javaClass)
private val mapper = ObjectMapper()
@Autowired
private lateinit var executor: ExecutorController
fun handleRequest(header: AmazonHeader, payload: JsonNode): String {
val message = executor.controlDevices(header.name, payload)
message.error?.let {
return getErrorResponse(header.namespace, it)
}
//null pointer exception is wanted if the name is null
val response = AmazonMessage(header.namespace, message.name!!, message.payload!!)
return mapper.writeValueAsString(response)
}
fun getErrorResponse(namespace: String, error: String): String {
val pl = mapper.nodeFactory.objectNode()
val response = AmazonMessage(namespace, error, pl)
return mapper.writeValueAsString(response)
}
} | apache-2.0 | 9e93997bf73803acc09dd59e148be38d | 36.176471 | 89 | 0.74901 | 4.559567 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/window/LookupUpAction.kt | 1 | 1349 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.action.window
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.VimActionHandler
/**
* @author Alex Plate
*/
class LookupUpAction : VimActionHandler.SingleExecution() {
private val keySet = setOf(injector.parser.parseKeys("<C-P>"))
override val type: Command.Type = Command.Type.OTHER_READONLY
override fun execute(
editor: VimEditor,
context: ExecutionContext,
cmd: Command,
operatorArguments: OperatorArguments,
): Boolean {
val activeLookup = injector.lookupManager.getActiveLookup(editor)
if (activeLookup != null) {
activeLookup.up(editor.primaryCaret(), context)
} else {
val keyStroke = keySet.first().first()
val actions = injector.keyGroup.getKeymapConflicts(keyStroke)
for (action in actions) {
if (injector.actionExecutor.executeAction(action, context)) break
}
}
return true
}
}
| mit | 8a09d6e4d4fec9a71699761a03569bd6 | 28.977778 | 73 | 0.733136 | 4.075529 | false | false | false | false |
NCBSinfo/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/fragments/ManageTransportFragment.kt | 2 | 5166 | package com.rohitsuratekar.NCBSinfo.fragments
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.rohitsuratekar.NCBSinfo.R
import com.rohitsuratekar.NCBSinfo.adapters.ManageTransportAdapter
import com.rohitsuratekar.NCBSinfo.common.Constants
import com.rohitsuratekar.NCBSinfo.models.MyFragment
import com.rohitsuratekar.NCBSinfo.models.Route
import com.rohitsuratekar.NCBSinfo.viewmodels.ManageTransportViewModel
import kotlinx.android.synthetic.main.fragment_manage_transport.*
import java.util.*
class ManageTransportFragment : MyFragment(), ManageTransportAdapter.OnOptionClicked {
private lateinit var viewModel: ManageTransportViewModel
private val routeList = mutableListOf<Route>()
private lateinit var adapter: ManageTransportAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_manage_transport, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(ManageTransportViewModel::class.java)
callback?.showProgress()
viewModel.getRouteList(repository)
adapter = ManageTransportAdapter(routeList, this)
mt_add_new_btn.setOnClickListener { callback?.navigate(Constants.NAVIGATE_EDIT_TRANSPORT) }
mt_recycler.adapter = adapter
mt_recycler.layoutManager = LinearLayoutManager(context)
mt_reset.setOnClickListener { resetRoutes() }
subscribe()
}
private fun subscribe() {
viewModel.routeList.observe(viewLifecycleOwner, Observer {
callback?.hideProgress()
routeList.clear()
routeList.addAll(it)
adapter.notifyDataSetChanged()
})
viewModel.routeDeleted.observe(viewLifecycleOwner, Observer {
callback?.hideProgress()
routeList.clear()
routeList.addAll(it)
adapter.notifyDataSetChanged()
sharedModel.changeCurrentRoute(it[0])
})
}
private fun resetRoutes() {
context?.let {
AlertDialog.Builder(it).setTitle(R.string.mt_reset_route_title)
.setMessage(R.string.mt_reset_route)
.setPositiveButton(
R.string.yes
) { d, _ ->
callback?.showProgress()
viewModel.resetRoutes(repository)
d.dismiss()
}
.setNegativeButton(R.string.cancel) { _, _ -> }.show()
}
}
override fun expand(route: Route) {
for (r in routeList) {
if (r == route) {
r.isExpanded = !r.isExpanded
} else {
r.isExpanded = false
}
}
adapter.notifyDataSetChanged()
}
override fun edit(route: Route) {
val arg =
ManageTransportFragmentDirections.actionManageTransportFragmentToEditTransport(route.routeData.routeID)
callback?.editRoute(arg)
}
override fun delete(route: Route) {
var message = getString(
R.string.mt_delete_confirm,
route.routeData.origin?.toUpperCase(Locale.getDefault()),
route.routeData.destination?.toUpperCase(Locale.getDefault()),
route.routeData.type
)
if (routeList.size == 1) {
message = getString(R.string.mt_single_route_error)
}
context?.let {
AlertDialog.Builder(it).setTitle(R.string.are_you_sure)
.setMessage(message)
.setPositiveButton(
R.string.delete
) { d, _ ->
callback?.showProgress()
viewModel.deleteRoute(repository, route)
d.dismiss()
}
.setNegativeButton(R.string.cancel) { _, _ -> }.show()
}
}
override fun report(route: Route) {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/html"
intent.putExtra(
Intent.EXTRA_EMAIL,
arrayOf("[email protected]", "[email protected]")
)
intent.putExtra(
Intent.EXTRA_SUBJECT, getString(
R.string.mt_route_feedback,
route.routeData.origin?.toUpperCase(Locale.getDefault()),
route.routeData.destination?.toUpperCase(Locale.getDefault()),
route.routeData.type
)
)
startActivity(Intent.createChooser(intent, "Send Email"))
}
}
| mit | c7a1511b35fcf243285cded01e4b499d | 34.9 | 115 | 0.611885 | 5.099704 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidWiki/src/main/kotlin/com/eden/orchid/wiki/menu/WikiPagesMenuItemType.kt | 2 | 2905 | package com.eden.orchid.wiki.menu
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.indexing.OrchidIndex
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.theme.menus.MenuItem
import com.eden.orchid.api.theme.menus.OrchidMenuFactory
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.wiki.model.WikiModel
import com.eden.orchid.wiki.model.WikiSection
@Description("Links to all pages in your wiki, optionally by section.", name = "Wiki Pages")
class WikiPagesMenuItemType : OrchidMenuFactory("wiki") {
@Option
@Description("The wiki section to include in this menu.")
lateinit var section: String
override fun getMenuItems(
context: OrchidContext,
page: OrchidPage
): List<MenuItem> {
val model: WikiModel = context.resolve(WikiModel::class.java)
val menuItems = ArrayList<MenuItem>()
val sections = HashMap<String?, WikiSection>()
val menuItemTitle: String
// multiple sections to choose from
if (model.sections.size > 1) {
// we're specifying a single section to show
if (section.isNotBlank()) {
val wikiSection = model.getSection(section)
if (wikiSection != null) {
sections.put(section, wikiSection)
menuItemTitle = wikiSection.title
} else {
menuItemTitle = "Wiki"
}
}
// did not specify a section, include them all
else {
sections.putAll(model.sections)
menuItemTitle = "Wiki"
}
}
// we only have the default section, so add it
else {
sections.putAll(model.sections)
menuItemTitle = "Wiki"
}
if (submenuTitle.isBlank()) {
submenuTitle = menuItemTitle
}
val wikiPagesIndex = OrchidIndex(null, "wiki")
for (value in sections.values) {
for (wikiPage in value.wikiPages) {
wikiPagesIndex.addToIndex(wikiPage.reference.path, wikiPage)
}
}
menuItems.add(
MenuItem.Builder(context)
.fromIndex(wikiPagesIndex)
.build()
)
for (item in menuItems) {
item.indexComparator = wikiMenuItemComparator
}
val innerItems = ArrayList<MenuItem>()
for (item in menuItems) {
if (item.isHasChildren) {
innerItems.addAll(item.children)
} else {
innerItems.add(item)
}
}
return if (model.sections.size > 1 && section.isNotBlank()) {
innerItems.first().children
} else {
innerItems
}
}
}
| mit | 9d4c09b16d5fc3d6131e19f86fec3f5f | 29.904255 | 92 | 0.585886 | 4.640575 | false | false | false | false |
icela/FriceEngine | src/org/frice/util/data/XMLPreference.kt | 1 | 2890 | package org.frice.util.data
import org.frice.util.*
import org.w3c.dom.Document
import org.w3c.dom.Element
import java.io.File
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
/**
* An Android-like XMLPreference.
*
* Created by ice1000 on 2016/8/15.
* @author ice1000
* @since 0.2.2
*/
class XMLPreference constructor(val file: File) : Database {
constructor(path: String) : this(File(path))
private val builder: DocumentBuilder = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
private val doc: Document
private val root: Element
companion object {
const val ROOT = "PREFERENCE_CONST_ROOT"
const val TYPE = "PREFERENCE_CONST_TYPE"
const val VALUE = "PREFERENCE_CONST_VALUE"
const val TYPE_BYTE = "PREFERENCE_CONST_TYPE_BYTE"
const val TYPE_INT = "PREFERENCE_CONST_TYPE_INT"
const val TYPE_LONG = "PREFERENCE_CONST_TYPE_LONG"
const val TYPE_SHORT = "PREFERENCE_CONST_TYPE_SHORT"
const val TYPE_DOUBLE = "PREFERENCE_CONST_TYPE_DOUBLE"
const val TYPE_FLOAT = "PREFERENCE_CONST_TYPE_FLOAT"
const val TYPE_STRING = "PREFERENCE_CONST_TYPE_STRING"
const val TYPE_CHAR = "PREFERENCE_CONST_TYPE_CHAR"
}
init {
if (file.exists()) {
doc = builder.parse(file)
root = doc.documentElement
} else {
file.createNewFile()
doc = builder.newDocument()
root = doc.createElement(ROOT)
doc.appendChild(root)
save()
}
}
private fun save() {
val transformer = TransformerFactory.newInstance().newTransformer()
transformer.transform(DOMSource(doc), StreamResult(file))
}
override fun insert(key: String, value: Any?) = value.let {
forceRun { loop { root.removeChild(doc.getElementsByTagName(key).item(0)) } }
val node = doc.createElement(key)
node.setAttribute(VALUE, value.toString())
node.setAttribute(TYPE, when (value) {
is Byte -> TYPE_BYTE
is Int -> TYPE_INT
is Long -> TYPE_LONG
is Short -> TYPE_SHORT
is Float -> TYPE_FLOAT
is Double -> TYPE_DOUBLE
is Char -> TYPE_CHAR
is String -> TYPE_STRING
else -> throw RuntimeException("invalid type $TYPE!")
})
root.appendChild(node)
save()
}
override fun query(key: String, default: Any?): Any? {
val node = doc.getElementsByTagName(key).item(0)
val value: String?
try {
value = node.attributes.getNamedItem(VALUE).nodeValue
} catch (e: Throwable) {
return default
}
return forceGet(default) {
when (node.attributes.getNamedItem(TYPE).nodeValue) {
TYPE_BYTE -> value.toByte()
TYPE_INT -> value.toInt()
TYPE_LONG -> value.toLong()
TYPE_SHORT -> value.toShort()
TYPE_CHAR -> value[0]
TYPE_FLOAT -> value.toFloat()
TYPE_DOUBLE -> value.toDouble()
TYPE_STRING -> value
else -> default
}
}
}
}
| agpl-3.0 | 61ed74a53cea2d823583725b1840d27f | 27.058252 | 79 | 0.704498 | 3.364377 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/main/kotlin/entities/AbstractInheritedAttributes.kt | 1 | 619 | package entities
import com.onyx.persistence.annotations.Attribute
import java.util.Date
/**
* Created by timothy.osborn on 11/4/14.
*/
open class AbstractInheritedAttributes : AbstractEntity() {
@Attribute
var longValue: Long? = null
@Attribute
var longPrimitive: Long = 0
@Attribute
var stringValue: String? = null
@Attribute
var dateValue: Date? = null
@Attribute
var doubleValue: Double? = null
@Attribute
var doublePrimitive: Double = 0.toDouble()
@Attribute
var booleanValue: Boolean? = null
@Attribute
var booleanPrimitive: Boolean = false
}
| agpl-3.0 | 63cf5640aa9cd26e160d0c7a548693ed | 21.107143 | 59 | 0.689822 | 4.210884 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/create/GHPRCreateComponentHolder.kt | 3 | 16854 | // 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.plugins.github.pullrequest.ui.toolwindow.create
import com.intellij.collaboration.async.CompletableFutureUtil.completionOnEdt
import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt
import git4idea.remote.hosting.knownRepositories
import com.intellij.collaboration.ui.SingleValueModel
import com.intellij.collaboration.ui.codereview.commits.CommitsBrowserComponentBuilder
import com.intellij.diff.chains.DiffRequestChain
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.ListSelection
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.EditorTabDiffPreviewManager.Companion.EDITOR_TAB_DIFF_PREVIEW
import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer
import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain
import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain.Producer
import com.intellij.openapi.vcs.changes.ui.ChangesTree
import com.intellij.openapi.vcs.history.VcsDiffUtil
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.OnePixelSplitter
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SideBorder
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.vcs.log.VcsCommitMetadata
import git4idea.changes.GitChangeUtils
import git4idea.history.GitCommitRequirements
import git4idea.history.GitLogUtil
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryChangeListener
import kotlinx.coroutines.flow.map
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.GHPRCombinedDiffPreviewBase.Companion.createAndSetupDiffPreview
import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings
import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContext
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import org.jetbrains.plugins.github.pullrequest.ui.*
import org.jetbrains.plugins.github.pullrequest.ui.changes.GHPRChangesTreeFactory
import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHPRDiffController
import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHPRToolWindowTabComponentController
import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.GHPRViewTabsFactory
import org.jetbrains.plugins.github.ui.util.DisableableDocument
import org.jetbrains.plugins.github.util.ChangeDiffRequestProducerFactory
import org.jetbrains.plugins.github.util.DiffRequestChainProducer
import org.jetbrains.plugins.github.util.GHGitRepositoryMapping
import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager
import java.util.concurrent.CompletableFuture
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.text.Document
import javax.swing.text.PlainDocument
internal class GHPRCreateComponentHolder(private val actionManager: ActionManager,
private val project: Project,
private val settings: GithubPullRequestsProjectUISettings,
private val repositoriesManager: GHHostedRepositoriesManager,
private val dataContext: GHPRDataContext,
private val viewController: GHPRToolWindowTabComponentController,
disposable: Disposable) {
private val repositoryDataService = dataContext.repositoryDataService
private val directionModel = GHPRMergeDirectionModelImpl(repositoryDataService.repositoryMapping, repositoriesManager)
private val titleDocument = PlainDocument()
private val descriptionDocument = DisableableDocument()
private val metadataModel = GHPRCreateMetadataModel(repositoryDataService, dataContext.securityService.currentUser)
private val commitSelectionModel = SingleValueModel<VcsCommitMetadata?>(null)
private val changesLoadingModel = GHIOExecutorLoadingModel<Collection<Change>>(disposable)
private val commitsLoadingModel = GHIOExecutorLoadingModel<List<VcsCommitMetadata>>(disposable)
private val commitChangesLoadingModel = GHIOExecutorLoadingModel<Collection<Change>>(disposable)
private val filesCountFlow = changesLoadingModel.getResultFlow().map { it?.size }
private val commitsCountFlow = commitsLoadingModel.getResultFlow().map { it?.size }
private val commitsCountModel = createCountModel(commitsLoadingModel)
private val existenceCheckLoadingModel = GHIOExecutorLoadingModel<GHPRIdentifier?>(disposable)
private val createLoadingModel = GHCompletableFutureLoadingModel<GHPullRequestShort>(disposable)
init {
directionModel.addAndInvokeDirectionChangesListener {
checkLoadChanges(true)
commitSelectionModel.value = null
}
commitSelectionModel.addAndInvokeListener {
checkLoadSelectedCommitChanges(true)
}
project.messageBus.connect(disposable).subscribe(GitRepository.GIT_REPO_CHANGE, GitRepositoryChangeListener { repository ->
if (repository == repositoryDataService.remoteCoordinates.repository) {
runInEdt {
checkLoadChanges(false)
checkLoadSelectedCommitChanges(false)
checkUpdateHead()
}
}
})
resetModel()
}
private fun checkLoadChanges(clear: Boolean) {
if (clear) {
changesLoadingModel.reset()
commitsLoadingModel.reset()
}
val baseBranch = directionModel.baseBranch
val headRepo = directionModel.headRepo
val headBranch = directionModel.headBranch
if (baseBranch == null || headRepo == null || headBranch == null) {
changesLoadingModel.reset()
commitsLoadingModel.reset()
return
}
val repository = headRepo.remote.repository
changesLoadingModel.load(EmptyProgressIndicator()) {
GitChangeUtils.getThreeDotDiff(repository, baseBranch.name, headBranch.name)
}
commitsLoadingModel.load(EmptyProgressIndicator()) {
GitLogUtil.collectMetadata(project, repository.root, "${baseBranch.name}..${headBranch.name}").commits
}
}
private fun checkLoadSelectedCommitChanges(clear: Boolean) {
val commit = commitSelectionModel.value
if (clear) commitChangesLoadingModel.reset()
if (commit != null)
commitChangesLoadingModel.load(EmptyProgressIndicator()) {
val changes = mutableListOf<Change>()
GitLogUtil.readFullDetailsForHashes(project, dataContext.repositoryDataService.remoteCoordinates.repository.root,
listOf(commit.id.asString()),
GitCommitRequirements.DEFAULT) { gitCommit -> changes.addAll(gitCommit.changes) }
changes
}
}
private fun checkUpdateHead() {
val headRepo = directionModel.headRepo
if (headRepo != null && !directionModel.headSetByUser) directionModel.setHead(headRepo,
headRepo.remote.repository.currentBranch)
}
private val changesLoadingErrorHandler = GHRetryLoadingErrorHandler {
checkLoadChanges(false)
}
private val commitsLoadingErrorHandler = GHRetryLoadingErrorHandler {
checkLoadChanges(false)
}
private val diffRequestProducer = NewPRDiffRequestChainProducer()
private val diffController = GHPRDiffController(dataContext.newPRDiffModel, diffRequestProducer)
private val uiDisposable = Disposer.newDisposable().also {
Disposer.register(disposable, it)
}
val component by lazy {
val infoComponent = GHPRCreateInfoComponentFactory(project, settings, dataContext, viewController)
.create(directionModel, titleDocument, descriptionDocument, metadataModel, commitsCountModel, existenceCheckLoadingModel,
createLoadingModel)
GHPRViewTabsFactory(project, viewController::viewList, uiDisposable)
.create(infoComponent, diffController,
createFilesComponent(), filesCountFlow, null,
createCommitsComponent(), commitsCountFlow).apply {
setDataProvider { dataId ->
if (DiffRequestChainProducer.DATA_KEY.`is`(dataId)) diffRequestProducer
else null
}
}.component
}
private fun createFilesComponent(): JComponent {
val panel = BorderLayoutPanel().withBackground(UIUtil.getListBackground())
val changesLoadingPanel = GHLoadingPanelFactory(changesLoadingModel,
GithubBundle.message("pull.request.create.select.branches"),
GithubBundle.message("cannot.load.changes"),
changesLoadingErrorHandler)
.withContentListener {
diffController.filesTree = UIUtil.findComponentOfType(it, ChangesTree::class.java)
}
.createWithUpdatesStripe(uiDisposable) { parent, model ->
createChangesTree(parent, model, GithubBundle.message("pull.request.does.not.contain.changes"))
}.apply {
border = IdeBorderFactory.createBorder(SideBorder.TOP)
}
val toolbar = GHPRChangesTreeFactory.createTreeToolbar(actionManager, changesLoadingPanel)
return panel.addToTop(toolbar).addToCenter(changesLoadingPanel)
}
private fun createCommitsComponent(): JComponent {
val splitter = OnePixelSplitter(true, "Github.PullRequest.Commits.Component", 0.4f).apply {
isOpaque = true
background = UIUtil.getListBackground()
}
val commitsLoadingPanel = GHLoadingPanelFactory(commitsLoadingModel,
GithubBundle.message("pull.request.create.select.branches"),
GithubBundle.message("cannot.load.commits"),
commitsLoadingErrorHandler)
.createWithUpdatesStripe(uiDisposable) { _, model ->
CommitsBrowserComponentBuilder(project, model)
.installPopupActions(DefaultActionGroup(actionManager.getAction("Github.PullRequest.Changes.Reload")), "GHPRCommitsPopup")
.setEmptyCommitListText(GithubBundle.message("pull.request.does.not.contain.commits"))
.onCommitSelected { commitSelectionModel.value = it }
.create()
}
val changesLoadingPanel = GHLoadingPanelFactory(commitChangesLoadingModel,
GithubBundle.message("pull.request.select.commit.to.view.changes"),
GithubBundle.message("cannot.load.changes"))
.withContentListener {
diffController.commitsTree = UIUtil.findComponentOfType(it, ChangesTree::class.java)
}
.createWithModel { parent, model ->
createChangesTree(parent, model, GithubBundle.message("pull.request.commit.does.not.contain.changes"))
}.apply {
border = IdeBorderFactory.createBorder(SideBorder.TOP)
}
val toolbar = GHPRChangesTreeFactory.createTreeToolbar(actionManager, changesLoadingPanel)
val changesBrowser = BorderLayoutPanel().andTransparent()
.addToTop(toolbar)
.addToCenter(changesLoadingPanel)
return splitter.apply {
firstComponent = commitsLoadingPanel
secondComponent = changesBrowser
}
}
private fun createChangesTree(parentPanel: JPanel,
model: SingleValueModel<Collection<Change>>,
emptyTextText: String): JComponent {
val tree = GHPRChangesTreeFactory(project, model).create(emptyTextText)
val diffPreviewHolder = createAndSetupDiffPreview(tree, diffRequestProducer.changeProducerFactory, null, dataContext.filesManager)
DataManager.registerDataProvider(parentPanel) { dataId ->
when {
EDITOR_TAB_DIFF_PREVIEW.`is`(dataId) -> diffPreviewHolder.activePreview
tree.isShowing -> tree.getData(dataId)
else -> null
}
}
return ScrollPaneFactory.createScrollPane(tree, true)
}
private fun createCountModel(loadingModel: GHSimpleLoadingModel<out Collection<*>>): SingleValueModel<Int?> {
val model = SingleValueModel<Int?>(null)
val loadingListener = object : GHLoadingModel.StateChangeListener {
override fun onLoadingCompleted() {
val items = if (loadingModel.resultAvailable) loadingModel.result!! else null
model.value = items?.size
}
}
loadingModel.addStateChangeListener(loadingListener)
loadingListener.onLoadingCompleted()
return model
}
fun resetModel() {
existenceCheckLoadingModel.reset()
createLoadingModel.future = null
commitSelectionModel.value = null
changesLoadingModel.reset()
commitsLoadingModel.reset()
commitChangesLoadingModel.reset()
metadataModel.assignees = emptyList()
metadataModel.reviewers = emptyList()
metadataModel.labels = emptyList()
descriptionDocument.clear()
descriptionDocument.loadContent(GithubBundle.message("pull.request.create.loading.template")) {
GHPRTemplateLoader.readTemplate(project)
}
titleDocument.clear()
directionModel.preFill()
}
private fun GHPRMergeDirectionModelImpl.preFill() {
val repositoryDataService = dataContext.repositoryDataService
val currentRemote = repositoryDataService.repositoryMapping.remote
val currentRepo = currentRemote.repository
val baseRepo = GHGitRepositoryMapping(repositoryDataService.repositoryCoordinates, currentRemote)
val branches = currentRepo.branches
val defaultBranchName = repositoryDataService.defaultBranchName
if (defaultBranchName != null) {
baseBranch = branches.findRemoteBranch("${currentRemote.remote.name}/$defaultBranchName")
}
else {
baseBranch = branches.findRemoteBranch("${currentRemote.remote.name}/master")
if (baseBranch == null) {
baseBranch = branches.findRemoteBranch("${currentRemote.remote.name}/main")
}
}
val repos = repositoriesManager.knownRepositories
val baseIsFork = repositoryDataService.isFork
val recentHead = settings.recentNewPullRequestHead
val headRepo = repos.find { it.repository == recentHead } ?: when {
repos.size == 1 -> repos.single()
baseIsFork -> baseRepo
else -> repos.find { it.remote.remote.name == "origin" }
}
val headBranch = headRepo?.remote?.repository?.currentBranch
setHead(headRepo, headBranch)
headSetByUser = false
}
private fun Document.clear() {
if (length > 0) {
remove(0, length)
}
}
private fun DisableableDocument.loadContent(@Nls loadingText: String, loader: () -> CompletableFuture<String?>) {
enabled = false
insertString(0, loadingText, null)
loader().successOnEdt {
if (!enabled) {
remove(0, length)
insertString(0, it, null)
}
}.completionOnEdt {
if (!enabled) enabled = true
}
}
private inner class NewPRDiffRequestChainProducer : DiffRequestChainProducer {
val changeProducerFactory = ChangeDiffRequestProducerFactory { project, change ->
val requestDataKeys = mutableMapOf<Key<out Any>, Any?>()
if (diffController.activeTree == GHPRDiffController.ActiveTree.FILES) {
val baseBranchName = directionModel.baseBranch?.name ?: "Base"
requestDataKeys[DiffUserDataKeysEx.VCS_DIFF_LEFT_CONTENT_TITLE] =
VcsDiffUtil.getRevisionTitle(baseBranchName, change.beforeRevision?.file, change.afterRevision?.file)
val headBranchName = directionModel.headBranch?.name ?: "Head"
requestDataKeys[DiffUserDataKeysEx.VCS_DIFF_RIGHT_CONTENT_TITLE] =
VcsDiffUtil.getRevisionTitle(headBranchName, change.afterRevision?.file, null)
}
else {
VcsDiffUtil.putFilePathsIntoChangeContext(change, requestDataKeys)
}
ChangeDiffRequestProducer.create(project, change, requestDataKeys)
}
override fun getRequestChain(changes: ListSelection<Change>): DiffRequestChain {
val producers = changes.map { change -> changeProducerFactory.create(project, change) as? Producer }
return ChangeDiffRequestChain(producers)
}
}
}
| apache-2.0 | 7d28bcbfc9b693e48df86e6019663496 | 44.064171 | 134 | 0.73395 | 5.166769 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddNamesToFollowingArgumentsIntention.kt | 1 | 3199 | // 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.k2.codeinsight.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.KotlinApplicableIntentionWithContext
import org.jetbrains.kotlin.idea.codeinsight.utils.dereferenceValidKeys
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddArgumentNamesUtils.addArgumentNames
import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddArgumentNamesUtils.associateArgumentNamesStartingAt
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtLambdaArgument
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
internal class AddNamesToFollowingArgumentsIntention :
KotlinApplicableIntentionWithContext<KtValueArgument, AddNamesToFollowingArgumentsIntention.Context>(KtValueArgument::class),
LowPriorityAction {
class Context(val argumentNames: Map<SmartPsiElementPointer<KtValueArgument>, Name>)
override fun getFamilyName(): String = KotlinBundle.message("add.names.to.this.argument.and.following.arguments")
override fun getActionName(element: KtValueArgument, context: Context): String = familyName
override fun getApplicabilityRange() = ApplicabilityRanges.VALUE_ARGUMENT_EXCLUDING_LAMBDA
override fun isApplicableByPsi(element: KtValueArgument): Boolean {
// Not applicable when lambda is trailing lambda after argument list (e.g., `run { }`); element is a KtLambdaArgument.
// May be applicable when lambda is inside an argument list (e.g., `run({ })`); element is a KtValueArgument in this case.
if (element.isNamed() || element is KtLambdaArgument) {
return false
}
val argumentList = element.parent as? KtValueArgumentList ?: return false
// Shadowed by `AddNamesToCallArgumentsIntention`
if (argumentList.arguments.firstOrNull() == element) return false
// Shadowed by `AddNameToArgumentIntention`
if (argumentList.arguments.lastOrNull { !it.isNamed() } == element) return false
return true
}
context(KtAnalysisSession)
override fun prepareContext(element: KtValueArgument): Context? {
val argumentList = element.parent as? KtValueArgumentList ?: return null
val call = argumentList.parent as? KtCallElement ?: return null
return associateArgumentNamesStartingAt(call, element)?.let { Context(it) }
}
override fun apply(element: KtValueArgument, context: Context, project: Project, editor: Editor?) =
addArgumentNames(context.argumentNames.dereferenceValidKeys())
} | apache-2.0 | cfccefe8d8e0582df889910f78807989 | 55.140351 | 158 | 0.786183 | 4.883969 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.