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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
siosio/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/common/ContextSimilarityFeatures.kt | 1 | 2452 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.ml.common
import com.intellij.codeInsight.completion.CompletionLocation
import com.intellij.codeInsight.completion.ml.ContextFeatures
import com.intellij.codeInsight.completion.ml.ElementFeatureProvider
import com.intellij.codeInsight.completion.ml.MLFeatureValue
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.util.Key
class ContextSimilarityFeatures : ElementFeatureProvider {
override fun getName(): String = "common_similarity"
override fun calculateFeatures(element: LookupElement,
location: CompletionLocation,
contextFeatures: ContextFeatures): MutableMap<String, MLFeatureValue> {
val features = mutableMapOf<String, MLFeatureValue>()
features.setSimilarityFeatures("line", ContextSimilarityUtil.LINE_SIMILARITY_SCORER_KEY, element.lookupString, contextFeatures)
features.setSimilarityFeatures("parent", ContextSimilarityUtil.PARENT_SIMILARITY_SCORER_KEY, element.lookupString, contextFeatures)
return features
}
private fun MutableMap<String, MLFeatureValue>.setSimilarityFeatures(baseName: String,
key: Key<ContextSimilarityUtil.ContextSimilarityScoringFunction>,
lookupString: String,
contextFeatures: ContextFeatures) {
val similarityScorer = contextFeatures.getUserData(key)
if (similarityScorer != null) {
val prefixSimilarity = similarityScorer.scorePrefixSimilarity(lookupString)
val stemmedSimilarity = similarityScorer.scoreStemmedSimilarity(lookupString)
addFeature("${baseName}_mean", prefixSimilarity.meanSimilarity())
addFeature("${baseName}_max", prefixSimilarity.maxSimilarity())
addFeature("${baseName}_full", prefixSimilarity.fullSimilarity())
addFeature("${baseName}_stemmed_mean", stemmedSimilarity.meanSimilarity())
addFeature("${baseName}_stemmed_max", stemmedSimilarity.maxSimilarity())
}
}
private fun MutableMap<String, MLFeatureValue>.addFeature(name: String, value: Double) {
if (value != 0.0) this[name] = MLFeatureValue.float(value)
}
} | apache-2.0 | 6cf0a79878f932f29aa01fbb0651ce5e | 57.404762 | 140 | 0.706362 | 5.261803 | false | false | false | false |
siosio/intellij-community | platform/execution-impl/src/com/intellij/openapi/editor/actions/TerminalChangeFontSizeAction.kt | 2 | 1578 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor.actions
import com.intellij.application.options.EditorFontsConstants
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.editor.EditorBundle
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.terminal.JBTerminalWidget
import java.util.function.Supplier
sealed class TerminalChangeFontSizeAction(text: Supplier<String?>, private val myStep: Int) : DumbAwareAction(text), LightEditCompatible {
override fun actionPerformed(e: AnActionEvent) {
val terminalWidget = getTerminalWidget(e)
if (terminalWidget != null) {
val newFontSize = terminalWidget.fontSize + myStep
if (newFontSize >= EditorFontsConstants.getMinEditorFontSize() && newFontSize <= EditorFontsConstants.getMaxEditorFontSize()) {
terminalWidget.fontSize = newFontSize
}
}
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = getTerminalWidget(e) != null
}
class IncreaseEditorFontSize : TerminalChangeFontSizeAction(EditorBundle.messagePointer("increase.editor.font"), 1)
class DecreaseEditorFontSize : TerminalChangeFontSizeAction(EditorBundle.messagePointer("decrease.editor.font"), -1)
companion object {
fun getTerminalWidget(e: AnActionEvent): JBTerminalWidget? {
return e.dataContext.getData(JBTerminalWidget.TERMINAL_DATA_KEY)
}
}
} | apache-2.0 | 3bc4cf11ed7143d344ce2cf96dfaf4f7 | 42.861111 | 140 | 0.786439 | 4.457627 | false | false | false | false |
zsmb13/MaterialDrawerKt | library/src/main/java/co/zsmb/materialdrawerkt/draweritems/profile/ProfileSettingDrawerItemKt.kt | 1 | 9115 | @file:Suppress("RedundantVisibilityModifier")
package co.zsmb.materialdrawerkt.draweritems.profile
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import co.zsmb.materialdrawerkt.builders.AccountHeaderBuilderKt
import co.zsmb.materialdrawerkt.draweritems.base.AbstractDrawerItemKt
import co.zsmb.materialdrawerkt.nonReadable
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.materialdrawer.holder.ColorHolder
import com.mikepenz.materialdrawer.holder.ImageHolder
import com.mikepenz.materialdrawer.holder.StringHolder
import com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem
/**
* Adds a new ProfileSettingDrawerItem with the given [name] and [description].
* @return The created ProfileSettingDrawerItem instance
*/
public fun AccountHeaderBuilderKt.profileSetting(
name: String = "",
description: String? = null,
setup: ProfileSettingDrawerItemKt.() -> Unit = {}): ProfileSettingDrawerItem {
val item = ProfileSettingDrawerItemKt()
item.name = name
description?.let { item.description = it }
item.setup()
return item.build().apply { addItem(this) }
}
/**
* Adds a new ProfileSettingDrawerItem with the given [nameRes] and [descriptionRes].
* @return The created ProfileSettingDrawerItem instance
*/
public fun AccountHeaderBuilderKt.profileSetting(
nameRes: Int,
descriptionRes: Int? = null,
setup: ProfileSettingDrawerItemKt.() -> Unit = {}): ProfileSettingDrawerItem {
val item = ProfileSettingDrawerItemKt()
item.nameRes = nameRes
descriptionRes?.let { item.descriptionRes = it }
item.setup()
return item.build().apply { addItem(this) }
}
public class ProfileSettingDrawerItemKt : AbstractDrawerItemKt<ProfileSettingDrawerItem>(ProfileSettingDrawerItem()) {
/**
* The description of the profile setting item.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.withDescription] method.
*/
public var description: String
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.withDescription(value)
}
/**
* The description of the profile setting item, as a String resource.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.withDescription] method.
*/
public var descriptionRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.withDescription(value)
}
/**
* The color of the profile setting item's description, as an argb Long.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.descriptionTextColor] property.
*/
public var descriptionTextColor: Long
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.descriptionTextColor = ColorHolder.fromColor(value.toInt())
}
/**
* The color of the profile setting item's description, as a color resource.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.descriptionTextColor] property.
*/
public var descriptionTextColorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.descriptionTextColor = ColorHolder.fromColorRes(value)
}
/**
* The description of the profile setting.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.withEmail] method.
*/
@Deprecated(level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("description"),
message = "Only here for discoverability. Use the description properties instead")
public var email: String
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.email = StringHolder(value)
}
/**
* The icon of the profile setting, as a drawable resource.
*
* Convenience for [iconRes]. Non-readable property. Wraps the [ProfileSettingDrawerItem.icon] property.
*/
public var icon: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.icon = ImageHolder(value)
}
/**
* The icon of the profile setting, as a Bitmap.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.icon] property.
*/
public var iconBitmap: Bitmap
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.icon = ImageHolder(value)
}
/**
* The color of the profile setting item's icon, as an argb Long.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.iconColor] property.
*/
public var iconColor: Long
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.iconColor = ColorHolder.fromColor(value.toInt())
}
/**
* The color of the profile setting item's icon, as a color resource.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.iconColor] property.
*/
public var iconColorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.iconColor = ColorHolder.fromColorRes(value)
}
/**
* The icon of the profile setting, as a Drawable.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.icon] property.
*/
public var iconDrawable: Drawable
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.icon = ImageHolder(value)
}
/**
* The icon of the profile setting, as a drawable resource.
*
* See [icon] as an alternative.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.icon] property.
*/
@Deprecated(level = DeprecationLevel.WARNING,
message = "Alternatives are available, check the documentation.")
public var iconRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.icon = ImageHolder(value)
}
/**
* The icon of the profile setting, as a Uri.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.icon] property.
*/
public var iconUri: Uri
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.icon = ImageHolder(value)
}
/**
* The icon of the profile setting, as a url String.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.icon] property.
*/
public var iconUrl: String
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.icon = ImageHolder(value)
}
/**
* The icon of the profile setting, as an IIcon.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.icon] property.
*/
public var iicon: IIcon
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.icon = ImageHolder(value)
}
/**
* Whether the icon of the profile setting item should be tinted with the enabled/disabled/selected color. If set to
* false, your icon will always be displayed with its default colors.
* Default value is false.
*
* Wraps the [ProfileSettingDrawerItem.isIconTinted] property.
*/
public var iconTinted: Boolean
get() = item.isIconTinted
set(value) {
item.isIconTinted = value
}
/**
* The name of the profile setting.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.name] property.
*/
public var name: CharSequence
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.name = StringHolder(value)
}
/**
* The name of the profile setting, as a String resource.
*
* Non-readable property. Wraps the [ProfileSettingDrawerItem.name] property.
*/
public var nameRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.")
get() = nonReadable()
set(value) {
item.name = StringHolder(value)
}
}
| apache-2.0 | a6a8e3510e52728b9ab4c05f410fa1f2 | 33.923372 | 120 | 0.650247 | 4.631606 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SelfAssignmentInspection.kt | 3 | 4107 | // 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
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
class SelfAssignmentInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return binaryExpressionVisitor(fun(expression) {
if (expression.operationToken != KtTokens.EQ) return
val left = expression.left
val leftRefExpr = left?.asNameReferenceExpression() ?: return
val right = expression.right
val rightRefExpr = right?.asNameReferenceExpression() ?: return
// To omit analyzing too much
if (leftRefExpr.text != rightRefExpr.text) return
val context = expression.analyze(BodyResolveMode.PARTIAL)
val leftResolvedCall = left.getResolvedCall(context)
val leftCallee = leftResolvedCall?.resultingDescriptor as? VariableDescriptor ?: return
val rightResolvedCall = right.getResolvedCall(context)
val rightCallee = rightResolvedCall?.resultingDescriptor as? VariableDescriptor ?: return
if (leftCallee != rightCallee) return
if (!rightCallee.isVar) return
if (rightCallee is PropertyDescriptor) {
if (rightCallee.isOverridable) return
if (rightCallee.accessors.any { !it.isDefault }) return
}
if (left.receiverDeclarationDescriptor(leftResolvedCall, context) != right.receiverDeclarationDescriptor(
rightResolvedCall,
context
)
) {
return
}
holder.registerProblem(
right,
KotlinBundle.message("variable.0.is.assigned.to.itself", rightCallee.name),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
RemoveSelfAssignmentFix()
)
})
}
private fun KtExpression.asNameReferenceExpression(): KtNameReferenceExpression? = when (this) {
is KtNameReferenceExpression ->
this
is KtDotQualifiedExpression ->
(selectorExpression as? KtNameReferenceExpression)?.takeIf { receiverExpression is KtThisExpression }
else ->
null
}
private fun KtExpression.receiverDeclarationDescriptor(
resolvedCall: ResolvedCall<out CallableDescriptor>,
context: BindingContext
): DeclarationDescriptor? {
val thisExpression = (this as? KtDotQualifiedExpression)?.receiverExpression as? KtThisExpression
if (thisExpression != null) {
return thisExpression.getResolvedCall(context)?.resultingDescriptor?.containingDeclaration
}
val implicitReceiver = with(resolvedCall) { dispatchReceiver ?: extensionReceiver } as? ImplicitReceiver
return implicitReceiver?.declarationDescriptor
}
}
private class RemoveSelfAssignmentFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.self.assignment.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val right = descriptor.psiElement as? KtExpression ?: return
right.parent.delete()
}
}
| apache-2.0 | ea7c43095a321c9cd8be2ec0b8fda79b | 44.131868 | 158 | 0.699294 | 5.657025 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/State.kt | 1 | 10341 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet", "ReplaceGetOrSet")
package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement
import com.github.benmanes.caffeine.cache.Caffeine
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.advertiser.PluginData
import com.intellij.ide.plugins.advertiser.PluginFeatureCacheService
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.fileTypes.FileNameMatcher
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeFactory
import com.intellij.openapi.fileTypes.PlainTextLikeFileType
import com.intellij.openapi.fileTypes.ex.FakeFileType
import com.intellij.openapi.fileTypes.impl.DetectedByContentFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.Strings
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence
import com.intellij.util.containers.mapSmartSet
import kotlinx.serialization.Serializable
import org.jetbrains.annotations.VisibleForTesting
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
data class PluginAdvertiserExtensionsData(
// Either extension or file name. Depends on which of the two properties has more priority for advertising plugins for this specific file.
val extensionOrFileName: String,
val plugins: Set<PluginData> = emptySet(),
)
@State(name = "PluginAdvertiserExtensions", storages = [Storage(StoragePathMacros.CACHE_FILE)])
@Service(Service.Level.APP)
class PluginAdvertiserExtensionsStateService : SerializablePersistentStateComponent<PluginAdvertiserExtensionsStateService.State>(
State()
) {
private val tracker = SimpleModificationTracker()
/**
* Stores locally installed plugins (both enabled and disabled) supporting given filenames/extensions.
*/
@Serializable
data class State(val plugins: MutableMap<String, PluginData> = HashMap())
override fun getStateModificationCount() = tracker.modificationCount
companion object {
private val LOG = logger<PluginAdvertiserExtensionsStateService>()
@JvmStatic
val instance
get() = service<PluginAdvertiserExtensionsStateService>()
@JvmStatic
fun getFullExtension(fileName: String): String? = Strings.toLowerCase(
FileUtilRt.getExtension(fileName)).takeIf { it.isNotEmpty() }?.let { "*.$it" }
@RequiresBackgroundThread
@RequiresReadLockAbsence
private fun requestCompatiblePlugins(
extensionOrFileName: String,
dataSet: Set<PluginData>,
): Set<PluginData> {
if (dataSet.isEmpty()) {
LOG.debug("No features for extension $extensionOrFileName")
return emptySet()
}
val pluginIdsFromMarketplace = MarketplaceRequests
.getLastCompatiblePluginUpdate(dataSet.mapSmartSet { it.pluginId })
.map { it.pluginId }
.toSet()
val plugins = dataSet
.asSequence()
.filter {
it.isFromCustomRepository
|| it.isBundled
|| pluginIdsFromMarketplace.contains(it.pluginIdString)
}.toSet()
LOG.debug {
if (plugins.isEmpty())
"No plugins for extension $extensionOrFileName"
else
"Found following plugins for '${extensionOrFileName}': ${plugins.joinToString { it.pluginIdString }}"
}
return plugins
}
@Suppress("HardCodedStringLiteral")
private fun createUnknownExtensionFeature(extensionOrFileName: String) = UnknownFeature(
FileTypeFactory.FILE_TYPE_FACTORY_EP.name,
"File Type",
extensionOrFileName,
extensionOrFileName,
)
private fun findEnabledPlugin(plugins: Set<String>): IdeaPluginDescriptor? {
return if (plugins.isNotEmpty())
PluginManagerCore.getLoadedPlugins().find {
it.isEnabled && plugins.contains(it.pluginId.idString)
}
else
null
}
}
// Stores the marketplace plugins that support given filenames/extensions and are known to be compatible with
// the current IDE build.
private val cache = Caffeine
.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.build<String, PluginAdvertiserExtensionsData>()
fun createExtensionDataProvider(project: Project) = ExtensionDataProvider(project)
fun registerLocalPlugin(matcher: FileNameMatcher, descriptor: PluginDescriptor) {
state.plugins.put(matcher.presentableString, PluginData(descriptor))
// no need to waste time to check that map is really changed - registerLocalPlugin is not called often after start-up,
// so, mod count will be not incremented too often
tracker.incModificationCount()
}
@RequiresBackgroundThread
@RequiresReadLockAbsence
fun updateCache(extensionOrFileName: String): Boolean {
if (cache.getIfPresent(extensionOrFileName) != null) {
return false
}
val knownExtensions = PluginFeatureCacheService.getInstance().extensions
if (knownExtensions == null) {
LOG.debug("No known extensions loaded")
return false
}
val compatiblePlugins = requestCompatiblePlugins(extensionOrFileName, knownExtensions.get(extensionOrFileName))
updateCache(extensionOrFileName, compatiblePlugins)
return true
}
@VisibleForTesting
fun updateCache(extensionOrFileName: String, compatiblePlugins: Set<PluginData>) {
cache.put(extensionOrFileName, PluginAdvertiserExtensionsData(extensionOrFileName, compatiblePlugins))
}
inner class ExtensionDataProvider(private val project: Project) {
private val unknownFeaturesCollector get() = UnknownFeaturesCollector.getInstance(project)
private val enabledExtensionOrFileNames = Collections.newSetFromMap<String>(ConcurrentHashMap())
fun ignoreExtensionOrFileNameAndInvalidateCache(extensionOrFileName: String) {
unknownFeaturesCollector.ignoreFeature(createUnknownExtensionFeature(extensionOrFileName))
cache.invalidate(extensionOrFileName)
}
fun addEnabledExtensionOrFileNameAndInvalidateCache(extensionOrFileName: String) {
enabledExtensionOrFileNames.add(extensionOrFileName)
cache.invalidate(extensionOrFileName)
}
private fun getByFilenameOrExt(fileNameOrExtension: String): PluginAdvertiserExtensionsData? {
return state.plugins[fileNameOrExtension]?.let {
PluginAdvertiserExtensionsData(fileNameOrExtension, setOf(it))
}
}
/**
* Returns the list of plugins supporting a file with the specified name and file type.
* The list includes both locally installed plugins (enabled and disabled) and plugins that can be installed
* from the marketplace (if none of the installed plugins handle the given filename or extension).
*
* The return value of null indicates that the locally available data is not enough to produce a suggestion,
* and we need to fetch up-to-date data from the marketplace.
*/
fun requestExtensionData(fileName: String, fileType: FileType): PluginAdvertiserExtensionsData? {
fun noSuggestions() = PluginAdvertiserExtensionsData(fileName, emptySet())
val fullExtension = getFullExtension(fileName)
if (fullExtension != null && isIgnored(fullExtension)) {
LOG.debug("Extension '$fullExtension' is ignored in project '${project.name}'")
return noSuggestions()
}
if (isIgnored(fileName)) {
LOG.debug("File '$fileName' is ignored in project '${project.name}'")
return noSuggestions()
}
if (fullExtension == null && fileType is FakeFileType) {
return noSuggestions()
}
// Check if there's an installed plugin matching the exact file name
getByFilenameOrExt(fileName)?.let {
return it
}
val knownExtensions = PluginFeatureCacheService.getInstance().extensions
if (knownExtensions == null) {
LOG.debug("No known extensions loaded")
return null
}
val plugin = findEnabledPlugin(knownExtensions.get(fileName).mapTo(HashSet()) { it.pluginIdString })
if (plugin != null) {
// Plugin supporting the exact file name is installed and enabled, no advertiser is needed
return noSuggestions()
}
val pluginsForExactFileName = cache.getIfPresent(fileName)
if (pluginsForExactFileName != null && pluginsForExactFileName.plugins.isNotEmpty()) {
return pluginsForExactFileName
}
if (knownExtensions.get(fileName).isNotEmpty()) {
// there is a plugin that can support the exact file name, but we don't know a compatible version,
// return null to force request to update cache
return null
}
// Check if there's an installed plugin matching the extension
fullExtension?.let { getByFilenameOrExt(it) }?.let {
return it
}
if (fileType is PlainTextLikeFileType || fileType is DetectedByContentFileType) {
if (fullExtension != null) {
val knownCompatiblePlugins = cache.getIfPresent(fullExtension)
if (knownCompatiblePlugins != null) {
return knownCompatiblePlugins
}
if (knownExtensions.get(fullExtension).isNotEmpty()) {
// there is a plugin that can support the file type, but we don't know a compatible version,
// return null to force request to update cache
return null
}
}
// no extension and no plugins matching the exact name
return noSuggestions()
}
return null
}
private fun isIgnored(extensionOrFileName: String): Boolean {
return enabledExtensionOrFileNames.contains(extensionOrFileName)
|| unknownFeaturesCollector.isIgnored(createUnknownExtensionFeature(extensionOrFileName))
}
}
}
| apache-2.0 | 6c72228eb6ffec7f70a9dcc982406b8c | 38.319392 | 140 | 0.736099 | 5.162756 | false | false | false | false |
allotria/intellij-community | java/java-tests/testSrc/com/intellij/util/indexing/CountingFileBasedIndexExtension.kt | 2 | 1126 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.EnumeratorIntegerDescriptor
import com.intellij.util.io.KeyDescriptor
import java.util.concurrent.atomic.AtomicInteger
class CountingFileBasedIndexExtension : ScalarIndexExtension<Int>() {
override fun getIndexer(): DataIndexer<Int, Void, FileContent> {
return DataIndexer {
COUNTER.incrementAndGet()
mapOf(1 to null)
}
}
override fun getName(): ID<Int, Void> = INDEX_ID
override fun getKeyDescriptor(): KeyDescriptor<Int> = EnumeratorIntegerDescriptor.INSTANCE
override fun getVersion(): Int = 0
override fun getInputFilter(): FileBasedIndex.InputFilter = FileBasedIndex.InputFilter { f: VirtualFile -> f.name.contains("Foo") }
override fun dependsOnFileContent(): Boolean = true
companion object {
@JvmStatic
val INDEX_ID = ID.create<Int, Void>("counting.file.based.index")
@JvmStatic
val COUNTER = AtomicInteger()
}
} | apache-2.0 | 67ba3b47d283477909c439082d3823dc | 37.862069 | 140 | 0.754885 | 4.398438 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertTextJavaCopyPasteProcessor.kt | 1 | 14533 | // 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.conversion.copy
import com.intellij.codeInsight.editorActions.CopyPastePostProcessor
import com.intellij.codeInsight.editorActions.TextBlockTransferable
import com.intellij.codeInsight.editorActions.TextBlockTransferableData
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import com.intellij.refactoring.suggested.range
import com.intellij.util.LocalTimeCounter
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.editor.KotlinEditorOptions
import org.jetbrains.kotlin.idea.statistics.ConversionType
import org.jetbrains.kotlin.idea.statistics.J2KFusCollector
import org.jetbrains.kotlin.j2k.J2kConverterExtension
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
import kotlin.system.measureTimeMillis
class ConvertTextJavaCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransferableData>() {
private val LOG = Logger.getInstance(ConvertTextJavaCopyPasteProcessor::class.java)
private val javaContextDeclarationRenderer = JavaContextDeclarationRenderer()
private class MyTransferableData(val text: String) : TextBlockTransferableData {
override fun getFlavor() = DATA_FLAVOR
companion object {
val DATA_FLAVOR: DataFlavor =
DataFlavor(ConvertTextJavaCopyPasteProcessor::class.java, "class: ConvertTextJavaCopyPasteProcessor")
}
}
override fun collectTransferableData(
file: PsiFile,
editor: Editor,
startOffsets: IntArray,
endOffsets: IntArray
): List<TextBlockTransferableData> {
if (file is KtFile) return listOf(CopiedKotlinCode(file.text, startOffsets, endOffsets))
return emptyList()
}
override fun extractTransferableData(content: Transferable): List<TextBlockTransferableData> {
try {
if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) {
if (content.isDataFlavorSupported(CopiedKotlinCode.DATA_FLAVOR) ||
/* Handled by ConvertJavaCopyPasteProcessor */
content.isDataFlavorSupported(CopiedJavaCode.DATA_FLAVOR)
) return emptyList()
val text = content.getTransferData(DataFlavor.stringFlavor) as String
return listOf(MyTransferableData(text))
}
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
LOG.error(e)
}
return emptyList()
}
override fun processTransferableData(
project: Project,
editor: Editor,
bounds: RangeMarker,
caretOffset: Int,
indented: Ref<in Boolean>,
values: List<TextBlockTransferableData>
) {
if (DumbService.getInstance(project).isDumb) return
if (!KotlinEditorOptions.getInstance().isEnableJavaToKotlinConversion) return //TODO: use another option?
val text = TextBlockTransferable.convertLineSeparators(editor, (values.single() as MyTransferableData).text, values)
val psiDocumentManager = PsiDocumentManager.getInstance(project)
val targetFile = psiDocumentManager.getPsiFile(editor.document).safeAs<KtFile>()?.takeIf { it.virtualFile.isWritable } ?: return
psiDocumentManager.commitDocument(editor.document)
val useNewJ2k = checkUseNewJ2k(targetFile)
val targetModule = targetFile.module
val pasteTarget = detectPasteTarget(targetFile, bounds.startOffset, bounds.endOffset) ?: return
val conversionContext = detectConversionContext(pasteTarget.pasteContext, text, project) ?: return
if (!confirmConvertJavaOnPaste(project, isPlainText = true)) return
val copiedJavaCode = prepareCopiedJavaCodeByContext(text, conversionContext, pasteTarget)
val dataForConversion = DataForConversion.prepare(copiedJavaCode, project)
fun convert() {
val additionalImports = dataForConversion.tryResolveImports(targetFile)
ProgressManager.checkCanceled()
var convertedImportsText = additionalImports.convertCodeToKotlin(project, targetModule, useNewJ2k).text
val convertedResult = dataForConversion.convertCodeToKotlin(project, targetModule, useNewJ2k)
val convertedText = convertedResult.text
ProgressManager.checkCanceled()
val newBounds = runWriteAction {
val importsInsertOffset = targetFile.importList?.endOffset ?: 0
if (targetFile.importDirectives.isEmpty() && importsInsertOffset > 0)
convertedImportsText = "\n" + convertedImportsText
if (convertedImportsText.isNotBlank())
editor.document.insertString(importsInsertOffset, convertedImportsText)
val startOffset = bounds.startOffset
editor.document.replaceString(startOffset, bounds.endOffset, convertedText)
val endOffsetAfterCopy = startOffset + convertedText.length
editor.caretModel.moveToOffset(endOffsetAfterCopy)
editor.document.createRangeMarker(startOffset, startOffset + convertedText.length)
}
psiDocumentManager.commitAllDocuments()
ProgressManager.checkCanceled()
if (useNewJ2k) {
val postProcessor = J2kConverterExtension.extension(useNewJ2k = true).createPostProcessor(formatCode = true)
convertedResult.importsToAdd.forEach { fqName ->
postProcessor.insertImport(targetFile, fqName)
}
}
runPostProcessing(project, targetFile, newBounds.range, convertedResult.converterContext, useNewJ2k)
conversionPerformed = true
}
val conversionTime = measureTimeMillis { convert() }
J2KFusCollector.log(
ConversionType.TEXT_EXPRESSION,
checkUseNewJ2k(targetFile),
conversionTime,
dataForConversion.elementsAndTexts.linesCount(),
filesCount = 1
)
}
private fun DataForConversion.convertCodeToKotlin(project: Project, targetModule: Module?, useNewJ2k: Boolean): ConversionResult {
return elementsAndTexts.convertCodeToKotlin(project, targetModule, useNewJ2k)
}
private val KtElement.pasteContext: KotlinContext
get() = when (this) {
is KtFile -> KotlinContext.TOP_LEVEL
is KtClassBody -> KotlinContext.CLASS_BODY
is KtBlockExpression -> KotlinContext.IN_BLOCK
else -> KotlinContext.EXPRESSION
}
private fun detectPasteTarget(file: KtFile, startOffset: Int, endOffset: Int): KtElement? {
if (isNoConversionPosition(file, startOffset)) return null
val fileText = file.text
val dummyDeclarationText = "fun dummy(){}"
val newFileText = "${fileText.substring(0, startOffset)} $dummyDeclarationText\n${fileText.substring(endOffset)}"
val newFile = parseAsFile(newFileText, KotlinFileType.INSTANCE, file.project)
(newFile as KtFile).analysisContext = file
val funKeyword = newFile.findElementAt(startOffset + 1) ?: return null
if (funKeyword.node.elementType != KtTokens.FUN_KEYWORD) return null
val declaration = funKeyword.parent as? KtFunction ?: return null
return declaration.parent as? KtElement
}
private fun detectConversionContext(pasteContext: KotlinContext, text: String, project: Project): JavaContext? {
if (isParsedAsKotlinCode(text, pasteContext, project)) return null
fun JavaContext.check(): JavaContext? =
takeIf { isParsedAsJavaCode(text, it, project) }
when (pasteContext) {
KotlinContext.TOP_LEVEL -> {
JavaContext.TOP_LEVEL.check()?.let { return it }
JavaContext.CLASS_BODY.check()?.let { return it }
return null
}
KotlinContext.CLASS_BODY -> return JavaContext.CLASS_BODY.check()
KotlinContext.IN_BLOCK -> return JavaContext.IN_BLOCK.check()
KotlinContext.EXPRESSION -> return JavaContext.EXPRESSION.check()
}
}
private enum class KotlinContext {
TOP_LEVEL, CLASS_BODY, IN_BLOCK, EXPRESSION
}
private enum class JavaContext {
TOP_LEVEL, CLASS_BODY, IN_BLOCK, EXPRESSION
}
private fun isParsedAsJavaCode(text: String, context: JavaContext, project: Project): Boolean {
return when (context) {
JavaContext.TOP_LEVEL -> isParsedAsJavaFile(text, project)
JavaContext.CLASS_BODY -> isParsedAsJavaFile("class Dummy { $text\n}", project)
JavaContext.IN_BLOCK -> isParsedAsJavaFile("class Dummy { void foo() {$text\n}\n}", project)
JavaContext.EXPRESSION -> isParsedAsJavaFile("class Dummy { Object field = $text; }", project)
}
}
private fun isParsedAsKotlinCode(text: String, context: KotlinContext, project: Project): Boolean {
return when (context) {
KotlinContext.TOP_LEVEL -> isParsedAsKotlinFile(text, project)
KotlinContext.CLASS_BODY -> isParsedAsKotlinFile("class Dummy { $text\n}", project)
KotlinContext.IN_BLOCK -> isParsedAsKotlinFile("fun foo() {$text\n}", project)
KotlinContext.EXPRESSION -> isParsedAsKotlinFile("val v = $text", project)
}
}
private fun isParsedAsJavaFile(text: String, project: Project) = isParsedAsFile(text, JavaFileType.INSTANCE, project)
private fun isParsedAsKotlinFile(text: String, project: Project) = isParsedAsFile(text, KotlinFileType.INSTANCE, project)
private fun isParsedAsFile(text: String, fileType: LanguageFileType, project: Project): Boolean {
val psiFile = parseAsFile(text, fileType, project)
return !psiFile.anyDescendantOfType<PsiErrorElement>()
}
private fun parseAsFile(text: String, fileType: LanguageFileType, project: Project): PsiFile {
return PsiFileFactory.getInstance(project)
.createFileFromText("Dummy." + fileType.defaultExtension, fileType, text, LocalTimeCounter.currentTime(), true)
}
private fun DataForConversion.tryResolveImports(targetFile: KtFile): ElementAndTextList {
val importResolver = PlainTextPasteImportResolver(this, targetFile)
importResolver.addImportsFromTargetFile()
importResolver.tryResolveReferences()
return ElementAndTextList(importResolver.addedImports.flatMap { importStatement ->
listOf("\n", importStatement)
} + "\n\n") //TODO Non-manual formatting for import list
}
private fun prepareCopiedJavaCodeByContext(text: String, context: JavaContext, target: KtElement): CopiedJavaCode {
val targetFile = target.containingFile as KtFile
val (localDeclarations, memberDeclarations) = javaContextDeclarationRenderer.render(target)
val prefix = buildString {
targetFile.packageDirective?.let {
if (it.text.isNotEmpty()) {
append(it.text)
append(";\n")
}
}
}
val classDef = when (context) {
JavaContext.TOP_LEVEL -> ""
JavaContext.CLASS_BODY, JavaContext.IN_BLOCK, JavaContext.EXPRESSION -> {
val lightClass = target.getParentOfType<KtClass>(false)?.toLightClass()
buildString {
append("class ")
append(lightClass?.name ?: "Dummy")
lightClass?.extendsListTypes?.ifNotEmpty {
joinTo(
this@buildString,
prefix = " extends "
) { it.getCanonicalText(true) }
}
lightClass?.implementsListTypes?.ifNotEmpty {
joinTo(this@buildString, prefix = " implements ") {
it.getCanonicalText(
true
)
}
}
}
}
}
return when (context) {
JavaContext.TOP_LEVEL -> createCopiedJavaCode(prefix, "$", text)
JavaContext.CLASS_BODY -> createCopiedJavaCode(prefix, "$classDef {\n$memberDeclarations $\n}", text)
JavaContext.IN_BLOCK ->
createCopiedJavaCode(prefix, "$classDef {\n$memberDeclarations void foo() {\n$localDeclarations $\n}\n}", text)
JavaContext.EXPRESSION -> createCopiedJavaCode(prefix, "$classDef {\nObject field = $\n}", text)
}
}
private fun createCopiedJavaCode(prefix: String, templateWithoutPrefix: String, text: String): CopiedJavaCode {
val template = "$prefix$templateWithoutPrefix"
val index = template.indexOf("$")
assert(index >= 0)
val fileText = template.substring(0, index) + text + template.substring(index + 1)
return CopiedJavaCode(fileText, intArrayOf(index), intArrayOf(index + text.length))
}
companion object {
@get:TestOnly
var conversionPerformed: Boolean = false
}
}
| apache-2.0 | 6b6b7dfdf8b4a9b1752638ebe8d0bd16 | 43.716923 | 158 | 0.680245 | 5.083246 | false | false | false | false |
androidx/androidx | paging/paging-common/src/test/kotlin/androidx/paging/TestPagingSourceExt.kt | 3 | 2569 | /*
* 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.paging
import androidx.paging.LoadState.NotLoading
import androidx.paging.TestPagingSource.Companion.ITEMS
internal fun createRefresh(
range: IntRange,
combinedLoadStates: CombinedLoadStates
) = PageEvent.Insert.Refresh(
pages = pages(0, range),
placeholdersBefore = range.first.coerceAtLeast(0),
placeholdersAfter = (ITEMS.size - range.last - 1).coerceAtLeast(0),
sourceLoadStates = combinedLoadStates.source,
mediatorLoadStates = combinedLoadStates.mediator,
)
internal fun createRefresh(
range: IntRange,
startState: LoadState = NotLoading.Incomplete,
endState: LoadState = NotLoading.Incomplete
) = PageEvent.Insert.Refresh(
pages = pages(0, range),
placeholdersBefore = range.first.coerceAtLeast(0),
placeholdersAfter = (ITEMS.size - range.last - 1).coerceAtLeast(0),
sourceLoadStates = loadStates(prepend = startState, append = endState),
mediatorLoadStates = null,
)
internal fun createPrepend(
pageOffset: Int,
range: IntRange,
startState: LoadState = NotLoading.Incomplete,
endState: LoadState = NotLoading.Incomplete
) = PageEvent.Insert.Prepend(
pages = pages(pageOffset, range),
placeholdersBefore = range.first.coerceAtLeast(0),
sourceLoadStates = loadStates(prepend = startState, append = endState),
mediatorLoadStates = null,
)
internal fun createAppend(
pageOffset: Int,
range: IntRange,
startState: LoadState = NotLoading.Incomplete,
endState: LoadState = NotLoading.Incomplete
) = PageEvent.Insert.Append(
pages = pages(pageOffset, range),
placeholdersAfter = (ITEMS.size - range.last - 1).coerceAtLeast(0),
sourceLoadStates = loadStates(prepend = startState, append = endState),
mediatorLoadStates = null,
)
private fun pages(
pageOffset: Int,
range: IntRange
) = listOf(
TransformablePage(
originalPageOffset = pageOffset,
data = ITEMS.slice(range)
)
)
| apache-2.0 | 13e8d3deb08268de3649f0be78885987 | 32.363636 | 75 | 0.731802 | 4.274542 | false | false | false | false |
androidx/androidx | camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/CameraDevices.kt | 3 | 3784 | /*
* 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.
*/
@file:Suppress("NOTHING_TO_INLINE")
@file:RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
package androidx.camera.camera2.pipe
import androidx.annotation.RequiresApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
/**
* Methods for querying, iterating, and selecting the Cameras that are available on the device.
*/
public interface CameraDevices {
/**
* Iterate and return a list of CameraId's on the device that are capable of being opened. Some
* camera devices may be hidden or un-openable if they are included as part of a logical camera
* group.
*/
@Deprecated(
message = "findAll may block the calling thread and is deprecated.",
replaceWith = ReplaceWith("ids"),
level = DeprecationLevel.WARNING
)
public fun findAll(): List<CameraId>
/**
* Load the list of CameraIds from the Camera2 CameraManager, suspending if the list of
* CameraIds has not yet been loaded.
*/
public suspend fun ids(): List<CameraId>
/**
* Load CameraMetadata for a specific CameraId. Loading CameraMetadata can take a
* non-zero amount of time to execute. If CameraMetadata is not already cached this function
* will suspend until CameraMetadata can be loaded.
*/
public suspend fun getMetadata(camera: CameraId): CameraMetadata
/**
* Load CameraMetadata for a specific CameraId and block the calling thread until the result is
* available.
*/
public fun awaitMetadata(camera: CameraId): CameraMetadata
}
@JvmInline
public value class CameraId(public val value: String) {
public companion object {
public inline fun fromCamera2Id(value: String): CameraId = CameraId(value)
public inline fun fromCamera1Id(value: Int): CameraId = CameraId("$value")
}
/**
* Attempt to parse an camera1 id from a camera2 id.
*
* @return The parsed Camera1 id, or null if the value cannot be parsed as a Camera1 id.
*/
public inline fun toCamera1Id(): Int? = value.toIntOrNull()
public override fun toString(): String = "Camera $value"
}
/**
* Produce a [Flow]<[CameraMetadata]>, optionally expanding the list to include the physical
* metadata of cameras that are otherwise hidden. Metadata for hidden cameras are always returned
* last.
*/
public fun CameraDevices.find(includeHidden: Boolean = false): Flow<CameraMetadata> =
flow {
val cameras = [email protected]()
val visited = mutableSetOf<CameraId>()
for (id in cameras) {
if (visited.add(id)) {
val metadata = [email protected](id)
emit(metadata)
}
}
if (includeHidden) {
for (id in cameras) {
val metadata = [email protected](id)
for (physicalId in metadata.physicalCameraIds) {
if (visited.add(physicalId)) {
val physicalMetadata = [email protected](id)
emit(physicalMetadata)
}
}
}
}
}
| apache-2.0 | 9cfd90373851ba5c57497a20fa75969e | 34.364486 | 99 | 0.664112 | 4.586667 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/testData/stepping/custom/smartStepIntoSamLambdaFromKotlinFunInterface.kt | 4 | 894 | package smartStepIntoSamLambdaFromKotlinFunInterface
fun interface I {
fun f()
}
fun Any.acceptLambda(f: () -> Unit): Any {
f()
return this
}
fun Any.acceptI(i: I): Any {
i.f()
return this
}
fun foo1() = 1
fun foo2() = 2
fun foo3() = 3
fun main() {
// STEP_OVER: 1
//Breakpoint!
val pos1 = 1
// SMART_STEP_INTO_BY_INDEX: 3
// STEP_INTO: 1
// RESUME: 1
Any().acceptI { foo1() } .acceptLambda { foo2() }.acceptI { foo3() }
// STEP_OVER: 1
//Breakpoint!
val pos2 = 2
// SMART_STEP_INTO_BY_INDEX: 5
// STEP_INTO: 1
// RESUME: 1
Any().acceptI { foo1() } .acceptLambda { foo2() }.acceptI { foo3() }
// STEP_OVER: 1
//Breakpoint!
val pos3 = 3
// SMART_STEP_INTO_BY_INDEX: 7
// STEP_INTO: 1
// RESUME: 1
Any().acceptI { foo1() } .acceptLambda { foo2() }.acceptI { foo3() }
}
// IGNORE_K2 | apache-2.0 | 894163db5fb71e8fef3258cf5b588261 | 16.9 | 72 | 0.54698 | 3.040816 | false | false | false | false |
GunoH/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyMultipleArgumentsCompletionContributor.kt | 3 | 5797 | package com.jetbrains.python.codeInsight.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.completion.util.ParenthesesInsertHandler
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.Key
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.ui.IconManager
import com.intellij.util.ProcessingContext
import com.intellij.util.containers.ContainerUtil
import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.extensions.inArgumentList
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.types.PyCallableParameter
class PyMultipleArgumentsCompletionContributor: CompletionContributor(), DumbAware {
init {
extend(CompletionType.BASIC, PlatformPatterns.psiElement().inArgumentList(), MyCompletionProvider)
}
private object MyCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val position = parameters.position
val argumentExplicitIndex = getArgumentIndex(position) ?: return
val call = PsiTreeUtil.getParentOfType(position, PyCallExpression::class.java) ?: return
val typeEvalContext = parameters.getTypeEvalContext()
val resolveContext = PyResolveContext.defaultContext(typeEvalContext)
val callableTypes = call.multiResolveCallee(resolveContext)
if (callableTypes.isEmpty()) return
val scopeOwner = ScopeUtil.getScopeOwner(position) ?: return
val names = collectNames(scopeOwner, position)
callableTypes.forEach { callableType ->
val callableParameters = callableType.getParameters(typeEvalContext)
val argumentIndex = callableType.implicitOffset + argumentExplicitIndex
if (callableParameters == null ||
argumentIndex >= callableParameters.size ||
callableParameters.any { it.isKeywordContainer || it.isPositionalContainer }) {
return@forEach
}
val unfilledParameters = ContainerUtil.subList(callableParameters, argumentIndex)
val variables = collectVariablesToComplete(unfilledParameters, names)
if (variables.size > 1) {
result.addElement(createParametersLookupElement(variables, call))
}
}
}
}
companion object {
val MULTIPLE_ARGUMENTS_VARIANT_KEY: Key<Boolean> = Key.create("py.multiple.arguments.completion.variant")
private fun getArgumentIndex(position: PsiElement): Int? {
val argumentList = PsiTreeUtil.getParentOfType(position, PyArgumentList::class.java) ?: return null
if (argumentList.arguments.isEmpty()) return null
if (argumentList.arguments.any { it is PyKeywordArgument || it is PyStarArgument }) return null
if (!PsiTreeUtil.isAncestor(argumentList.arguments.last(), position, false)) return null
return argumentList.arguments.size - 1
}
private fun createParametersLookupElement(variables: List<String>, call: PyCallExpression): LookupElement {
return LookupElementBuilder.create(variables.joinToString(", "))
.withIcon(IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Variable))
.withInsertHandler(PyMultipleArgumentsInsertHandler(call))
.apply {
putUserData(MULTIPLE_ARGUMENTS_VARIANT_KEY, true)
}
}
private fun collectVariablesToComplete(parameters: List<PyCallableParameter>, argumentsNames: Set<String>): List<String> {
val variables = mutableListOf<String>()
var keywordsOnlyFlag = false
for (parameter in parameters) {
if (parameter.parameter is PySlashParameter) continue
if (parameter.parameter is PySingleStarParameter) {
keywordsOnlyFlag = true
continue
}
val paramName = parameter.name ?: return emptyList()
if (paramName in argumentsNames) {
if (!keywordsOnlyFlag) {
variables.add(paramName)
}
else {
variables.add("$paramName=$paramName")
}
}
else {
if (!parameter.hasDefaultValue()) return emptyList()
}
}
return variables
}
private fun collectNames(scope: ScopeOwner, position: PsiElement): Set<String> =
ControlFlowCache.getScope(scope).namedElements
.asSequence()
.filter { element ->
PsiTreeUtil.getParentOfType(element, PyListCompExpression::class.java) ?.let { listComp ->
PsiTreeUtil.isAncestor(listComp.resultExpression, position, false)
} ?: PyPsiUtils.isBefore(element, position)
}
.mapNotNull { it.name }
.toSet()
}
}
class PyMultipleArgumentsInsertHandler(private val call: PyCallExpression): ParenthesesInsertHandler<LookupElement>() {
override fun placeCaretInsideParentheses(context: InsertionContext?, item: LookupElement?): Boolean = false
override fun handleInsert(context: InsertionContext, item: LookupElement) {
val editor = context.editor
context.commitDocument()
if (call.argumentList?.closingParen == null) {
editor.document.insertString(context.tailOffset, ")")
editor.caretModel.moveToOffset(context.tailOffset)
}
else {
editor.caretModel.moveToOffset(context.tailOffset + 1)
}
}
} | apache-2.0 | a10a7099dbb367ba6b51ce2c170c06c3 | 41.632353 | 126 | 0.733828 | 5.049652 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/settings/buildsystem/Repository.kt | 2 | 2702 | // 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.tools.projectWizard.settings.buildsystem
interface Repository {
val url: String
val idForMaven: String
}
data class DefaultRepository(val type: Type) : Repository {
override val url: String
get() = type.url
override val idForMaven: String
get() = type.gradleName
enum class Type(val gradleName: String, val url: String) {
JCENTER("jcenter", "https://jcenter.bintray.com/"),
MAVEN_CENTRAL("mavenCentral", "https://repo1.maven.org/maven2/"),
GOOGLE("google", "https://dl.google.com/dl/android/maven2/"),
GRADLE_PLUGIN_PORTAL("gradlePluginPortal", "https://plugins.gradle.org/m2/"),
MAVEN_LOCAL("mavenLocal", "")
}
companion object {
val JCENTER = DefaultRepository(Type.JCENTER)
val MAVEN_CENTRAL = DefaultRepository(Type.MAVEN_CENTRAL)
val GOOGLE = DefaultRepository(Type.GOOGLE)
val GRADLE_PLUGIN_PORTAL = DefaultRepository(Type.GRADLE_PLUGIN_PORTAL)
val MAVEN_LOCAL = DefaultRepository(Type.MAVEN_LOCAL)
}
}
interface CustomMavenRepository : Repository
@Suppress("unused")
data class CustomMavenRepositoryImpl(val repository: String, val base: String) : CustomMavenRepository {
override val url: String = "$base/$repository"
override val idForMaven: String
get() = "bintray." + repository.replace('/', '.')
}
data class JetBrainsSpace(val repository: String) : CustomMavenRepository {
override val url: String = "https://maven.pkg.jetbrains.space/$repository"
override val idForMaven: String
get() = "jetbrains." + repository.replace('/', '.')
}
data class CacheRedirector(val redirectedRepositoryBase: String, val repository: String) : CustomMavenRepository {
override val url: String = "https://cache-redirector.jetbrains.com/$redirectedRepositoryBase/$repository"
override val idForMaven: String
get() = "cache-redirector.jetbrains." +
redirectedRepositoryBase.replace('/', '.') + "." +
repository.replace('/', '.')
}
object Repositories {
val KTOR = DefaultRepository.MAVEN_CENTRAL
val KOTLINX_HTML = JetBrainsSpace("public/p/kotlinx-html/maven")
val KOTLIN_JS_WRAPPERS = DefaultRepository.MAVEN_CENTRAL
val KOTLIN_EAP_MAVEN_CENTRAL = DefaultRepository.MAVEN_CENTRAL
val JETBRAINS_KOTLIN_DEV = JetBrainsSpace("kotlin/p/kotlin/dev")
val JETBRAINS_KOTLIN_BOOTSTRAP = CacheRedirector(
"maven.pkg.jetbrains.space",
"kotlin/p/kotlin/bootstrap"
)
}
| apache-2.0 | 859febde8dc3f9b3d970037635de47f4 | 37.6 | 158 | 0.695781 | 4.163328 | false | false | false | false |
siosio/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/refactorings/RefactoringMenuLessonBase.kt | 1 | 3078 | // 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 training.learn.lesson.general.refactorings
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.rename.inplace.InplaceRefactoring
import com.intellij.ui.EngravedLabel
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.util.adaptToNotNativeLocalization
import javax.swing.JList
abstract class RefactoringMenuLessonBase(lessonId: String) : KLesson(lessonId, LessonsBundle.message("refactoring.menu.lesson.name")) {
fun LessonContext.extractParameterTasks() {
lateinit var showPopupTaskId: TaskContext.TaskId
task("Refactorings.QuickListPopupAction") {
showPopupTaskId = taskId
text(LessonsBundle.message("refactoring.menu.show.refactoring.list", action(it)))
val refactorThisTitle = RefactoringBundle.message("refactor.this.title")
triggerByUiComponentAndHighlight(false, false) { ui: EngravedLabel ->
ui.text?.contains(refactorThisTitle) == true
}
restoreIfModifiedOrMoved()
}
if (TaskTestContext.inTestMode) {
task {
stateCheck {
focusOwner !is EditorComponentImpl
}
}
}
if (!adaptToNotNativeLocalization) {
task(ActionsBundle.message("action.IntroduceParameter.text").dropMnemonic()) {
text(LessonsBundle.message("refactoring.menu.introduce.parameter.eng", strong(it)))
triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { ui: JList<*> ->
ui.model.size > 0 && ui.model.getElementAt(0).toString().contains(it)
}
restoreByUi(restoreId = showPopupTaskId, delayMillis = defaultRestoreDelay)
test {
type("pa")
}
}
}
task("IntroduceParameter") {
val message = if (adaptToNotNativeLocalization) {
LessonsBundle.message("refactoring.menu.introduce.parameter",
strong(ActionsBundle.message("action.IntroduceParameter.text").dropMnemonic()), LessonUtil.rawEnter())
}
else LessonsBundle.message("refactoring.menu.start.refactoring", action("EditorChooseLookupItem"), LessonUtil.actionName(it))
text(message)
trigger(it)
stateCheck { hasInplaceRename() }
restoreByUi(restoreId = showPopupTaskId, delayMillis = defaultRestoreDelay)
test {
invokeActionViaShortcut("ENTER")
}
}
task {
text(LessonsBundle.message("refactoring.menu.finish.refactoring", LessonUtil.rawEnter()))
stateCheck {
!hasInplaceRename()
}
test(waitEditorToBeReady = false) {
invokeActionViaShortcut("ENTER")
}
}
}
private fun TaskRuntimeContext.hasInplaceRename() = editor.getUserData(InplaceRefactoring.INPLACE_RENAMER) != null
}
| apache-2.0 | d5d75a180dc536fc2103fe9a5a888b44 | 38.974026 | 140 | 0.717674 | 4.909091 | false | true | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/network/OkHttpExtensions.kt | 2 | 2263 | package eu.kanade.tachiyomi.data.network
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import rx.Producer
import rx.Subscription
import java.util.concurrent.atomic.AtomicBoolean
fun Call.asObservable(): Observable<Response> {
return Observable.create { subscriber ->
// Since Call is a one-shot type, clone it for each new subscriber.
val call = if (!isExecuted) this else {
// TODO use clone method in OkHttp 3.5
val field = javaClass.getDeclaredField("client").apply { isAccessible = true }
val client = field.get(this) as OkHttpClient
client.newCall(request())
}
// Wrap the call in a helper which handles both unsubscription and backpressure.
val requestArbiter = object : AtomicBoolean(), Producer, Subscription {
override fun request(n: Long) {
if (n == 0L || !compareAndSet(false, true)) return
try {
val response = call.execute()
if (!subscriber.isUnsubscribed) {
subscriber.onNext(response)
subscriber.onCompleted()
}
} catch (error: Exception) {
if (!subscriber.isUnsubscribed) {
subscriber.onError(error)
}
}
}
override fun unsubscribe() {
call.cancel()
}
override fun isUnsubscribed(): Boolean {
return call.isCanceled
}
}
subscriber.add(requestArbiter)
subscriber.setProducer(requestArbiter)
}
}
fun OkHttpClient.newCallWithProgress(request: Request, listener: ProgressListener): Call {
val progressClient = newBuilder()
.cache(null)
.addNetworkInterceptor { chain ->
val originalResponse = chain.proceed(chain.request())
originalResponse.newBuilder()
.body(ProgressResponseBody(originalResponse.body(), listener))
.build()
}
.build()
return progressClient.newCall(request)
} | gpl-3.0 | b42101f7f284b2f1e56bafc310d6a998 | 33.30303 | 90 | 0.571365 | 5.388095 | false | false | false | false |
Zeroami/CommonLib-Kotlin | commonlib/src/main/java/com/zeroami/commonlib/CommonLib.kt | 1 | 1339 | package com.zeroami.commonlib
import android.content.Context
import com.orhanobut.logger.LogLevel
import com.orhanobut.logger.Logger
import com.zeroami.commonlib.utils.LL
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* CommonLib启动配置类
*
* @author Zeroami
*/
object CommonLib {
var ctx: Context by object : ReadWriteProperty<Any?, Context> {
private var value: Context? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): Context {
return value ?: throw RuntimeException("请调用CommonLib.initialize(context)确保CommonLib正常工作")
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Context) {
this.value = value
}
}
val TAG = "TAG"
/**
* 初始化Context,使CommonLib正常工作
*/
fun initialize(context: Context) {
ctx = context
setEnableLog(true)
}
/**
* 日志开关
*/
fun setEnableLog(isEnableLog: Boolean, tag: String = TAG) {
LL.setEnableLog(isEnableLog, tag)
if (isEnableLog) {
Logger.init(tag).logLevel(LogLevel.FULL).methodCount(1).methodOffset(1)
} else {
Logger.init(tag).logLevel(LogLevel.NONE).methodCount(1).methodOffset(1)
}
}
}
| apache-2.0 | 433eddae235e24843d353b56ff3ec668 | 24.7 | 101 | 0.64358 | 4.040881 | false | false | false | false |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/RetainAnnotation.kt | 4 | 983 | /*
* Copyright 2010-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.kotlin.backend.konan.llvm
import org.jetbrains.kotlin.backend.konan.descriptors.getAnnotationStringValue
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.util.findAnnotation
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.name.FqName
private val retainAnnotationName = FqName("kotlin.native.Retain")
private val retainForTargetAnnotationName = FqName("kotlin.native.RetainForTarget")
internal fun IrFunction.retainAnnotation(target: KonanTarget): Boolean {
if (this.annotations.findAnnotation(retainAnnotationName) != null) return true
val forTarget = this.annotations.findAnnotation(retainForTargetAnnotationName)
if (forTarget != null && forTarget.getAnnotationStringValue() == target.name) return true
return false
}
| apache-2.0 | 7fd83c6c70c150d3ccded0acd948432f | 43.681818 | 101 | 0.806714 | 4.330396 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/refactoring/rename/ui/RenameDialog.kt | 2 | 6394 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.rename.ui
import com.intellij.find.FindBundle
import com.intellij.ide.util.scopeChooser.ScopeChooserCombo
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.validation.DialogValidationRequestor
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsContexts.Label
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.rename.api.RenameValidationResult.Companion.RenameValidationResultData
import com.intellij.refactoring.rename.api.RenameValidationResult.Companion.RenameValidationResultProblemLevel
import com.intellij.refactoring.rename.api.RenameValidator
import com.intellij.refactoring.rename.impl.RenameOptions
import com.intellij.refactoring.rename.impl.TextOptions
import com.intellij.refactoring.ui.NameSuggestionsField
import com.intellij.ui.UserActivityWatcher
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.util.asSafely
import java.awt.event.ActionEvent
import java.awt.event.ItemEvent
import javax.swing.AbstractAction
import javax.swing.Action
import javax.swing.JComponent
internal class RenameDialog(
private val project: Project,
@Label private val presentableText: String,
private val renameValidator: RenameValidator,
initOptions: Options,
) : DialogWrapper(project) {
// model
private var myTargetName: String = initOptions.targetName
private var myCommentsStringsOccurrences: Boolean? = initOptions.renameOptions.textOptions.commentStringOccurrences
private var myTextOccurrences: Boolean? = initOptions.renameOptions.textOptions.textOccurrences
private var myScope: SearchScope = initOptions.renameOptions.searchScope
var preview: Boolean = false
private set
private val myPreviewAction: Action = object : AbstractAction(RefactoringBundle.message("preview.button")) {
override fun actionPerformed(e: ActionEvent) {
preview = true
okAction.actionPerformed(e)
}
}
// ui
private val myDialogPanel: DialogPanel = doCreateCenterPanel()
init {
title = RefactoringBundle.message("rename.title")
setOKButtonText(RefactoringBundle.message("rename.title"))
init()
installWatcher()
}
private fun installWatcher() {
UserActivityWatcher().apply {
addUserActivityListener(::stateChanged)
register(myDialogPanel)
}
}
private fun stateChanged() {
myDialogPanel.apply() // for some reason DSL UI implementation only updates model from UI only within apply()
}
override fun createCenterPanel(): JComponent = myDialogPanel
override fun createActions(): Array<Action> {
return arrayOf(okAction, cancelAction, helpAction, myPreviewAction)
}
private fun doCreateCenterPanel(): DialogPanel = panel {
presentableText()
newName()
textOccurrenceCheckboxes()
searchScope()
}
private fun Panel.presentableText() {
row {
label(RefactoringBundle.message("rename.0.and.its.usages.to", presentableText))
}
}
private fun Panel.newName() {
row {
cell(NameSuggestionsField(arrayOf(myTargetName), project))
.applyToComponent {
addDataChangedListener {
myTargetName = enteredName
}
}
.focused()
.label(RefactoringBundle.message("rename.dialog.new.name.label"))
.widthGroup("")
.align(AlignX.RIGHT)
.validationRequestor(
DialogValidationRequestor.WithParameter { field ->
DialogValidationRequestor { parentDisposable, validate ->
field.addDataChangedListener(validate)
parentDisposable?.let { Disposer.register(it) { field.removeDataChangedListener(validate) } }
}
})
.validation { field ->
renameValidator
.validate(field.enteredName)
.asSafely<RenameValidationResultData>()
?.let {
when (it.level) {
RenameValidationResultProblemLevel.WARNING -> warning(StringUtil.escapeXmlEntities(it.message(field.enteredName)))
RenameValidationResultProblemLevel.ERROR -> error(StringUtil.escapeXmlEntities(it.message(field.enteredName)))
}
}
}
}
}
private fun Panel.textOccurrenceCheckboxes() {
if (myCommentsStringsOccurrences == null && myTextOccurrences == null) {
return
}
row {
myCommentsStringsOccurrences?.let {
[email protected](RefactoringBundle.getSearchInCommentsAndStringsText())
.bindSelected({ it }, { myCommentsStringsOccurrences = it })
}
myTextOccurrences?.let {
[email protected](RefactoringBundle.getSearchForTextOccurrencesText())
.bindSelected({ it }, { myTextOccurrences = it })
}
}
}
private fun Panel.searchScope() {
if (myScope is LocalSearchScope) {
return
}
row {
cell(ScopeChooserCombo(project, true, true, myScope.displayName))
.applyToComponent {
Disposer.register(myDisposable, this)
comboBox.addItemListener { event ->
if (event.stateChange == ItemEvent.SELECTED) {
myScope = selectedScope ?: return@addItemListener
}
}
}
// For some reason Scope and New name fields are misaligned - fix this here
.customize(Gaps(right = 3))
.label(FindBundle.message("find.scope.label"))
.widthGroup("")
.align(AlignX.RIGHT)
}
}
fun result(): Options = Options(
targetName = myTargetName,
renameOptions = RenameOptions(
textOptions = TextOptions(
commentStringOccurrences = myCommentsStringsOccurrences,
textOccurrences = myTextOccurrences,
),
searchScope = myScope
)
)
data class Options(
val targetName: String,
val renameOptions: RenameOptions
)
}
| apache-2.0 | f266d3177cc43b419516404909903fc1 | 33.75 | 140 | 0.716297 | 4.847612 | false | false | false | false |
LouisCAD/Splitties | modules/views-dsl-recyclerview/src/androidMain/kotlin/splitties/views/dsl/recyclerview/SrollWrapping.kt | 1 | 939 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.views.dsl.recyclerview
import android.view.View
import androidx.annotation.IdRes
import androidx.recyclerview.widget.RecyclerView
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
inline fun View.wrapInRecyclerView(
horizontal: Boolean = false,
@IdRes id: Int = View.NO_ID,
initView: RecyclerView.() -> Unit = {}
): RecyclerView {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return wrapInRecyclerView(horizontal, id).apply(initView)
}
fun View.wrapInRecyclerView(
horizontal: Boolean = false,
@IdRes id: Int = View.NO_ID
): RecyclerView = recyclerView(id) {
val contentAdapter = SingleViewAdapter(this@wrapInRecyclerView, vertical = !horizontal)
layoutManager = contentAdapter.layoutManager
adapter = contentAdapter
}
| apache-2.0 | 2a5cf6e1ab2a5707494675e38920ae79 | 32.535714 | 109 | 0.761448 | 4.367442 | false | false | false | false |
smmribeiro/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/InlineStylesExtension.kt | 2 | 1712 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.extensions.common
import com.intellij.openapi.project.Project
import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension
import org.intellij.plugins.markdown.settings.MarkdownSettings
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel
import org.intellij.plugins.markdown.ui.preview.ResourceProvider
internal class InlineStylesExtension(private val project: Project?) : MarkdownBrowserPreviewExtension, ResourceProvider {
override val priority: MarkdownBrowserPreviewExtension.Priority
get() = MarkdownBrowserPreviewExtension.Priority.AFTER_ALL
override val styles: List<String> = listOf("inlineStyles/inline.css")
override val resourceProvider: ResourceProvider = this
override fun canProvide(resourceName: String): Boolean = resourceName in styles
override fun loadResource(resourceName: String): ResourceProvider.Resource {
val settings = project?.let(MarkdownSettings::getInstance)
val text = settings?.customStylesheetText.takeIf { settings?.useCustomStylesheetText == true }
return when (text) {
null -> ResourceProvider.Resource(emptyStylesheet)
else -> ResourceProvider.Resource(text.toByteArray())
}
}
override fun dispose() = Unit
class Provider: MarkdownBrowserPreviewExtension.Provider {
override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension? {
return InlineStylesExtension(panel.project)
}
}
companion object {
private val emptyStylesheet = "".toByteArray()
}
}
| apache-2.0 | 5476792f23621086cb303b22052811fa | 41.8 | 140 | 0.793224 | 5.203647 | false | false | false | false |
StuStirling/ribot-viewer | app/src/main/java/com/stustirling/ribotviewer/ui/allribot/AllRibotAdapter.kt | 1 | 2529 | package com.stustirling.ribotviewer.ui.allribot
import android.graphics.Color
import android.support.constraint.ConstraintLayout
import android.support.v4.graphics.drawable.DrawableCompat
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.stustirling.ribotviewer.R
import com.stustirling.ribotviewer.model.RibotModel
/**
* Created by Stu Stirling on 24/09/2017.
*/
class AllRibotAdapter(val callback: (ribot: RibotModel, sharedView:View) -> Unit) : RecyclerView.Adapter<AllRibotAdapter.ViewHolder> () {
var items : List<RibotModel> = emptyList()
set(value) {
field = value
notifyDataSetChanged() }
override fun getItemId(position: Int): Long {
return items[position].id.toLong()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.content_all_ribot,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) =
holder.bind( items[position] )
override fun getItemCount(): Int = items.size
inner class ViewHolder( itemView: View) : RecyclerView.ViewHolder(itemView) {
private val container = itemView.findViewById<ConstraintLayout>(R.id.cl_alc_container)
private val avatar = itemView.findViewById<ImageView>(R.id.civ_alc_avatar)
private val name = itemView.findViewById<TextView>(R.id.tv_alc_name)
fun bind(ribot:RibotModel) {
container.setOnClickListener { callback(items[adapterPosition],avatar) }
ViewCompat.setTransitionName(avatar,ribot.id)
val placeholder = container.context.getDrawable(R.drawable.small_ribot_logo).apply {
mutate()
DrawableCompat.setTint(this, Color.parseColor(ribot.hexColor))
}
Glide.with(avatar.context)
.load(ribot.avatar)
.apply(RequestOptions.fitCenterTransform()
.placeholder(placeholder))
.into(avatar)
name.text = avatar.context.getString(
R.string.full_name_format,ribot.firstName,ribot.lastName)
}
}
} | apache-2.0 | b17582184909f4d61b6621992df78146 | 36.761194 | 137 | 0.691973 | 4.360345 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/gui/view/window/chatroom/messaging/reading/display/room_event/m_message/embed_preview/display_node.kt | 1 | 6556 | @file:Suppress("EXPERIMENTAL_API_USAGE")
package koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.embed_preview
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.control.ContextMenu
import javafx.scene.control.MenuItem
import javafx.scene.input.Clipboard
import javafx.scene.input.ClipboardContent
import javafx.scene.layout.*
import javafx.scene.layout.VBox
import javafx.scene.paint.Color
import javafx.scene.text.Text
import koma.Server
import koma.gui.element.emoji.icon.EmojiIcon
import koma.gui.view.window.chatroom.messaging.reading.display.ViewNode
import koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.embed_preview.media.MediaViewers
import koma.gui.view.window.chatroom.messaging.reading.display.room_event.m_message.embed_preview.site.siteViewConstructors
import koma.koma_app.appState
import koma.matrix.UserId
import koma.storage.persistence.settings.AppSettings
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import link.continuum.desktop.gui.*
import link.continuum.desktop.gui.HBox
import link.continuum.desktop.gui.icon.avatar.AvatarInline
import link.continuum.desktop.gui.list.user.UserDataStore
import link.continuum.desktop.util.debugAssert
import link.continuum.desktop.util.debugAssertUiThread
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
private val settings: AppSettings = appState.store.settings
sealed class FlowElement {
abstract val node: Node
fun isMultiLine() = this is WebContentNode && this.multiLine
}
class InlineElement(override val node: Node): FlowElement() {
fun startsWithNewline(): Boolean = this.node is Text && this.node.text.firstOrNull() == '\n'
fun endsWithNewline(): Boolean = this.node is Text && this.node.text.lastOrNull() == '\n'
}
class UserLinkElement(
private val userDatas: UserDataStore
): FlowElement() {
private val scope = MainScope()
private val channel = Channel<Pair<UserId, Server>>(Channel.CONFLATED)
private val avatar = AvatarInline().apply {
root.background = whiteBackground
}
private val label = Text().apply {
fill = Color.WHITE
}
override val node = object: HBox(avatar.root, label) {
override fun getBaselineOffset(): Double = height * 0.75
init {
alignment = Pos.CENTER
background = orangeBackground
}
}
init {
var server: Server? = null
HBox.setMargin(avatar.root, insets)
HBox.setMargin(label, insets)
channel.consumeAsFlow().onEach {
server = it.second
avatar.updateUrl(null, it.second)
}.flatMapLatest {
userDatas.getAvatarUrlUpdates(it.first)
}.onEach { url->
debugAssert(server != null)
server?.let {avatar.updateUrl(url, it)}
}.launchIn(scope)
}
fun update(name: String, userId: UserId, server: Server) {
debugAssertUiThread()
label.text = name
channel.offer(userId to server)
}
companion object {
private val insets = Insets(0.0, 2.0, 0.0, 2.0)
private val orangeBackground = Background(BackgroundFill(Color.DARKORANGE, CornerRadii(4.0), Insets.EMPTY))
private val whiteBackground = Background(BackgroundFill(Color.WHITE, CornerRadii(2.0), Insets.EMPTY))
}
}
fun messageSliceView(slice: TextSegment, server: Server,
data: UserDataStore
): FlowElement {
return when(slice) {
is PlainTextSegment -> InlineElement(Text(slice.text))
is LinkTextSegment -> WebContentNode(slice.text, server)
is EmojiTextSegment -> {
val icon = EmojiIcon(slice.emoji, settings.fontSize)
InlineElement(icon.node)
}
is UserIdLink -> {
val link = UserLinkElement(data)
link.update(slice.text, slice.userId, server)
link
}
}
}
/**
* link with optional preview
*/
@ExperimentalCoroutinesApi
class WebContentNode(private val link: String,
server: Server
): FlowElement() {
override val node = VBox()
val multiLine: Boolean
private val menuItems = mutableListOf<MenuItem>()
private val mediaViewers = MediaViewers(server)
init {
val linknode = hyperlinkNode(link)
node.add(linknode)
val preview = findPreview()
if (preview != null) {
multiLine = true
val prefWide = doubleBinding(preview.node.widthProperty()) { Math.max(value, 160.0)}
linknode.prefWidthProperty().bind(prefWide)
setUpPrevie(preview)
} else {
linknode.maxWidth = 200.0 * settings.scaling
multiLine = false
}
setUpMenus()
}
private fun findPreview(): ViewNode? {
val url = link.toHttpUrlOrNull()
url ?: return null
val site = url.host
val sview = siteViewConstructors.get(site)?.let { view -> view(url) }
val filename = url.pathSegments.last()
val ext = filename.substringAfter('.')
val view = sview ?: mediaViewers.get(ext, url)
return view
}
private fun setUpPrevie(view: ViewNode) {
node.border = Border(BorderStroke(
Color.LIGHTGRAY,
BorderStrokeStyle.SOLID,
CornerRadii(3.0, false),
BorderWidths(1.0)
))
node.background = Background(BackgroundFill(
Color.TRANSPARENT,
CornerRadii(3.0, false),
Insets.EMPTY))
node.add(view.node)
menuItems.addAll(view.menuItems)
}
private val cmenu by lazy {
ContextMenu().apply {
this.items.addAll(menuItems)
item("Copy URL").action {
Clipboard.getSystemClipboard().setContent(
ClipboardContent().apply {
putString(link)
}
)
}
item("Open in Browser").action { openInBrowser(link) }
}
}
private fun setUpMenus() {
node.setOnContextMenuRequested {
cmenu.show(this.node, it.screenX, it.screenY)
it.consume()
}
}
}
| gpl-3.0 | 0aeecb3001fd5b943d89b9ef6731a0ec | 32.620513 | 123 | 0.656345 | 4.279373 | false | false | false | false |
atlarge-research/opendc-simulator | opendc-stdlib/src/main/kotlin/com/atlarge/opendc/simulator/instrumentation/Helpers.kt | 1 | 2084 | package com.atlarge.opendc.simulator.instrumentation
import kotlinx.coroutines.experimental.Unconfined
import kotlinx.coroutines.experimental.channels.ReceiveChannel
import kotlinx.coroutines.experimental.channels.consumeEach
import kotlinx.coroutines.experimental.channels.produce
import kotlinx.coroutines.experimental.channels.toChannel
import kotlinx.coroutines.experimental.launch
import kotlin.coroutines.experimental.CoroutineContext
import kotlin.coroutines.experimental.coroutineContext
/**
* Transform each element in the channel into a [ReceiveChannel] of output elements that is then flattened into the
* output stream by emitting elements from the channels as they become available.
*
* @param context The [CoroutineContext] to run the operation in.
* @param transform The function to transform the elements into channels.
* @return The flattened [ReceiveChannel] of merged elements.
*/
fun <E, R> ReceiveChannel<E>.flatMapMerge(context: CoroutineContext = Unconfined,
transform: suspend (E) -> ReceiveChannel<R>): ReceiveChannel<R> =
produce(context) {
val job = launch(Unconfined) {
consumeEach {
launch(coroutineContext) {
transform(it).toChannel(this@produce)
}
}
}
job.join()
}
/**
* Merge this channel with the other channel into an output stream by emitting elements from the channels as they
* become available.
*
* @param context The [CoroutineContext] to run the operation in.
* @param other The other channel to merge with.
* @return The [ReceiveChannel] of merged elements.
*/
fun <E, E1: E, E2: E> ReceiveChannel<E1>.merge(context: CoroutineContext = Unconfined,
other: ReceiveChannel<E2>): ReceiveChannel<E> =
produce(context) {
val job = launch(Unconfined) {
launch(coroutineContext) { toChannel(this@produce) }
launch(coroutineContext) { other.toChannel(this@produce) }
}
job.join()
}
| mit | 834d886b197ff25db477ae85a65fdcea | 41.530612 | 115 | 0.693378 | 4.857809 | false | false | false | false |
intrigus/jtransc | jtransc-utils/src/com/jtransc/log/log.kt | 2 | 991 | package com.jtransc.log
import com.jtransc.time.measureTime
object log {
enum class Level { DEBUG, INFO, WARN, ERROR }
var logger: (Any?, Level) -> Unit = { content, level -> println(content) }
inline fun <T> setTempLogger(noinline logger: (Any?, Level) -> Unit, callback: () -> T): T {
val oldLogger = this.logger
this.logger = logger
try {
return callback()
} finally {
this.logger = oldLogger
}
}
operator fun invoke(v: Any?) {
logger(v, Level.INFO)
}
operator fun invoke(v: Any?, type: Level) {
logger(v, type)
}
fun debug(v: Any?) {
logger(v, Level.DEBUG)
}
fun info(v: Any?) {
logger(v, Level.INFO)
}
fun warn(v: Any?) {
logger(v, Level.WARN)
}
fun error(v: Any?) {
logger(v, Level.ERROR)
}
inline fun <T> logAndTime(text:String, callback: () -> T): T {
log("$text...")
val (time, result) = measureTime {
callback()
}
log("Ok($time)")
return result
}
fun printStackTrace(e: Throwable) {
e.printStackTrace()
}
} | apache-2.0 | 1042452bdec8fbf863c65a58c3c3e4ce | 16.714286 | 93 | 0.618567 | 2.77591 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/wallet/WalletScreen.kt | 1 | 11150 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 1/21/20.
* Copyright (c) 2020 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.wallet
import com.breadwallet.R
import com.breadwallet.breadbox.WalletState
import com.breadwallet.crypto.Transfer
import com.breadwallet.legacy.presenter.entities.CryptoRequest
import com.breadwallet.model.PriceChange
import com.breadwallet.model.PriceDataPoint
import com.breadwallet.tools.manager.MarketDataResult
import com.breadwallet.tools.util.asCryptoRequestUrl
import com.breadwallet.ui.navigation.NavigationEffect
import com.breadwallet.ui.navigation.NavigationTarget
import com.breadwallet.platform.entities.TxMetaData
import dev.zacsweers.redacted.annotations.Redacted
import java.math.BigDecimal
object WalletScreen {
const val DIALOG_CREATE_ACCOUNT = "create_account_dialog"
data class M(
val currencyCode: String,
val currencyId: String = "",
val currencyName: String = "",
@Redacted val address: String = "",
val fiatPricePerUnit: String = "",
val balance: BigDecimal = BigDecimal.ZERO,
val fiatBalance: BigDecimal = BigDecimal.ZERO,
@Redacted val transactions: List<WalletTransaction> = emptyList(),
@Redacted val filteredTransactions: List<WalletTransaction> = emptyList(),
val isCryptoPreferred: Boolean = false,
val isShowingDelistedBanner: Boolean = false,
val isShowingSearch: Boolean = false,
val isShowingBrdRewards: Boolean = false,
val isShowingReviewPrompt: Boolean = false,
val showReviewPrompt: Boolean = false,
@Redacted val filterQuery: String = "",
val filterSent: Boolean = false,
val filterReceived: Boolean = false,
val filterPending: Boolean = false,
val filterComplete: Boolean = false,
val syncProgress: Float = 0f,
val syncingThroughMillis: Long = 0,
val isSyncing: Boolean = false,
val hasInternet: Boolean = true,
val priceChartIsLoading: Boolean = true,
val priceChartInterval: Interval = Interval.ONE_YEAR,
@Redacted val priceChartDataPoints: List<PriceDataPoint> = emptyList(),
val marketDataState: MarketDataState = MarketDataState.LOADING,
val marketCap: BigDecimal? = null,
val totalVolume: BigDecimal? = null,
val high24h: BigDecimal? = null,
val low24h: BigDecimal? = null,
val selectedPriceDataPoint: PriceDataPoint? = null,
val priceChange: PriceChange? = null,
val state: WalletState = WalletState.Loading
) {
companion object {
fun createDefault(currencyCode: String) =
M(currencyCode = currencyCode)
}
val isFilterApplied: Boolean
get() = filterQuery.isNotBlank() ||
filterSent || filterReceived ||
filterPending || filterComplete
}
sealed class E {
data class OnSyncProgressUpdated(
val progress: Float,
val syncThroughMillis: Long,
val isSyncing: Boolean
) : E() {
init {
require(progress in 0.0..1.0) {
"Sync progress must be in 0..1 but was $progress"
}
}
}
data class OnQueryChanged(@Redacted val query: String) : E()
data class OnCurrencyNameUpdated(val name: String, val currencyId: String) : E()
data class OnBrdRewardsUpdated(val showing: Boolean) : E()
data class OnBalanceUpdated(val balance: BigDecimal, val fiatBalance: BigDecimal) : E()
data class OnFiatPricePerUpdated(val pricePerUnit: String, val priceChange: PriceChange?) :
E()
data class OnTransactionsUpdated(
@Redacted val walletTransactions: List<WalletTransaction>
) : E()
data class OnTransactionMetaDataUpdated(
@Redacted val transactionHash: String,
val transactionMetaData: TxMetaData
) : E()
data class OnTransactionMetaDataLoaded(
val metadata: Map<String, TxMetaData>
) : E()
data class OnVisibleTransactionsChanged(
@Redacted val transactionHashes: List<String>
) : E()
data class OnCryptoTransactionsUpdated(
@Redacted val transactions: List<Transfer>
) : E()
data class OnTransactionAdded(val walletTransaction: WalletTransaction) : E()
data class OnTransactionRemoved(val walletTransaction: WalletTransaction) : E()
data class OnConnectionUpdated(val isConnected: Boolean) : E()
object OnFilterSentClicked : E()
object OnFilterReceivedClicked : E()
object OnFilterPendingClicked : E()
object OnFilterCompleteClicked : E()
object OnSearchClicked : E()
object OnSearchDismissClicked : E()
object OnBackClicked : E()
object OnGiftClicked : E()
object OnChangeDisplayCurrencyClicked : E()
object OnSendClicked : E()
data class OnSendRequestGiven(val cryptoRequest: CryptoRequest) : E()
object OnReceiveClicked : E()
data class OnTransactionClicked(@Redacted val txHash: String) : E()
object OnBrdRewardsClicked : E()
data class OnIsCryptoPreferredLoaded(val isCryptoPreferred: Boolean) : E()
data class OnChartIntervalSelected(val interval: Interval) : E()
data class OnMarketChartDataUpdated(
@Redacted val priceDataPoints: List<PriceDataPoint>
) : E()
data class OnMarketDataUpdated(
val marketData : MarketDataResult
) : E()
data class OnChartDataPointSelected(val priceDataPoint: PriceDataPoint) : E()
object OnChartDataPointReleased : E()
data class OnIsTokenSupportedUpdated(val isTokenSupported: Boolean) : E()
data class OnWalletStateUpdated(val walletState: WalletState) : E()
object OnCreateAccountClicked : E()
object OnCreateAccountConfirmationClicked : E()
object OnStakingCellClicked : E()
}
sealed class F {
data class UpdateCryptoPreferred(val cryptoPreferred: Boolean) : F()
sealed class Nav : F(), NavigationEffect {
data class GoToSend(
val currencyId: String,
val cryptoRequest: CryptoRequest? = null
) : Nav() {
override val navigationTarget =
NavigationTarget.SendSheet(currencyId, cryptoRequest?.asCryptoRequestUrl())
}
data class GoToReceive(val currencyId: String) : Nav() {
override val navigationTarget =
NavigationTarget.ReceiveSheet(currencyId)
}
data class GoToTransaction(
val currencyId: String,
val txHash: String
) : Nav() {
override val navigationTarget =
NavigationTarget.ViewTransaction(currencyId, txHash)
}
object GoBack : Nav() {
override val navigationTarget = NavigationTarget.Back
}
object GoToBrdRewards : Nav() {
override val navigationTarget = NavigationTarget.BrdRewards
}
data class GoToStaking(
val currencyId: String
): Nav() {
override val navigationTarget = NavigationTarget.Staking(currencyId)
}
data class GoToCreateGift(
val currencyId: String
): Nav() {
override val navigationTarget = NavigationTarget.CreateGift(currencyId)
}
}
data class LoadCurrencyName(val currencyCode: String) : F()
data class LoadSyncState(val currencyCode: String) : F()
data class LoadWalletBalance(val currencyCode: String) : F()
data class LoadTransactions(val currencyCode: String) : F()
data class LoadFiatPricePerUnit(val currencyCode: String) : F()
data class LoadTransactionMetaData(
val currencyCode: String,
@Redacted val transactionHashes: List<String>
) : F()
data class LoadTransactionMetaDataSingle(
val currencyCode: String,
@Redacted val transactionHashes: List<String>
) : F()
data class LoadIsTokenSupported(val currencyCode: String) : F()
object LoadCryptoPreferred : F()
data class ConvertCryptoTransactions(
@Redacted val transactions: List<Transfer>
) : F()
data class LoadChartInterval(
val interval: Interval,
val currencyCode: String
) : F()
data class LoadMarketData(
val currencyCode: String
) : F()
data class TrackEvent(
val eventName: String,
val attributes: Map<String, String>? = null
) : F()
data class LoadWalletState(val currencyCode: String) : F()
object ShowCreateAccountDialog : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
titleResId = R.string.AccountCreation_title,
messageResId = R.string.AccountCreation_body,
positiveButtonResId = R.string.AccountCreation_create,
negativeButtonResId = R.string.AccountCreation_notNow,
dialogId = DIALOG_CREATE_ACCOUNT
)
}
object ShowCreateAccountErrorDialog : F(), NavigationEffect {
override val navigationTarget = NavigationTarget.AlertDialog(
titleResId = R.string.AccountCreation_title,
messageResId = R.string.AccountCreation_error,
positiveButtonResId = R.string.AccessibilityLabels_close
)
}
data class CreateAccount(val currencyCode: String) : F()
object LoadConnectivityState : F()
}
}
enum class MarketDataState {
LOADED, LOADING, ERROR
}
| mit | f74bff1c778a312a8efb83158b2cb98a | 36.79661 | 99 | 0.644215 | 5.036134 | false | false | false | false |
deviant-studio/energy-meter-scanner | app/src/main/java/ds/meterscanner/mvvm/viewmodel/MainViewModel.kt | 1 | 3306 | package ds.meterscanner.mvvm.viewmodel
import L
import android.graphics.Bitmap
import android.text.format.DateUtils
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.instance
import com.google.firebase.auth.FirebaseUser
import ds.bindingtools.binding
import ds.meterscanner.R
import ds.meterscanner.db.model.Snapshot
import ds.meterscanner.mvvm.BindableViewModel
import ds.meterscanner.mvvm.Command
import ds.meterscanner.mvvm.MainView
import ds.meterscanner.mvvm.invoke
import ds.meterscanner.util.post
class MainViewModel(kodein: Kodein) : BindableViewModel(kodein) {
var buttonsEnabled: Boolean by binding()
var lastUpdated: String by binding()
var apiKey: String by binding()
var toolbarSubtitle: String by binding()
val onLoggedInCommand = Command<Unit>()
val runAlarmsCommand = Command<Unit>()
private var jobsChecked = false
var jobId: Int = -1
var isIntentConsumed = false
val appVersion: String = instance("version")
init {
toggleProgress(true)
}
override fun onLoggedIn(user: FirebaseUser) {
L.v("signed in")
// workaround
post { toggleProgress(false) }
db.keepSynced(true)
prepareApiKey()
updateLastSnapshot()
toolbarSubtitle = user.email ?: ""
checkTasks()
onLoggedInCommand()
}
private fun prepareApiKey() = async {
try {
apiKey = prefs.apiKey()
L.v("anyline key=$apiKey")
} catch (e: Exception) {
showSnackbarCommand(getString(R.string.api_key_not_found))
}
}
private fun updateLastSnapshot() = async {
val snapshot: Snapshot = db.getLatestSnapshot()
lastUpdated = "${getString(R.string.latest_shot)} ${DateUtils.getRelativeTimeSpanString(snapshot.timestamp)}"
}
private fun checkTasks() {
if (scheduler.getScheduledJobs().size == 0 && jobId < 0 && !jobsChecked) {
jobsChecked = true
showSnackbarCommand(getString(R.string.empty_jobs_message), actionText = R.string.go, actionCallback = {
runAlarmsCommand()
})
}
}
fun logout() {
authenticator.signOut()
toggleProgress(true)
scheduler.clearAllJobs()
prefs.clearAll()
}
override fun toggleProgress(enabled: Boolean) {
super.toggleProgress(enabled)
buttonsEnabled = !enabled
}
fun onNewData(value: Double, bitmap: Bitmap, corrected: Boolean) = async {
val s = Snapshot(value, prefs.currentTemperature.toInt())
val url = if (prefs.saveImages)
db.uploadImage(bitmap, s.timestamp.toString())
else
""
s.image = url
db.saveSnapshot(s)
val message = "$value " + if (corrected) "(corrected)" else ""
showSnackbarCommand(message, actionText = R.string.discard, actionCallback = {
db.deleteSnapshots(listOf(s))
})
updateLastSnapshot()
}
fun onCameraButton(view: MainView) = view.navigateCameraScreen()
fun onListsButton(view: MainView) = view.navigateListsScreen()
fun onChartsButton(view: MainView) = view.navigateChartsScreen()
fun onSettingsButton(view: MainView) = view.navigateSettingsScreen()
} | mit | 200e9fac44a5c29618d8f79114bb0b83 | 28.792793 | 117 | 0.659105 | 4.373016 | false | false | false | false |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/encoding/AsciiArmouredGpgXCoder.kt | 1 | 1699 | package io.oversec.one.crypto.encoding
import android.content.Context
import io.oversec.one.crypto.R
import io.oversec.one.crypto.encoding.pad.AbstractPadder
import io.oversec.one.crypto.gpg.GpgCryptoHandler
import io.oversec.one.crypto.gpg.OversecAsciiArmoredOutputStream
import io.oversec.one.crypto.proto.Outer
import java.io.IOException
class AsciiArmouredGpgXCoder(ctx: Context) : AbstractXCoder(ctx) {
override val id: String
get() = ID
override val isTextOnly: Boolean
get() = true
@Throws(IOException::class)
override fun encodeInternal(
msg: Outer.Msg,
ignore: AbstractPadder?,
packagename: String
): String {
return GpgCryptoHandler.getRawMessageAsciiArmoured(msg) ?: ""
}
@Throws(IOException::class, IllegalArgumentException::class)
override fun decode(s: String): Outer.Msg? {
val i = s.indexOf(OversecAsciiArmoredOutputStream.headerStart)
if (i < 0) {
return null
} else {
val k = s.indexOf(
OversecAsciiArmoredOutputStream.footerStart,
i + OversecAsciiArmoredOutputStream.headerStart.length
)
if (k < 0) {
throw IllegalArgumentException("invalid ascii armour")
}
}
return GpgCryptoHandler.parseMessageAsciiArmoured(s)
}
override fun getLabel(padder: AbstractPadder?): String {
return mCtx.getString(R.string.encoder_gpg_ascii_armoured)
}
override fun getExample(padder: AbstractPadder?): String {
return "-----BEGIN PGP MESSAGE-----"
}
companion object {
const val ID = "gpg-ascii-armoured"
}
}
| gpl-3.0 | 6ded447f3238f549489e19777e3f44f8 | 28.807018 | 70 | 0.657446 | 4.164216 | false | false | false | false |
addonovan/ftc-ext | ftc-ext/src/main/java/com/addonovan/ftcext/Log.kt | 1 | 3513 | /**
* The MIT License (MIT)
*
* Copyright (c) 2016 Austin Donovan (addonovan)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.addonovan.ftcext
import android.util.Log as AndroidLog
import java.util.*
import kotlin.reflect.KClass
/**
* An interface which handles the minor annoyances of having to write the log tags.
*
* @author addonovan
* @since 8/16/16
*/
interface ILog
{
val LogTag: String;
@Suppress( "unused" ) fun v( msg: String ) = AndroidLog.v( LogTag, msg );
@Suppress( "unused" ) fun d( msg: String ) = AndroidLog.d( LogTag, msg );
@Suppress( "unused" ) fun i( msg: String ) = AndroidLog.i( LogTag, msg );
@Suppress( "unused" ) fun w( msg: String ) = AndroidLog.w( LogTag, msg );
@Suppress( "unused" ) fun e( msg: String ) = AndroidLog.e( LogTag, msg );
@Suppress( "unused" ) fun wtf( msg: String ) = AndroidLog.e( LogTag, msg );
@Suppress( "unused" ) fun v( msg: String, error: Throwable ) = AndroidLog.v( LogTag, msg, error );
@Suppress( "unused" ) fun d( msg: String, error: Throwable ) = AndroidLog.d( LogTag, msg, error );
@Suppress( "unused" ) fun i( msg: String, error: Throwable ) = AndroidLog.i( LogTag, msg, error );
@Suppress( "unused" ) fun w( msg: String, error: Throwable ) = AndroidLog.w( LogTag, msg, error );
@Suppress( "unused" ) fun e( msg: String, error: Throwable ) = AndroidLog.e( LogTag, msg, error );
@Suppress( "unused" ) fun wtf( msg: String, error: Throwable ) = AndroidLog.wtf( LogTag, msg, error );
}
/** Class that implements the ILog interface. */
private class Log( override val LogTag: String ) : ILog;
/** Stores all of the log instances. */
private val logMap = HashMap< String, ILog >();
/**
* Gets the log for the given class, if one doesn't exist, then it is made.
*
* @param[kClass]
* The class to get the log for.
* @return The log for the class.
*/
fun getLog( kClass: KClass< * > ): ILog
{
val name = kClass.java.name;
if ( !logMap.containsKey( name ) )
{
logMap[ name ] = Log( "ftcext.${kClass.java.simpleName}" );
}
return logMap[ name ]!!;
}
/**
* Gets a log for the given id. This is generally used for when classes are
* not accessible for some reason.
*
* @param[id]
* The id of the logger.
* @return The log for the id.
*/
fun getLog( id: String ): ILog
{
if ( !logMap.containsKey( id ) )
{
logMap[ id ] = Log( "ftcext.$id" );
}
return logMap[ id ]!!;
}
| mit | 4adecbdb98b29b2a6ed048c4bb429a31 | 34.846939 | 106 | 0.668375 | 3.555668 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/internal/adapter/DelimitedStringSetAdapterFactory.kt | 2 | 2362 | package me.proxer.library.internal.adapter
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
/**
* @author Ruben Gees
*/
internal class DelimitedStringSetAdapterFactory : JsonAdapter.Factory {
@Suppress("ReturnCount")
override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? {
val rawType = Types.getRawType(type)
if (rawType !== Set::class.java || type !is ParameterizedType) {
return null
}
val parameterType = type.actualTypeArguments[0]
if (parameterType !== String::class.java) {
return null
}
val annotation = annotations.filterIsInstance(DelimitedStringSet::class.java).firstOrNull() ?: return null
return DelimitedStringSetAdapter(
annotation.delimiter,
annotation.valuesToKeep
)
}
private class DelimitedStringSetAdapter internal constructor(
private val delimiter: String,
valuesToKeep: Array<String>
) : JsonAdapter<Set<String>>() {
private val valuesToKeep = valuesToKeep.map { it.split(delimiter).toSet() }
override fun fromJson(reader: JsonReader): Set<String> {
return if (reader.peek() == JsonReader.Token.NULL) {
reader.nextNull<Any>()
emptySet()
} else {
val rawParts = reader.nextString().trim()
if (rawParts.isEmpty()) {
emptySet()
} else {
val splitParts = rawParts.split(delimiter).toMutableSet()
for (valueToKeep in valuesToKeep) {
if (splitParts.removeAll(valueToKeep)) {
splitParts.add(valueToKeep.joinToString(delimiter))
}
}
splitParts
}
}
}
override fun toJson(writer: JsonWriter, value: Set<String>?) {
if (value == null) {
writer.nullValue()
} else {
writer.value(value.joinToString(delimiter))
}
}
}
}
| gpl-3.0 | 4dca6e3b26303d815ce97ef5f76927e3 | 29.675325 | 114 | 0.579594 | 5.025532 | false | false | false | false |
juanavelez/crabzilla | crabzilla-pg-client/src/main/java/io/github/crabzilla/pgc/PgcEntityComponent.kt | 1 | 2649 | package io.github.crabzilla.pgc
import io.github.crabzilla.framework.*
import io.github.crabzilla.internal.CommandController
import io.github.crabzilla.internal.EntityComponent
import io.vertx.core.Promise
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.pgclient.PgPool
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class PgcEntityComponent<E: Entity>(vertx: Vertx,
writeDb: PgPool,
private val entityName: String,
private val jsonAware: EntityJsonAware<E>,
cmdAware: EntityCommandAware<E>) : EntityComponent<E> {
companion object {
private val log: Logger = LoggerFactory.getLogger(PgcEntityComponent::class.java)
}
private val uowRepo = PgcUowRepo(writeDb, jsonAware)
private val snapshotRepo = PgcSnapshotRepo(writeDb, entityName, cmdAware, jsonAware)
private val uowJournal = PgcUowJournal(vertx, writeDb, jsonAware)
private val cmdController = CommandController(cmdAware, snapshotRepo, uowJournal)
override fun entityName(): String {
return entityName
}
override fun getUowByUowId(uowId: Long) : Promise<UnitOfWork> {
return uowRepo.getUowByUowId(uowId)
}
override fun getAllUowByEntityId(id: Int): Promise<List<UnitOfWork>> {
return uowRepo.getAllUowByEntityId(id)
}
override fun getSnapshot(entityId: Int): Promise<Snapshot<E>> {
return snapshotRepo.retrieve(entityId)
}
override fun handleCommand(metadata: CommandMetadata, command: Command): Promise<Pair<UnitOfWork, Long>> {
val promise = Promise.promise<Pair<UnitOfWork, Long>>()
uowRepo.getUowByCmdId(metadata.commandId).future().setHandler { gotCommand ->
if (gotCommand.succeeded()) {
val uowPair = gotCommand.result()
if (uowPair != null) {
promise.complete(uowPair)
return@setHandler
}
}
cmdController.handle(metadata, command).future().setHandler { cmdHandled ->
if (cmdHandled.succeeded()) {
val pair = cmdHandled.result()
promise.complete(pair)
if (log.isTraceEnabled) log.trace("Command successfully handled: $pair")
} else {
log.error("When handling command", cmdHandled.cause())
promise.fail(cmdHandled.cause())
}
}
}
return promise
}
override fun toJson(state: E): JsonObject {
return jsonAware.toJson(state)
}
override fun cmdFromJson(commandName: String, cmdAsJson: JsonObject): Command {
return jsonAware.cmdFromJson(commandName, cmdAsJson)
}
}
| apache-2.0 | df3d4974a270b3383eaa411f7eceeaf4 | 32.1125 | 108 | 0.680634 | 4.062883 | false | false | false | false |
actframework/FrameworkBenchmarks | frameworks/Kotlin/http4k/core/src/main/kotlin/Database.kt | 3 | 1887 | import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.ResultSet
class Database(private val dataSource: javax.sql.DataSource) {
companion object {
operator fun invoke(host: String): Database {
val postgresqlUrl = "jdbc:postgresql://$host:5432/hello_world?" +
"jdbcCompliantTruncation=false&" +
"elideSetAutoCommits=true&" +
"useLocalSessionState=true&" +
"cachePrepStmts=true&" +
"cacheCallableStmts=true&" +
"alwaysSendSetIsolation=false&" +
"prepStmtCacheSize=4096&" +
"cacheServerConfiguration=true&" +
"prepStmtCacheSqlLimit=2048&" +
"traceProtocol=false&" +
"useUnbufferedInput=false&" +
"useReadAheadInput=false&" +
"maintainTimeStats=false&" +
"useServerPrepStmts=true&" +
"cacheRSMetadata=true"
val config = HikariConfig()
config.jdbcUrl = postgresqlUrl
config.maximumPoolSize = 100
config.username = "benchmarkdbuser"
config.password = "benchmarkdbpass"
return Database(HikariDataSource(config))
}
}
fun <T> withConnection(fn: Connection.() -> T): T = dataSource.connection.use(fn)
fun <T> withStatement(stmt: String, fn: PreparedStatement.() -> T): T = withConnection { withStatement(stmt, fn) }
}
fun <T> Connection.withStatement(stmt: String, fn: PreparedStatement.() -> T): T = prepareStatement(stmt).use(fn)
fun <T> ResultSet.toList(fn: ResultSet.() -> T): List<T> =
use {
mutableListOf<T>().apply {
while (next()) {
add(fn(this@toList))
}
}
}
| bsd-3-clause | 803c20b8be30e0f670248fadc9ab9f18 | 36 | 118 | 0.585056 | 4.450472 | false | true | false | false |
KotlinPorts/pooled-client | db-async-common/src/main/kotlin/com/github/elizarov/async/withTimeout-test.kt | 2 | 1126 | package com.github.elizarov.async
import io.netty.channel.EventLoopGroup
import io.netty.channel.nio.NioEventLoopGroup
import java.time.Duration
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executors
fun main(args: Array<String>) {
val service = Executors.newSingleThreadScheduledExecutor()
fun supplySlow(s: String) = CompletableFuture.supplyAsync<String> {
Thread.sleep(500L)
s
}
val f = async<String> {
val a = supplySlow("A").await()
log("a = $a")
withTimeout(service, Duration.ofSeconds(1)) {
val b = supplySlow("B").await()
log("b = $b")
}
try {
withTimeout(service, Duration.ofMillis(750L)) {
val c = supplySlow("C").await()
log("c = $c")
val d = supplySlow("D").await()
log("d = $d")
}
} catch (ex: CancellationException) {
log("timed out with $ex")
}
val e = supplySlow("E").await()
log("e = $e")
"done"
}
println("f.get() = ${f.get()}")
}
| apache-2.0 | 724b8526ad49e62735999f068911df20 | 27.871795 | 71 | 0.553286 | 3.978799 | false | false | false | false |
daemontus/Distributed-CTL-Model-Checker | src/main/kotlin/com/github/sybila/checker/map/ConstantStateMap.kt | 3 | 668 | package com.github.sybila.checker.map
import com.github.sybila.checker.StateMap
import java.util.*
class ConstantStateMap<out Params : Any>(
internal val states: BitSet,
private val value: Params,
private val default: Params
) : StateMap<Params> {
override fun states(): Iterator<Int> = states.stream().iterator()
override fun entries(): Iterator<Pair<Int, Params>> = states.stream().mapToObj { it to value }.iterator()
override fun get(state: Int): Params = if (states.get(state)) value else default
override fun contains(state: Int): Boolean = states.get(state)
override val sizeHint: Int = states.cardinality()
} | gpl-3.0 | eb94c871213bdab2f1de06cf6e32a7df | 28.086957 | 109 | 0.699102 | 4.073171 | false | false | false | false |
mikkokar/styx | system-tests/ft-suite/src/test/kotlin/com/hotels/styx/admin/MetricsSpec.kt | 1 | 5257 | /*
Copyright (C) 2013-2020 Expedia 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.hotels.styx.admin
import com.github.tomakehurst.wiremock.client.WireMock
import com.hotels.styx.api.HttpHeaderNames.HOST
import com.hotels.styx.api.HttpRequest.get
import com.hotels.styx.api.HttpResponseStatus.OK
import com.hotels.styx.server.HttpConnectorConfig
import com.hotels.styx.servers.MockOriginServer
import com.hotels.styx.support.ResourcePaths
import com.hotels.styx.support.StyxServerProvider
import com.hotels.styx.support.metrics
import com.hotels.styx.support.proxyHttpHostHeader
import com.hotels.styx.support.testClient
import com.hotels.styx.support.wait
import io.kotlintest.Spec
import io.kotlintest.eventually
import io.kotlintest.matchers.doubles.shouldBeGreaterThan
import io.kotlintest.matchers.numerics.shouldBeGreaterThan
import io.kotlintest.matchers.shouldBeInRange
import io.kotlintest.seconds
import io.kotlintest.shouldBe
import io.kotlintest.specs.FunSpec
import org.slf4j.LoggerFactory
import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
class MetricsSpec : FunSpec() {
val tempDir = createTempDir(suffix = "-${this.javaClass.simpleName}")
val originsFile = File(tempDir, "origins.yml")
val LOGGER = LoggerFactory.getLogger(OriginsFileCompatibilitySpec::class.java)
val styxServer = StyxServerProvider(
defaultConfig = """
---
proxy:
connectors:
http:
port: 0
admin:
connectors:
http:
port: 0
providers:
originsFileLoader:
type: YamlFileConfigurationService
config:
originsFile: ${originsFile.absolutePath}
ingressObject: pathPrefixRouter
monitor: True
pollInterval: PT0.1S
httpPipeline: pathPrefixRouter
""".trimIndent(),
defaultLoggingConfig = ResourcePaths.fixturesHome(
OriginsFileCompatibilitySpec::class.java,
"/conf/logback/logback.xml")
.toAbsolutePath())
init {
context("Origin metrics in backwards compatibility mode") {
writeOrigins("""
- id: appA
path: "/"
origins:
- { id: "appA-01", host: "localhost:${mockServerA01.port()}" }
""".trimIndent())
styxServer.restart()
test("Connection pool metrics path") {
eventually(2.seconds, AssertionError::class.java) {
testClient.send(get("/")
.header(HOST, styxServer().proxyHttpHostHeader())
.build())
.wait().let {
it!!.status() shouldBe OK
it.bodyAs(UTF_8) shouldBe "appA-01"
}
}
eventually(1.seconds, AssertionError::class.java) {
val (name, _) = styxServer().metrics()
.toList()
.first { (name, _) -> name.contains("connectionspool".toRegex()) }
name shouldBe "origins.appA.appA-01.connectionspool.available-connections"
}
}
test("time-to-first-byte metrics are reported") {
styxServer().metrics().let {
(it["origins.appA.appA-01.requests.time-to-first-byte"]!!["count"] as Int) shouldBeGreaterThan 0
(it["origins.appA.appA-01.requests.time-to-first-byte"]!!["mean"] as Double) shouldBeGreaterThan 0.0
(it["origins.requests.time-to-first-byte"]!!["count"] as Int) shouldBeGreaterThan 0
(it["origins.requests.time-to-first-byte"]!!["mean"] as Double) shouldBeGreaterThan 0.0
}
}
}
}
internal fun writeOrigins(text: String, debug: Boolean = true) {
originsFile.writeText(text)
if (debug) {
LOGGER.info("new origins file: \n${originsFile.readText()}")
}
}
val mockServerA01 = MockOriginServer.create("appA", "appA-01", 0, HttpConnectorConfig(0))
.start()
.stub(WireMock.get(WireMock.urlMatching("/.*")), WireMock.aResponse()
.withStatus(200)
.withBody("appA-01"))
override fun afterSpec(spec: Spec) {
styxServer.stop()
tempDir.deleteRecursively()
mockServerA01.stop()
}
}
| apache-2.0 | 81a2bb6dab35bb6dde391e500de8eb64 | 37.940741 | 120 | 0.586837 | 4.783439 | false | true | false | false |
android/fit-samples | SyncKotlin/app/src/main/java/com/google/android/gms/fit/samples/synckotlin/Notifications.kt | 1 | 2885 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.fit.samples.synckotlin
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import kotlin.random.Random
const val CHANNEL_ID = "FitSync"
/**
* Class to provide notifications to the user for errors in syncing to Google Fit.
*/
class Notifications(private val context: Context) {
init {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = context.getString(R.string.channel_name)
val descriptionText = context.getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
fun showNotification(message: String) {
val intent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.small_icon)
.setContentTitle("FitSync sync failure")
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
with(NotificationManagerCompat.from(context)) {
// notificationId is a unique int for each notification that you must define
notify(Random.nextInt(), builder.build())
}
}
} | apache-2.0 | 010d2dfdcc702ca9b4e202b7ca6db30c | 39.083333 | 93 | 0.705373 | 4.873311 | false | false | false | false |
tonyofrancis/Fetch | fetch2/src/main/java/com/tonyodev/fetch2/util/NotificationUtils.kt | 1 | 3019 | package com.tonyodev.fetch2.util
import android.content.Context
import android.content.Intent
import com.tonyodev.fetch2.*
fun onDownloadNotificationActionTriggered(context: Context?, intent: Intent?, fetchNotificationManager: FetchNotificationManager) {
if (context != null && intent != null) {
val namespace = intent.getStringExtra(EXTRA_NAMESPACE)
val downloadId = intent.getIntExtra(EXTRA_DOWNLOAD_ID, DOWNLOAD_ID_INVALID)
val actionType = intent.getIntExtra(EXTRA_ACTION_TYPE, ACTION_TYPE_INVALID)
val notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, NOTIFICATION_ID_INVALID)
val notificationGroupId = intent.getIntExtra(EXTRA_NOTIFICATION_GROUP_ID, NOTIFICATION_GROUP_ID_INVALID)
val isGroupAction = intent.getBooleanExtra(EXTRA_GROUP_ACTION, false)
val downloadNotifications = intent.getParcelableArrayListExtra(EXTRA_DOWNLOAD_NOTIFICATIONS)
?: emptyList<DownloadNotification>()
if (!isGroupAction) {
if (!namespace.isNullOrEmpty() && downloadId != DOWNLOAD_ID_INVALID && actionType != ACTION_TYPE_INVALID) {
val fetch = fetchNotificationManager.getFetchInstanceForNamespace(namespace)
if (!fetch.isClosed) {
when (actionType) {
ACTION_TYPE_CANCEL -> fetch.cancel(downloadId)
ACTION_TYPE_DELETE -> fetch.delete(downloadId)
ACTION_TYPE_PAUSE -> fetch.pause(downloadId)
ACTION_TYPE_RESUME -> fetch.resume(downloadId)
ACTION_TYPE_RETRY -> fetch.retry(downloadId)
else -> {
//do nothing
}
}
}
}
} else {
if (notificationGroupId != NOTIFICATION_GROUP_ID_INVALID && downloadNotifications.isNotEmpty()) {
downloadNotifications.groupBy { it.namespace }.forEach { entry ->
val fetchNamespace = entry.key
val downloadIds = entry.value.map { downloadNotification ->
downloadNotification.notificationId
}
val fetch = fetchNotificationManager.getFetchInstanceForNamespace(fetchNamespace)
if (!fetch.isClosed) {
when (actionType) {
ACTION_TYPE_CANCEL_ALL -> fetch.cancel(downloadIds)
ACTION_TYPE_DELETE_ALL -> fetch.delete(downloadIds)
ACTION_TYPE_PAUSE_ALL -> fetch.pause(downloadIds)
ACTION_TYPE_RESUME_ALL -> fetch.resume(downloadIds)
ACTION_TYPE_RETRY_ALL -> fetch.retry(downloadIds)
else -> {
//do nothing
}
}
}
}
}
}
}
} | apache-2.0 | c39f2548ad25ed4ce118e1aff8c1c5b8 | 51.982456 | 131 | 0.558132 | 5.529304 | false | false | false | false |
gradle/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/jos/JavaSerializationEncodingLookup.kt | 3 | 3255 | /*
* Copyright 2021 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.configurationcache.serialization.codecs.jos
import org.gradle.configurationcache.serialization.codecs.Encoding
import org.gradle.internal.service.scopes.Scopes
import org.gradle.internal.service.scopes.ServiceScope
import java.io.ObjectOutputStream
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.util.concurrent.ConcurrentHashMap
@ServiceScope(Scopes.BuildTree::class)
internal
class JavaSerializationEncodingLookup {
private
val encodings = ConcurrentHashMap<Class<*>, EncodingDetails>()
fun encodingFor(type: Class<*>): Encoding? {
return encodings.computeIfAbsent(type) { t -> calculateEncoding(t) }.encoding
}
private
fun calculateEncoding(type: Class<*>): EncodingDetails {
val candidates = type.allMethods()
val encoding = writeReplaceEncodingFor(candidates)
?: readResolveEncodingFor(candidates)
?: writeObjectEncodingFor(candidates)
?: readObjectEncodingFor(candidates)
return EncodingDetails(encoding)
}
private
fun writeReplaceEncodingFor(candidates: List<Method>) =
writeReplaceMethodFrom(candidates)
?.let(JavaObjectSerializationCodec::WriteReplaceEncoding)
private
fun readResolveEncodingFor(candidates: List<Method>) =
readResolveMethodFrom(candidates)
?.let { JavaObjectSerializationCodec.ReadResolveEncoding }
private
fun writeObjectEncodingFor(candidates: List<Method>): Encoding? =
writeObjectMethodHierarchyFrom(candidates)
.takeIf { it.isNotEmpty() }
?.let(JavaObjectSerializationCodec::WriteObjectEncoding)
private
fun readObjectEncodingFor(candidates: List<Method>): Encoding? =
readObjectMethodHierarchyFrom(candidates)
.takeIf { it.isNotEmpty() }
?.let { JavaObjectSerializationCodec.ReadObjectEncoding }
private
fun writeReplaceMethodFrom(candidates: List<Method>) =
candidates.firstAccessibleMatchingMethodOrNull {
!Modifier.isStatic(modifiers)
&& parameterCount == 0
&& returnType == java.lang.Object::class.java
&& name == "writeReplace"
}
private
fun writeObjectMethodHierarchyFrom(candidates: List<Method>) = candidates
.serializationMethodHierarchy("writeObject", ObjectOutputStream::class.java)
private
fun readResolveMethodFrom(candidates: List<Method>) =
candidates.find {
it.isReadResolve()
}
private
class EncodingDetails(
val encoding: Encoding?
)
}
| apache-2.0 | 18a3556aa1c6787f6b4e205a6320d164 | 34 | 85 | 0.709063 | 4.850969 | false | false | false | false |
Stargamers/FastHub | app/src/main/java/com/fastaccess/ui/widgets/markdown/MarkDownLayout.kt | 5 | 7501 | package com.fastaccess.ui.widgets.markdown
import android.annotation.SuppressLint
import android.content.Context
import android.support.design.widget.Snackbar
import android.support.transition.TransitionManager
import android.support.v4.app.FragmentManager
import android.util.AttributeSet
import android.view.View
import android.widget.EditText
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.fastaccess.R
import com.fastaccess.helper.AppHelper
import com.fastaccess.helper.InputHelper
import com.fastaccess.helper.ViewHelper
import com.fastaccess.provider.emoji.Emoji
import com.fastaccess.provider.markdown.MarkDownProvider
import com.fastaccess.ui.modules.editor.emoji.EmojiBottomSheet
import com.fastaccess.ui.modules.editor.popup.EditorLinkImageDialogFragment
/**
* Created by kosh on 11/08/2017.
*/
class MarkDownLayout : LinearLayout {
private val sentFromFastHub: String by lazy {
"\n\n_" + resources.getString(R.string.sent_from_fasthub, AppHelper.getDeviceName(), "",
"[" + resources.getString(R.string.app_name) + "](https://play.google.com/store/apps/details?id=com.fastaccess.github)") + "_"
}
var markdownListener: MarkdownListener? = null
var selectionIndex = 0
@BindView(R.id.editorIconsHolder) lateinit var editorIconsHolder: HorizontalScrollView
@BindView(R.id.addEmoji) lateinit var addEmojiView: View
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onFinishInflate() {
super.onFinishInflate()
orientation = HORIZONTAL
View.inflate(context, R.layout.markdown_buttons_layout, this)
if (isInEditMode) return
ButterKnife.bind(this)
}
override fun onDetachedFromWindow() {
markdownListener = null
super.onDetachedFromWindow()
}
@OnClick(R.id.view) fun onViewMarkDown() {
markdownListener?.let {
it.getEditText().let { editText ->
TransitionManager.beginDelayedTransition(this)
if (editText.isEnabled && !InputHelper.isEmpty(editText)) {
editText.isEnabled = false
selectionIndex = editText.selectionEnd
MarkDownProvider.setMdText(editText, InputHelper.toString(editText))
editorIconsHolder.visibility = View.INVISIBLE
addEmojiView.visibility = View.INVISIBLE
ViewHelper.hideKeyboard(editText)
} else {
editText.setText(it.getSavedText())
editText.setSelection(selectionIndex)
editText.isEnabled = true
editorIconsHolder.visibility = View.VISIBLE
addEmojiView.visibility = View.VISIBLE
ViewHelper.showKeyboard(editText)
}
}
}
}
@OnClick(R.id.headerOne, R.id.headerTwo, R.id.headerThree, R.id.bold, R.id.italic, R.id.strikethrough,
R.id.bullet, R.id.header, R.id.code, R.id.numbered, R.id.quote, R.id.link, R.id.image,
R.id.unCheckbox, R.id.checkbox, R.id.inlineCode, R.id.addEmoji,
R.id.signature)
fun onActions(v: View) {
markdownListener?.let {
it.getEditText().let { editText ->
if (!editText.isEnabled) {
Snackbar.make(this, R.string.error_highlighting_editor, Snackbar.LENGTH_SHORT).show()
} else {
when {
v.id == R.id.link -> EditorLinkImageDialogFragment.newInstance(true, getSelectedText())
.show(it.fragmentManager(), "EditorLinkImageDialogFragment")
v.id == R.id.image -> EditorLinkImageDialogFragment.newInstance(false, getSelectedText())
.show(it.fragmentManager(), "EditorLinkImageDialogFragment")
v.id == R.id.addEmoji -> {
ViewHelper.hideKeyboard(it.getEditText())
EmojiBottomSheet().show(it.fragmentManager(), "EmojiBottomSheet")
}
else -> onActionClicked(editText, v.id)
}
}
}
}
}
@SuppressLint("SetTextI18n")
private fun onActionClicked(editText: EditText, id: Int) {
if (editText.selectionEnd == -1 || editText.selectionStart == -1) {
return
}
when (id) {
R.id.headerOne -> MarkDownProvider.addHeader(editText, 1)
R.id.headerTwo -> MarkDownProvider.addHeader(editText, 2)
R.id.headerThree -> MarkDownProvider.addHeader(editText, 3)
R.id.bold -> MarkDownProvider.addBold(editText)
R.id.italic -> MarkDownProvider.addItalic(editText)
R.id.strikethrough -> MarkDownProvider.addStrikeThrough(editText)
R.id.numbered -> MarkDownProvider.addList(editText, "1.")
R.id.bullet -> MarkDownProvider.addList(editText, "-")
R.id.header -> MarkDownProvider.addDivider(editText)
R.id.code -> MarkDownProvider.addCode(editText)
R.id.quote -> MarkDownProvider.addQuote(editText)
R.id.checkbox -> MarkDownProvider.addList(editText, "- [x]")
R.id.unCheckbox -> MarkDownProvider.addList(editText, "- [ ]")
R.id.inlineCode -> MarkDownProvider.addInlinleCode(editText)
R.id.signature -> {
markdownListener?.getEditText()?.let {
if (!it.text.toString().contains(sentFromFastHub)) {
it.setText("${it.text}$sentFromFastHub")
} else {
it.setText(it.text.toString().replace(sentFromFastHub, ""))
}
editText.setSelection(it.text.length)
editText.requestFocus()
}
}
}
}
fun onEmojiAdded(emoji: Emoji?) {
markdownListener?.getEditText()?.let { editText ->
ViewHelper.showKeyboard(editText)
emoji?.let {
MarkDownProvider.insertAtCursor(editText, ":${it.aliases[0]}:")
}
}
}
interface MarkdownListener {
fun getEditText(): EditText
fun fragmentManager(): FragmentManager
fun getSavedText(): CharSequence?
}
fun onAppendLink(title: String?, link: String?, isLink: Boolean) {
markdownListener?.let {
if (isLink) {
MarkDownProvider.addLink(it.getEditText(), InputHelper.toString(title), InputHelper.toString(link))
} else {
MarkDownProvider.addPhoto(it.getEditText(), InputHelper.toString(title), InputHelper.toString(link))
}
}
}
private fun getSelectedText(): String? {
markdownListener?.getEditText()?.let {
if (!it.text.toString().isBlank()) {
val selectionStart = it.selectionStart
val selectionEnd = it.selectionEnd
return it.text.toString().substring(selectionStart, selectionEnd)
}
}
return null
}
} | gpl-3.0 | b29c3f01332b68b46357bc1555e32704 | 41.868571 | 142 | 0.611652 | 4.656114 | false | false | false | false |
BenoitDuffez/AndroidCupsPrint | app/src/main/java/io/github/benoitduffez/cupsprint/ssl/AdditionalKeyStoresSSLSocketFactory.kt | 1 | 2851 | package io.github.benoitduffez.cupsprint.ssl
import java.io.IOException
import java.net.InetAddress
import java.net.Socket
import java.security.KeyManagementException
import java.security.KeyStore
import java.security.KeyStoreException
import java.security.NoSuchAlgorithmException
import java.security.UnrecoverableKeyException
import java.security.cert.X509Certificate
import javax.net.ssl.KeyManager
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
/**
* Allows you to trust certificates from additional KeyStores in addition to
* the default KeyStore
*/
class AdditionalKeyStoresSSLSocketFactory
/**
* Create the SSL socket factory
*
* @param keyManager Key manager, can be null
* @param keyStore Keystore, can't be null
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
*/
@Throws(NoSuchAlgorithmException::class, KeyManagementException::class, KeyStoreException::class, UnrecoverableKeyException::class)
constructor(keyManager: KeyManager?, keyStore: KeyStore) : SSLSocketFactory() {
private val sslContext = SSLContext.getInstance("TLS")
private val trustManager: AdditionalKeyStoresTrustManager = AdditionalKeyStoresTrustManager(keyStore)
val serverCert: Array<X509Certificate>?
get() = trustManager.certChain
init {
// Ensure we don't pass an empty array. Array must contain a valid key manager, or must be null
val managers: Array<KeyManager>? = when (keyManager) {
null -> null
else -> arrayOf(keyManager)
}
sslContext.init(managers, arrayOf<TrustManager>(trustManager), null)
}
override fun getDefaultCipherSuites(): Array<String?> = arrayOfNulls(0)
override fun getSupportedCipherSuites(): Array<String?> = arrayOfNulls(0)
@Throws(IOException::class)
override fun createSocket(socket: Socket, host: String, port: Int, autoClose: Boolean): Socket =
sslContext.socketFactory.createSocket(socket, host, port, autoClose)
@Throws(IOException::class)
override fun createSocket(s: String, i: Int): Socket =
sslContext.socketFactory.createSocket(s, i)
@Throws(IOException::class)
override fun createSocket(s: String, i: Int, inetAddress: InetAddress, i1: Int): Socket =
sslContext.socketFactory.createSocket(s, i, inetAddress, i1)
@Throws(IOException::class)
override fun createSocket(inetAddress: InetAddress, i: Int): Socket =
sslContext.socketFactory.createSocket(inetAddress, i)
@Throws(IOException::class)
override fun createSocket(inetAddress: InetAddress, i: Int, inetAddress1: InetAddress, i1: Int): Socket =
sslContext.socketFactory.createSocket(inetAddress, i, inetAddress1, i1)
}
| lgpl-3.0 | 8ffb89c067f07826605d96338f353a90 | 38.054795 | 131 | 0.749562 | 4.576244 | false | false | false | false |
AlmasB/FXGL | fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/achievement/AchievementService.kt | 1 | 5879 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.achievement
import com.almasb.fxgl.core.EngineService
import com.almasb.fxgl.core.Inject
import com.almasb.fxgl.core.collection.PropertyChangeListener
import com.almasb.fxgl.core.collection.PropertyMap
import com.almasb.fxgl.core.serialization.Bundle
import com.almasb.fxgl.event.EventBus
import com.almasb.fxgl.logging.Logger
import com.almasb.fxgl.scene.SceneService
import java.util.*
/**
* Responsible for registering and updating achievements.
* Achievements can only be registered via Settings, before the engine starts.
*
* @author Almas Baimagambetov (AlmasB) ([email protected])
*/
class AchievementService : EngineService() {
private val log = Logger.get(javaClass)
// this is a read-only list as populated by the user
@Inject("achievements")
private lateinit var achievementsFromSettings: List<Achievement>
private lateinit var sceneService: SceneService
private lateinit var eventBus: EventBus
private val achievements = mutableListOf<Achievement>()
/**
* @return unmodifiable list of achievements
*/
val achievementsCopy: List<Achievement>
get() = Collections.unmodifiableList(achievements)
override fun onInit() {
eventBus = sceneService.eventBus
}
/**
* @param name achievement name
* @return registered achievement
* @throws IllegalArgumentException if achievement is not registered
*/
fun getAchievementByName(name: String): Achievement {
return achievements.find { it.name == name }
?: throw IllegalArgumentException("Achievement with name [$name] is not registered!")
}
/**
* Registers achievement in the system.
*
* @param a the achievement
*/
internal fun registerAchievement(a: Achievement) {
require(achievements.none { it.name == a.name }) {
"Achievement with name [${a.name}] exists"
}
achievements.add(a)
log.debug("Registered new achievement: ${a.name}")
}
override fun onMainLoopStarting() {
achievementsFromSettings.forEach { registerAchievement(it) }
}
override fun onGameReady(vars: PropertyMap) {
bindToVars(vars)
}
internal fun bindToVars(vars: PropertyMap) {
// only interested in non-achieved achievements
achievements.filter { !it.isAchieved }.forEach {
if (!vars.exists(it.varName)) {
log.warning("Achievement ${it.name} cannot find property ${it.varName}")
} else {
when (it.varValue) {
is Int -> {
registerIntAchievement(vars, it, it.varValue)
}
is Double -> {
registerDoubleAchievement(vars, it, it.varValue)
}
is Boolean -> {
registerBooleanAchievement(vars, it, it.varValue)
}
else -> throw IllegalArgumentException("Unknown value type for achievement: " + it.varValue)
}
}
}
}
private fun registerIntAchievement(vars: PropertyMap, a: Achievement, value: Int) {
var listener: PropertyChangeListener<Int>? = null
listener = object : PropertyChangeListener<Int> {
private var halfReached = false
override fun onChange(prev: Int, now: Int) {
if (!halfReached && now >= value / 2) {
halfReached = true
eventBus.fireEvent(AchievementProgressEvent(a, now.toDouble(), value.toDouble()))
}
if (now >= value) {
a.setAchieved()
eventBus.fireEvent(AchievementEvent(AchievementEvent.ACHIEVED, a))
vars.removeListener(a.varName, listener!!)
}
}
}
vars.addListener(a.varName, listener)
}
private fun registerDoubleAchievement(vars: PropertyMap, a: Achievement, value: Double) {
var listener: PropertyChangeListener<Double>? = null
listener = object : PropertyChangeListener<Double> {
private var halfReached = false
override fun onChange(prev: Double, now: Double) {
if (!halfReached && now >= value / 2) {
halfReached = true
eventBus.fireEvent(AchievementProgressEvent(a, now, value))
}
if (now >= value) {
a.setAchieved()
eventBus.fireEvent(AchievementEvent(AchievementEvent.ACHIEVED, a))
vars.removeListener(a.varName, listener!!)
}
}
}
vars.addListener(a.varName, listener)
}
private fun registerBooleanAchievement(vars: PropertyMap, a: Achievement, value: Boolean) {
var listener: PropertyChangeListener<Boolean>? = null
listener = object : PropertyChangeListener<Boolean> {
override fun onChange(prev: Boolean, now: Boolean) {
if (now == value) {
a.setAchieved()
eventBus.fireEvent(AchievementEvent(AchievementEvent.ACHIEVED, a))
vars.removeListener(a.varName, listener!!)
}
}
}
vars.addListener(a.varName, listener)
}
override fun write(bundle: Bundle) {
achievements.forEach { bundle.put(it.name, it.isAchieved) }
}
override fun read(bundle: Bundle) {
achievements.forEach {
val isAchieved = bundle.get<Boolean>(it.name)
if (isAchieved)
it.setAchieved()
}
}
} | mit | d5087123d1c68b8034a27e27947e93ff | 30.612903 | 112 | 0.59619 | 4.891015 | false | false | false | false |
ColaGom/KtGitCloner | src/main/kotlin/ml/Cluster.kt | 1 | 1821 | package ml
import com.google.gson.*
import java.lang.reflect.Type
class Cluster(val nodeList:List<Node>) {
var centroid:Int = 0
set(value) {
memberList.add(value)
}
val memberList : MutableSet<Int> = mutableSetOf()
fun addMember(member: Int) {
memberList.add(member)
}
fun addMember(list: Set<Int>)
{
memberList.addAll(list)
}
fun mean(): Double {
var sum = 0.0
memberList.parallelStream().forEach {
sum += nodeList.get(centroid).distanceTo(nodeList.get(it))
}
return sum / size()
}
fun getNodes() : List<Node>
{
return nodeList.filterIndexed { index, node -> memberList.contains(index) }
}
fun getCentroid() : Node
{
return nodeList.get(centroid)
}
fun updateCentroid() : Boolean {
val nodes = getNodes()
var maxValue = Double.MIN_VALUE
var maxIdx = 0
nodes.forEachIndexed { index, node ->
val current = node.mean(nodes)
if(current > maxValue)
{
maxValue = current
maxIdx = index
}
}
if(centroid != maxIdx) {
centroid = maxIdx
return true
}
return false
}
fun clearMember() {
memberList.removeIf{
!it.equals(centroid)
}
centroid = 0
}
fun size() = memberList.size
}
class SimpleSerializer : JsonSerializer<Any>
{
override fun serialize(src: Any?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
if(src is Node)
{
val json = JsonObject()
json.addProperty("fileName", src.fileName);
return json
}
return Gson().toJsonTree(src)
}
}
| apache-2.0 | 6d6a4e6d61a00735daabba813242bc6c | 19.931034 | 106 | 0.542559 | 4.377404 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/database/table/RPKTimedStoreItemTable.kt | 1 | 5646 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.store.bukkit.database.table
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.store.bukkit.RPKStoresBukkit
import com.rpkit.store.bukkit.database.create
import com.rpkit.store.bukkit.database.jooq.Tables.RPKIT_STORE_ITEM
import com.rpkit.store.bukkit.database.jooq.Tables.RPKIT_TIMED_STORE_ITEM
import com.rpkit.store.bukkit.storeitem.RPKStoreItemId
import com.rpkit.store.bukkit.storeitem.RPKTimedStoreItem
import com.rpkit.store.bukkit.storeitem.RPKTimedStoreItemImpl
import java.time.Duration
import java.util.concurrent.CompletableFuture
import java.util.logging.Level
class RPKTimedStoreItemTable(
private val database: Database,
private val plugin: RPKStoresBukkit
) : Table {
private val cache = if (plugin.config.getBoolean("caching.rpkit_timed_store_item.id.enabled")) {
database.cacheManager.createCache(
"rpkit-stores-bukkit.rpkit_timed_store_item.id",
Int::class.javaObjectType,
RPKTimedStoreItem::class.java,
plugin.config.getLong("caching.rpkit_consumable_purchase.id.size")
)
} else {
null
}
fun insert(entity: RPKTimedStoreItem): CompletableFuture<Void> {
return CompletableFuture.runAsync {
val id = database.getTable(RPKStoreItemTable::class.java).insert(entity).join()
database.create
.insertInto(
RPKIT_TIMED_STORE_ITEM,
RPKIT_TIMED_STORE_ITEM.STORE_ITEM_ID,
RPKIT_TIMED_STORE_ITEM.DURATION
)
.values(
id.value,
entity.duration.seconds
)
.execute()
entity.id = id
cache?.set(id.value, entity)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to insert timed store item", exception)
throw exception
}
}
fun update(entity: RPKTimedStoreItem): CompletableFuture<Void> {
val id = entity.id ?: return CompletableFuture.completedFuture(null)
return CompletableFuture.runAsync {
database.getTable(RPKStoreItemTable::class.java).update(entity).join()
database.create
.update(RPKIT_TIMED_STORE_ITEM)
.set(RPKIT_TIMED_STORE_ITEM.DURATION, entity.duration.seconds)
.where(RPKIT_TIMED_STORE_ITEM.STORE_ITEM_ID.eq(id.value))
.execute()
cache?.set(id.value, entity)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to update timed store item", exception)
throw exception
}
}
operator fun get(id: RPKStoreItemId): CompletableFuture<out RPKTimedStoreItem?> {
if (cache?.containsKey(id.value) == true) {
return CompletableFuture.completedFuture(cache[id.value])
} else {
return CompletableFuture.supplyAsync {
val result = database.create
.select(
RPKIT_STORE_ITEM.PLUGIN,
RPKIT_STORE_ITEM.IDENTIFIER,
RPKIT_STORE_ITEM.DESCRIPTION,
RPKIT_STORE_ITEM.COST,
RPKIT_TIMED_STORE_ITEM.DURATION
)
.from(
RPKIT_STORE_ITEM,
RPKIT_TIMED_STORE_ITEM
)
.where(RPKIT_STORE_ITEM.ID.eq(id.value))
.and(RPKIT_STORE_ITEM.ID.eq(RPKIT_TIMED_STORE_ITEM.ID))
.fetchOne() ?: return@supplyAsync null
val storeItem = RPKTimedStoreItemImpl(
id,
Duration.ofSeconds(result[RPKIT_TIMED_STORE_ITEM.DURATION]),
result[RPKIT_STORE_ITEM.PLUGIN],
result[RPKIT_STORE_ITEM.IDENTIFIER],
result[RPKIT_STORE_ITEM.DESCRIPTION],
result[RPKIT_STORE_ITEM.COST]
)
cache?.set(id.value, storeItem)
return@supplyAsync storeItem
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get timed store item", exception)
throw exception
}
}
}
fun delete(entity: RPKTimedStoreItem): CompletableFuture<Void> {
val id = entity.id ?: return CompletableFuture.completedFuture(null)
return CompletableFuture.runAsync {
database.getTable(RPKStoreItemTable::class.java).delete(entity).join()
database.create
.deleteFrom(RPKIT_TIMED_STORE_ITEM)
.where(RPKIT_TIMED_STORE_ITEM.ID.eq(id.value))
.execute()
cache?.remove(id.value)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to delete timed store item", exception)
throw exception
}
}
} | apache-2.0 | 256cbc733851300f85c4a65cbafcdd10 | 39.625899 | 100 | 0.603613 | 4.627869 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/set/CharacterSetDeadCommand.kt | 1 | 9461 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.characters.bukkit.command.character.set
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
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.conversations.*
import org.bukkit.entity.Player
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
/**
* Character set dead command.
* Sets character's dead state.
*/
class CharacterSetDeadCommand(private val plugin: RPKCharactersBukkit) : CommandExecutor {
private val conversationFactory: ConversationFactory
init {
conversationFactory = ConversationFactory(plugin)
.withModality(true)
.withFirstPrompt(DeadPrompt())
.withEscapeSequence("cancel")
.thatExcludesNonPlayersWithMessage(plugin.messages["not-from-console"])
.addConversationAbandonedListener { event ->
if (!event.gracefulExit()) {
val conversable = event.context.forWhom
if (conversable is Player) {
conversable.sendMessage(plugin.messages["operation-cancelled"])
}
}
}
}
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
if (!sender.hasPermission("rpkit.characters.command.character.set.dead")) {
sender.sendMessage(plugin.messages["no-permission-character-set-dead"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages["no-character-service"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
sender.sendMessage(plugin.messages["no-character"])
return true
}
if (args.isEmpty()) {
conversationFactory.buildConversation(sender).begin()
return true
}
val dead = args[0].toBoolean()
if (dead && sender.hasPermission("rpkit.characters.command.character.set.dead.yes") || !dead && sender.hasPermission("rpkit.characters.command.character.set.dead.no")) {
character.isDead = dead
characterService.updateCharacter(character).thenAccept { updatedCharacter ->
sender.sendMessage(plugin.messages["character-set-dead-valid"])
updatedCharacter?.showCharacterCard(minecraftProfile)
plugin.server.scheduler.runTask(plugin, Runnable {
if (dead) {
sender.addPotionEffect(PotionEffect(PotionEffectType.BLINDNESS, 1000000, 0))
sender.addPotionEffect(PotionEffect(PotionEffectType.SLOW, 1000000, 255))
} else {
sender.removePotionEffect(PotionEffectType.BLINDNESS)
sender.removePotionEffect(PotionEffectType.SLOW)
}
})
}
} else {
sender.sendMessage(plugin.messages["no-permission-character-set-dead-" + if (dead) "yes" else "no"])
return true
}
return true
}
private inner class DeadPrompt : BooleanPrompt() {
override fun acceptValidatedInput(context: ConversationContext, input: Boolean): Prompt {
val conversable = context.forWhom
if (conversable !is Player) return DeadSetPrompt()
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return DeadSetPrompt()
val characterService = Services[RPKCharacterService::class.java] ?: return DeadSetPrompt()
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(conversable) ?: return DeadSetPrompt()
val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return DeadSetPrompt()
return if (input && conversable.hasPermission("rpkit.characters.command.character.set.dead.yes") || !input && conversable.hasPermission("rpkit.characters.command.character.set.dead.no")) {
character.isDead = input
characterService.updateCharacter(character)
if (input) {
conversable.addPotionEffect(PotionEffect(PotionEffectType.BLINDNESS, 1000000, 0))
conversable.addPotionEffect(PotionEffect(PotionEffectType.SLOW, 1000000, 255))
} else {
conversable.removePotionEffect(PotionEffectType.BLINDNESS)
conversable.removePotionEffect(PotionEffectType.SLOW)
}
DeadSetPrompt()
} else {
DeadNotSetNoPermissionPrompt(input)
}
}
override fun getFailedValidationText(context: ConversationContext, invalidInput: String): String {
return plugin.messages["character-set-dead-invalid-boolean"]
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["character-set-dead-prompt"]
}
}
private inner class DeadSetPrompt : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt? {
val conversable = context.forWhom
if (conversable is Player) {
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
conversable.sendMessage(plugin.messages["no-minecraft-profile-service"])
return END_OF_CONVERSATION
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
conversable.sendMessage(plugin.messages["no-character-service"])
return END_OF_CONVERSATION
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(context.forWhom as Player)
if (minecraftProfile != null) {
characterService.getPreloadedActiveCharacter(minecraftProfile)?.showCharacterCard(minecraftProfile)
}
}
return Prompt.END_OF_CONVERSATION
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["character-set-dead-valid"]
}
}
private inner class DeadNotSetNoPermissionPrompt(private val dead: Boolean) : MessagePrompt() {
override fun getNextPrompt(context: ConversationContext): Prompt? {
val conversable = context.forWhom
if (conversable is Player) {
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
conversable.sendMessage(plugin.messages["no-minecraft-profile-service"])
return END_OF_CONVERSATION
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
conversable.sendMessage(plugin.messages["no-character-service"])
return END_OF_CONVERSATION
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(context.forWhom as Player)
if (minecraftProfile != null) {
characterService.getPreloadedActiveCharacter(minecraftProfile)?.showCharacterCard(minecraftProfile)
}
}
return END_OF_CONVERSATION
}
override fun getPromptText(context: ConversationContext): String {
return plugin.messages["no-permission-character-set-dead-" + if (dead) "yes" else "no"]
}
}
}
| apache-2.0 | 3e536e53df777649b7fd624f12a782bc | 45.605911 | 200 | 0.639679 | 5.478286 | false | false | false | false |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/upload/UploadRepositoryUnitTest.kt | 5 | 9921 | package fr.free.nrw.commons.upload
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.category.CategoriesModel
import fr.free.nrw.commons.category.CategoryItem
import fr.free.nrw.commons.contributions.Contribution
import fr.free.nrw.commons.contributions.ContributionDao
import fr.free.nrw.commons.filepicker.UploadableFile
import fr.free.nrw.commons.location.LatLng
import fr.free.nrw.commons.nearby.NearbyPlaces
import fr.free.nrw.commons.nearby.Place
import fr.free.nrw.commons.repository.UploadRepository
import fr.free.nrw.commons.upload.structure.depictions.DepictModel
import fr.free.nrw.commons.upload.structure.depictions.DepictedItem
import io.reactivex.Completable
import io.reactivex.Single
import org.junit.Before
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertEquals
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.MockitoAnnotations
import java.lang.reflect.Method
class UploadRepositoryUnitTest {
private lateinit var repository: UploadRepository
@Mock
private lateinit var uploadModel: UploadModel
@Mock
private lateinit var uploadController: UploadController
@Mock
private lateinit var categoriesModel: CategoriesModel
@Mock
private lateinit var nearbyPlaces: NearbyPlaces
@Mock
private lateinit var depictModel: DepictModel
@Mock
private lateinit var contributionDao: ContributionDao
@Mock
private lateinit var contribution: Contribution
@Mock
private lateinit var completable: Completable
@Mock
private lateinit var categoryItem: CategoryItem
@Mock
private lateinit var uploadableFile: UploadableFile
@Mock
private lateinit var place: Place
@Mock
private lateinit var similarImageInterface: SimilarImageInterface
@Mock
private lateinit var uploadItem: UploadItem
@Mock
private lateinit var depictedItem: DepictedItem
@Mock
private lateinit var imageCoordinates: ImageCoordinates
@Mock
private lateinit var media: Media
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
repository = UploadRepository(
uploadModel,
uploadController,
categoriesModel,
nearbyPlaces,
depictModel,
contributionDao
)
`when`(contributionDao.save(contribution)).thenReturn(completable)
}
@Test
fun testBuildContributions() {
assertEquals(repository.buildContributions(), uploadModel.buildContributions())
}
@Test
fun testPrepareMedia() {
assertEquals(
repository.prepareMedia(contribution),
uploadController.prepareMedia(contribution)
)
}
@Test
fun testSaveContribution() {
assertEquals(
repository.saveContribution(contribution),
contributionDao.save(contribution).blockingAwait()
)
}
@Test
fun testGetUploads() {
assertEquals(repository.uploads, uploadModel.uploads)
}
@Test
fun testCleanup() {
repository.cleanup()
verify(uploadModel).cleanUp()
verify(categoriesModel).cleanUp()
verify(depictModel).cleanUp()
}
@Test
fun testGetSelectedCategories() {
assertEquals(repository.selectedCategories, categoriesModel.getSelectedCategories())
}
@Test
fun testSearchAll() {
assertEquals(
repository.searchAll("", listOf(), listOf()),
categoriesModel.searchAll("", listOf(), listOf())
)
}
@Test
fun testSetSelectedCategories() {
repository.setSelectedCategories(listOf())
verify(uploadModel).setSelectedCategories(listOf())
}
@Test
fun testOnCategoryClicked() {
repository.onCategoryClicked(categoryItem, media)
verify(categoriesModel).onCategoryItemClicked(categoryItem, media)
}
@Test
fun testContainsYear() {
assertEquals(
repository.containsYear(""), categoriesModel.containsYear("")
)
}
@Test
fun testGetLicenses() {
assertEquals(repository.licenses, uploadModel.licenses)
}
@Test
fun testGetSelectedLicense() {
assertEquals(repository.selectedLicense, uploadModel.selectedLicense)
}
@Test
fun testGetCount() {
assertEquals(repository.count, uploadModel.count)
}
@Test
fun testPreProcessImage() {
assertEquals(
repository.preProcessImage(uploadableFile, place, similarImageInterface),
uploadModel.preProcessImage(uploadableFile, place, similarImageInterface)
)
}
@Test
fun testGetImageQuality() {
assertEquals(
repository.getImageQuality(uploadItem),
uploadModel.getImageQuality(uploadItem)
)
}
@Test
fun testDeletePicture() {
assertEquals(repository.deletePicture(""), uploadModel.deletePicture(""))
}
@Test
fun testGetUploadItemCaseNonNull() {
`when`(uploadModel.items).thenReturn(listOf(uploadItem))
assertEquals(
repository.getUploadItem(0),
uploadModel.items[0]
)
}
@Test
fun testGetUploadItemCaseNull() {
assertEquals(repository.getUploadItem(-1), null)
}
@Test
fun testSetSelectedLicense() {
assertEquals(repository.setSelectedLicense(""), uploadModel.setSelectedLicense(""))
}
@Test
fun testSetSelectedExistingDepictions() {
assertEquals(repository.setSelectedExistingDepictions(listOf("")),
uploadModel.setSelectedExistingDepictions(listOf("")))
}
@Test
fun testOnDepictItemClicked() {
assertEquals(
repository.onDepictItemClicked(depictedItem, mock()),
uploadModel.onDepictItemClicked(depictedItem, mock())
)
}
@Test
fun testGetSelectedDepictions() {
assertEquals(repository.selectedDepictions, uploadModel.selectedDepictions)
}
@Test
fun testGetSelectedExistingDepictions() {
assertEquals(repository.selectedExistingDepictions, uploadModel.selectedExistingDepictions)
}
@Test
fun testSearchAllEntities() {
assertEquals(
repository.searchAllEntities(""),
depictModel.searchAllEntities("", repository)
)
}
@Test
fun testGetPlaceDepictions() {
`when`(uploadModel.uploads).thenReturn(listOf(uploadItem))
`when`(uploadItem.place).thenReturn(place)
`when`(place.wikiDataEntityId).thenReturn("1")
assertEquals(
repository.placeDepictions,
depictModel.getPlaceDepictions(listOf("1"))
)
}
@Test
fun testCheckNearbyPlacesWithoutExceptionCaseNonNull() {
`when`(
nearbyPlaces.getFromWikidataQuery(
LatLng(0.0, 0.0, 0.0f),
java.util.Locale.getDefault().language, 0.1,
false, null
)
).thenReturn(listOf(place))
assertEquals(
repository.checkNearbyPlaces(0.0, 0.0),
place
)
}
@Test
fun testCheckNearbyPlacesWithoutExceptionCaseNull() {
assertEquals(
repository.checkNearbyPlaces(0.0, 0.0),
null
)
}
@Test
fun testCheckNearbyPlacesWithException() {
`when`(
nearbyPlaces.getFromWikidataQuery(
LatLng(0.0, 0.0, 0.0f),
java.util.Locale.getDefault().language, 0.1,
false, null
)
).thenThrow(Exception())
assertEquals(
repository.checkNearbyPlaces(0.0, 0.0),
null
)
}
@Test
fun testUseSimilarPictureCoordinates() {
assertEquals(
repository.useSimilarPictureCoordinates(imageCoordinates, 0),
uploadModel.useSimilarPictureCoordinates(imageCoordinates, 0)
)
}
@Test
fun testIsWMLSupportedForThisPlace() {
`when`(uploadModel.items).thenReturn(listOf(uploadItem))
`when`(uploadItem.isWLMUpload).thenReturn(true)
assertEquals(
repository.isWMLSupportedForThisPlace,
true
)
}
@Test
fun testGetDepictions() {
`when`(depictModel.getDepictions("Q12"))
.thenReturn(Single.just(listOf(mock(DepictedItem::class.java))))
val method: Method = UploadRepository::class.java.getDeclaredMethod(
"getDepictions",
List::class.java
)
method.isAccessible = true
method.invoke(repository, listOf("Q12"))
}
@Test
fun testJoinIDs() {
val method: Method = UploadRepository::class.java.getDeclaredMethod(
"joinQIDs",
List::class.java
)
method.isAccessible = true
method.invoke(repository, listOf("Q12", "Q23"))
}
@Test
fun `test joinIDs when depictIDs is null`() {
val method: Method = UploadRepository::class.java.getDeclaredMethod(
"joinQIDs",
List::class.java
)
method.isAccessible = true
method.invoke(repository, null)
}
@Test
fun testGetSelectedExistingCategories() {
assertEquals(repository.selectedExistingCategories,
categoriesModel.getSelectedExistingCategories())
}
@Test
fun testSetSelectedExistingCategories() {
assertEquals(repository.setSelectedExistingCategories(listOf("Test")),
categoriesModel.setSelectedExistingCategories(mutableListOf("Test")))
}
@Test
fun testGetCategories() {
assertEquals(repository.getCategories(listOf("Test")),
categoriesModel.getCategoriesByName(mutableListOf("Test")))
}
} | apache-2.0 | 51cd4f5f3a73845e605471c8188855d6 | 26.333333 | 99 | 0.656083 | 4.970441 | false | true | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/unicodeKeyboard/recyclerAdapters/UnicodeMenuAdapter.kt | 1 | 2786 | package com.itachi1706.cheesecakeutilities.modules.unicodeKeyboard.recyclerAdapters
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.itachi1706.cheesecakeutilities.R
/**
* Created by Kenneth on 11/1/2020.
* for com.itachi1706.cheesecakeutilities.modules.unicodeKeyboard.recyclerAdapters in CheesecakeUtilities
*/
class UnicodeMenuAdapter(strings: List<String>) : RecyclerView.Adapter<UnicodeMenuAdapter.UnicodeMenuHolder>() {
private var stringList: List<String> = ArrayList()
init { stringList = strings }
constructor(string: Array<String>): this(string.toList())
override fun getItemCount(): Int { return stringList.size }
override fun onBindViewHolder(holder: UnicodeMenuHolder, position: Int) {
val s = stringList[position]
holder.title.text = s
holder.title.isSelected = true
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UnicodeMenuHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.recyclerview_default_simple_list_item_1, parent, false)
return UnicodeMenuHolder(itemView)
}
inner class UnicodeMenuHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener, View.OnLongClickListener {
var title: TextView = v.findViewById(R.id.text1)
init {
title.ellipsize = TextUtils.TruncateAt.MARQUEE
title.marqueeRepeatLimit = -1
title.setHorizontallyScrolling(true)
v.setOnClickListener(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) v.setOnLongClickListener(this)
}
override fun onClick(v: View) {
val clipboard = v.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = getClip()
clipboard.primaryClip = clip
Toast.makeText(v.context, "${clip.getItemAt(0).text}\ncopied to clipboard", Toast.LENGTH_LONG).show()
}
@RequiresApi(Build.VERSION_CODES.N)
override fun onLongClick(v: View): Boolean {
val dragShadowBuilder = View.DragShadowBuilder(v)
v.startDragAndDrop(getClip(), dragShadowBuilder, true, View.DRAG_FLAG_GLOBAL or View.DRAG_FLAG_GLOBAL_URI_READ or View.DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION)
return true
}
private fun getClip(): ClipData { return ClipData.newPlainText("unicode", title.text.toString()) }
}
} | mit | f65e1bf81d5c055802059674d89d281c | 39.985294 | 175 | 0.722541 | 4.415214 | false | false | false | false |
LorittaBot/Loritta | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/TickerPrices.kt | 1 | 588 | package net.perfectdreams.loritta.cinnamon.pudding.tables
import net.perfectdreams.exposedpowerutils.sql.javatime.timestampWithTimeZone
import org.jetbrains.exposed.dao.id.IdTable
object TickerPrices : IdTable<String>() {
val ticker = text("ticker").entityId()
val status = text("status").index()
val value = long("value")
val dailyPriceVariation = double("daily_price_variation")
val lastUpdatedAt = timestampWithTimeZone("last_updated_at")
val enabled = bool("enabled").default(true)
override val id = ticker
override val primaryKey = PrimaryKey(id)
} | agpl-3.0 | dbe9393bf3c6a7bd7ecb2c877f47db25 | 35.8125 | 77 | 0.746599 | 4.170213 | false | false | false | false |
googlecodelabs/admob-firebase-codelabs-android | 102-complete/app/src/main/java/com/google/codelab/awesomedrawingquiz/ui/splash/SplashViewModel.kt | 3 | 2569 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.codelab.awesomedrawingquiz.ui.splash
import android.content.SharedPreferences
import android.content.res.AssetManager
import android.util.Log
import androidx.lifecycle.ViewModel
import com.google.codelab.awesomedrawingquiz.data.DrawingAssetsConverter
import com.google.codelab.awesomedrawingquiz.data.DrawingDao
import com.google.codelab.awesomedrawingquiz.data.DrawingsDbImporter
import io.reactivex.Completable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
class SplashViewModel(
private val assetManager: AssetManager,
private val preferences: SharedPreferences,
private val dao: DrawingDao
) : ViewModel() {
private var disposable: Disposable? = null
internal fun importDrawingsIfRequired(callback: () -> Unit) {
// if there is an ongoing task, don't start another one.
if (null != disposable) {
return
}
val signal: Completable
if (!preferences.getBoolean(KEY_INITIALIZED, false)) {
Log.d(TAG, "Database is not ready")
signal = DrawingAssetsConverter(assetManager).toList()
.flatMapCompletable { DrawingsDbImporter(dao, it) }
.doOnComplete { preferences.edit().putBoolean(KEY_INITIALIZED, true).apply() }
} else {
Log.d(TAG, "Database is ready to use")
// add 1 second delay even if we already imported all of the drawings,
// just to earn some time to show nice splash screen!
signal = Completable.timer(1, TimeUnit.SECONDS, Schedulers.io())
}
disposable = signal.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(callback)
}
override fun onCleared() {
if (null != disposable) {
disposable!!.dispose()
}
}
companion object {
private val TAG = "SplashViewModel"
private val KEY_INITIALIZED = "db_initialized"
}
}
| apache-2.0 | 1dd327e0c740ac5368e66bf2fb278e20 | 31.935897 | 88 | 0.732192 | 4.267442 | false | false | false | false |
world-federation-of-advertisers/common-jvm | src/main/kotlin/org/wfanet/measurement/common/db/postgres/PostgresFlags.kt | 1 | 1813 | // Copyright 2022 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.common.db.postgres
import picocli.CommandLine
/** Common command-line flags for connecting to a single Postgres database. */
class PostgresFlags {
@CommandLine.Option(
names = ["--postgres-database"],
description = ["Name of the Postgres database."],
required = false
)
var database: String = ""
private set
@CommandLine.Option(
names = ["--postgres-host"],
description = ["Host name of the Postgres database."],
required = true
)
lateinit var host: String
private set
@CommandLine.Option(
names = ["--postgres-port"],
description = ["Port of the Postgres database."],
required = true
)
var port: Int = 0
private set
@CommandLine.Option(
names = ["--postgres-user"],
description = ["User of the Postgres database."],
required = true
)
lateinit var user: String
private set
@CommandLine.Option(
names = ["--postgres-password"],
description = ["Password of the Postgres database."],
required = true
)
lateinit var password: String
private set
val jdbcConnectionString: String
get() {
return "jdbc:postgresql://$host:$port/$database"
}
}
| apache-2.0 | 905974031fc6cdbfafa4a7876ed7e451 | 26.892308 | 78 | 0.686707 | 4.389831 | false | false | false | false |
ProgramLeague/EmailEverything | src/main/kotlin/ray/eldath/ew/mail/POP3.kt | 1 | 483 | package ray.eldath.ew.mail
import ray.eldath.ew.util.ReceivedEmail
import ray.eldath.ew.util.ReceivedEmailSet
class POP3(server: String, port: Int, username: String, password: String, ssl: Boolean = false) : ReceiveEmail {
private val share = Share("pop3", server, port, username, password, ssl)
override fun receive(): ReceivedEmailSet = share.receive()
override fun delete(receivedEmail: ReceivedEmail) = share.delete(receivedEmail)
override fun close() = share.close()
} | gpl-3.0 | 158cc8b65a0c52520656b7c287bf597d | 31.266667 | 112 | 0.761905 | 3.525547 | false | false | false | false |
konachan700/Mew | software/MeWSync/app/src/main/java/com/mewhpm/mewsync/DeviceActivity.kt | 1 | 4068 | package com.mewhpm.mewsync
import android.content.Context
import android.graphics.drawable.Icon
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import com.mewhpm.mewsync.dao.KnownDevicesDao
import com.mewhpm.mewsync.dao.connectionSource
import com.mewhpm.mewsync.fragments.PasswordsRootFragment
import com.mewhpm.mewsync.ui.fragmentpages.getFragmentBook
import com.mewhpm.mewsync.utils.fixPaddingTopForNavigationView
import com.mewhpm.mewsync.utils.setOnLogoClickEvent
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil
import kotlinx.android.synthetic.main.x02_activity_device.*
import ru.ztrap.iconics.kt.wrapByIconics
class DeviceActivity : AppCompatActivity() {
companion object {
const val TAB_PASSWORDS_TREE_ROOT = "passwords_tree"
var currentDeviceMac = ""
}
private val passwordFragment = PasswordsRootFragment()
private fun generateIcon(icon: GoogleMaterial.Icon, colorResId: Int, size: Int = 28) : Icon {
return Icon.createWithBitmap(
IconicsDrawable([email protected])
.icon(icon).sizeDp(size)
.color(ContextCompat.getColor([email protected], colorResId))
.toBitmap())
}
private fun onMenuClickSelector(menuItemResId : Int) {
when (menuItemResId) {
R.id.menuItemPasswords -> {
[email protected](R.id.fragment_holder_dev_1).showTopInGroup(TAB_PASSWORDS_TREE_ROOT) }
R.id.menuSync -> {}
}
}
private fun onMenuClickBase(menuItem : MenuItem) : Boolean {
for (i in 0..([email protected]() - 1)) {
[email protected](i).isChecked = false
}
menuItem.isChecked = true
[email protected]()
onMenuClickSelector(menuItem.itemId)
return true
}
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(newBase.wrapByIconics())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.x02_activity_device)
val toolbar: Toolbar = this.activity_device_toolbar as Toolbar
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayShowTitleEnabled(false)
supportActionBar!!.setDisplayHomeAsUpEnabled(false)
supportActionBar!!.setDisplayUseLogoEnabled(true)
supportActionBar!!.setLogo(generateIcon(GoogleMaterial.Icon.gmd_apps, R.color.colorBrandWhite).loadDrawable(this))
toolbar.setOnLogoClickEvent {
[email protected](GravityCompat.START)
}
getFragmentBook(R.id.fragment_holder_dev_1).groupTopFragmentRequest = { group ->
when (group) {
TAB_PASSWORDS_TREE_ROOT -> passwordFragment
else -> throw IllegalArgumentException("Fragment group $group not exist")
}
}
this.navView1.menu.clear()
this.navView1.setNavigationItemSelectedListener { menuItem -> onMenuClickBase(menuItem) }
IconicsMenuInflaterUtil.inflate(menuInflater, this, R.menu.device_navigation_view, this.navView1.menu)
fixPaddingTopForNavigationView()
this.logoutIcon1.setImageIcon(generateIcon(GoogleMaterial.Icon.gmd_exit_to_app, R.color.colorBrandWhite, 20))
logoutTextView1.setOnClickListener {
KnownDevicesDao.getInstance(connectionSource).clearDefault()
[email protected]()
}
this.navView1.menu.findItem(R.id.menuItemPasswords).isChecked = true
getFragmentBook(R.id.fragment_holder_dev_1).showTopInGroup(TAB_PASSWORDS_TREE_ROOT)
}
}
| gpl-3.0 | 52d35c1a4867663332ce09898bff0464 | 40.938144 | 122 | 0.723206 | 4.540179 | false | false | false | false |
google-developer-training/android-demos | DonutTracker/ConditionalNavigation/app/src/main/java/com/android/samples/donuttracker/donut/DonutEntryDialogFragment.kt | 1 | 4609 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.samples.donuttracker.donut
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.observe
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.android.samples.donuttracker.Notifier
import com.android.samples.donuttracker.R
import com.android.samples.donuttracker.UserPreferencesRepository
import com.android.samples.donuttracker.databinding.DonutEntryDialogBinding
import com.android.samples.donuttracker.model.Donut
import com.android.samples.donuttracker.storage.SnackDatabase
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
/**
* This dialog allows the user to enter information about a donut, either creating a new
* entry or updating an existing one.
*/
class DonutEntryDialogFragment : BottomSheetDialogFragment() {
private enum class EditingState {
NEW_DONUT,
EXISTING_DONUT
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return DonutEntryDialogBinding.inflate(inflater, container, false).root
}
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val donutDao = SnackDatabase.getDatabase(requireContext()).donutDao()
val donutEntryViewModel: DonutEntryViewModel by viewModels {
DonutViewModelFactory(donutDao, UserPreferencesRepository.getInstance(requireContext()))
}
val binding = DonutEntryDialogBinding.bind(view)
var donut: Donut? = null
val args: DonutEntryDialogFragmentArgs by navArgs()
val editingState =
if (args.itemId > 0) {
EditingState.EXISTING_DONUT
} else {
EditingState.NEW_DONUT
}
// If we arrived here with an itemId of >= 0, then we are editing an existing item
if (editingState == EditingState.EXISTING_DONUT) {
// Request to edit an existing item, whose id was passed in as an argument.
// Retrieve that item and populate the UI with its details
donutEntryViewModel.get(args.itemId).observe(viewLifecycleOwner) { donutItem ->
binding.apply {
name.setText(donutItem.name)
description.setText(donutItem.description)
ratingBar.rating = donutItem.rating.toFloat()
}
donut = donutItem
}
}
// When the user clicks the Done button, use the data here to either update
// an existing item or create a new one
binding.doneButton.setOnClickListener {
// Grab these now since the Fragment may go away before the setupNotification
// lambda below is called
val context = requireContext().applicationContext
val navController = findNavController()
donutEntryViewModel.addData(
donut?.id ?: 0,
binding.name.text.toString(),
binding.description.text.toString(),
binding.ratingBar.rating.toInt()
) { actualId ->
val arg = DonutEntryDialogFragmentArgs(actualId).toBundle()
val pendingIntent = navController
.createDeepLink()
.setDestination(R.id.donutEntryDialogFragment)
.setArguments(arg)
.createPendingIntent()
Notifier.postNotification(actualId, context, pendingIntent)
}
dismiss()
}
// User clicked the Cancel button; just exit the dialog without saving the data
binding.cancelButton.setOnClickListener {
dismiss()
}
}
}
| apache-2.0 | ce6c9a08f3524adec70c60a80f9e98d3 | 38.059322 | 100 | 0.669993 | 5.126808 | false | false | false | false |
square/leakcanary | leakcanary-android-core/src/main/java/leakcanary/internal/activity/LeakActivity.kt | 2 | 7432 | package leakcanary.internal.activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.squareup.leakcanary.core.R
import java.io.FileInputStream
import java.io.IOException
import java.util.UUID
import leakcanary.EventListener.Event.HeapDump
import leakcanary.internal.InternalLeakCanary
import leakcanary.internal.activity.db.Db
import leakcanary.internal.activity.screen.AboutScreen
import leakcanary.internal.activity.screen.HeapAnalysisFailureScreen
import leakcanary.internal.activity.screen.HeapDumpScreen
import leakcanary.internal.activity.screen.HeapDumpsScreen
import leakcanary.internal.activity.screen.LeaksScreen
import leakcanary.internal.navigation.NavigatingActivity
import leakcanary.internal.navigation.Screen
import shark.SharkLog
internal class LeakActivity : NavigatingActivity() {
private val leaksButton by lazy {
findViewById<View>(R.id.leak_canary_navigation_button_leaks)
}
private val leaksButtonIconView by lazy {
findViewById<View>(R.id.leak_canary_navigation_button_leaks_icon)
}
private val heapDumpsButton by lazy {
findViewById<View>(R.id.leak_canary_navigation_button_heap_dumps)
}
private val heapDumpsButtonIconView by lazy {
findViewById<View>(R.id.leak_canary_navigation_button_heap_dumps_icon)
}
private val aboutButton by lazy {
findViewById<View>(R.id.leak_canary_navigation_button_about)
}
private val aboutButtonIconView by lazy {
findViewById<View>(R.id.leak_canary_navigation_button_about_icon)
}
private val bottomNavigationBar by lazy {
findViewById<View>(R.id.leak_canary_bottom_navigation_bar)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.leak_canary_leak_activity)
installNavigation(savedInstanceState, findViewById(R.id.leak_canary_main_container))
leaksButton.setOnClickListener { resetTo(LeaksScreen()) }
heapDumpsButton.setOnClickListener { resetTo(HeapDumpsScreen()) }
aboutButton.setOnClickListener { resetTo(AboutScreen()) }
handleViewHprof(intent)
}
private fun handleViewHprof(intent: Intent?) {
if (intent?.action != Intent.ACTION_VIEW) return
val uri = intent.data ?: return
if (uri.lastPathSegment?.endsWith(".hprof") != true) {
Toast.makeText(this, getString(R.string.leak_canary_import_unsupported_file_extension, uri.lastPathSegment), Toast.LENGTH_LONG).show()
return
}
resetTo(HeapDumpsScreen())
AsyncTask.THREAD_POOL_EXECUTOR.execute {
importHprof(uri)
}
}
override fun onNewScreen(screen: Screen) {
when (screen) {
is LeaksScreen -> {
bottomNavigationBar.visibility = View.VISIBLE
leaksButton.isSelected = true
leaksButtonIconView.alpha = 1.0f
heapDumpsButton.isSelected = false
heapDumpsButtonIconView.alpha = 0.4f
aboutButton.isSelected = false
aboutButtonIconView.alpha = 0.4f
}
is HeapDumpsScreen -> {
bottomNavigationBar.visibility = View.VISIBLE
leaksButton.isSelected = false
leaksButtonIconView.alpha = 0.4f
heapDumpsButton.isSelected = true
heapDumpsButtonIconView.alpha = 1.0f
aboutButton.isSelected = false
aboutButtonIconView.alpha = 0.4f
}
is AboutScreen -> {
bottomNavigationBar.visibility = View.VISIBLE
leaksButton.isSelected = false
leaksButtonIconView.alpha = 0.4f
heapDumpsButton.isSelected = false
heapDumpsButtonIconView.alpha = 0.4f
aboutButton.isSelected = true
aboutButtonIconView.alpha = 1.0f
}
else -> {
bottomNavigationBar.visibility = View.GONE
}
}
}
override fun getLauncherScreen(): Screen {
return LeaksScreen()
}
fun requestImportHprof() {
val requestFileIntent = Intent(Intent.ACTION_GET_CONTENT).apply {
type = "*/*"
addCategory(Intent.CATEGORY_OPENABLE)
}
val chooserIntent = Intent.createChooser(
requestFileIntent, resources.getString(R.string.leak_canary_import_from_title)
)
startActivityForResult(chooserIntent, FILE_REQUEST_CODE)
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
returnIntent: Intent?
) {
SharkLog.d {
"Got activity result with requestCode=$requestCode resultCode=$resultCode returnIntent=$returnIntent"
}
if (requestCode == FILE_REQUEST_CODE && resultCode == RESULT_OK && returnIntent != null) {
returnIntent.data?.let { fileUri ->
AsyncTask.THREAD_POOL_EXECUTOR.execute {
importHprof(fileUri)
}
}
}
}
private fun importHprof(fileUri: Uri) {
try {
contentResolver.openFileDescriptor(fileUri, "r")
?.fileDescriptor?.let { fileDescriptor ->
val inputStream = FileInputStream(fileDescriptor)
InternalLeakCanary.createLeakDirectoryProvider(this)
.newHeapDumpFile()
?.let { target ->
inputStream.use { input ->
target.outputStream()
.use { output ->
input.copyTo(output, DEFAULT_BUFFER_SIZE)
}
}
InternalLeakCanary.sendEvent(
HeapDump(
uniqueId = UUID.randomUUID().toString(),
file = target,
durationMillis = -1,
reason = "Imported by user"
)
)
}
}
} catch (e: IOException) {
SharkLog.d(e) { "Could not import Hprof file" }
}
}
override fun onDestroy() {
super.onDestroy()
if (!isChangingConfigurations) {
Db.closeDatabase()
}
}
override fun setTheme(resid: Int) {
// We don't want this to be called with an incompatible theme.
// This could happen if you implement runtime switching of themes
// using ActivityLifecycleCallbacks.
if (resid != R.style.leak_canary_LeakCanary_Base) {
return
}
super.setTheme(resid)
}
override fun parseIntentScreens(intent: Intent): List<Screen> {
val heapAnalysisId = intent.getLongExtra("heapAnalysisId", -1L)
if (heapAnalysisId == -1L) {
return emptyList()
}
val success = intent.getBooleanExtra("success", false)
return if (success) {
arrayListOf(HeapDumpsScreen(), HeapDumpScreen(heapAnalysisId))
} else {
arrayListOf(HeapDumpsScreen(), HeapAnalysisFailureScreen(heapAnalysisId))
}
}
companion object {
private const val FILE_REQUEST_CODE = 0
fun createHomeIntent(context: Context): Intent {
val intent = Intent(context, LeakActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
return intent
}
fun createSuccessIntent(context: Context, heapAnalysisId: Long): Intent {
val intent = createHomeIntent(context)
intent.putExtra("heapAnalysisId", heapAnalysisId)
intent.putExtra("success", true)
return intent
}
fun createFailureIntent(context: Context, heapAnalysisId: Long): Intent {
val intent = createHomeIntent(context)
intent.putExtra("heapAnalysisId", heapAnalysisId)
intent.putExtra("success", false)
return intent
}
}
}
| apache-2.0 | 923481d82fe163b5e9c03fd647c7bc3c | 31.034483 | 140 | 0.685818 | 4.408066 | false | false | false | false |
tmarsteel/compiler-fiddle | src/compiler/binding/BoundCodeChunk.kt | 1 | 3808 | /*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package compiler.binding
import compiler.EarlyStackOverflowException
import compiler.InternalCompilerError
import compiler.ast.CodeChunk
import compiler.ast.Executable
import compiler.binding.context.CTContext
import compiler.binding.type.BaseTypeReference
import compiler.reportings.Reporting
import compiler.throwOnCycle
class BoundCodeChunk(
/**
* Context that applies to the leftHandSide statement; derivatives are stored within the statements themselves
*/
override val context: CTContext,
override val declaration: CodeChunk
) : BoundExecutable<CodeChunk> {
private var expectedReturnType: BaseTypeReference? = null
/** The bound statements of this code; must not be null after semantic analysis is done */
var statements: List<BoundExecutable<*>>? = null
private set
override val isGuaranteedToThrow: Boolean?
get() = statements?.any { it.isGuaranteedToThrow ?: false }
override val isGuaranteedToReturn: Boolean?
get() = statements?.any { it.isGuaranteedToReturn ?: false }
override fun semanticAnalysisPhase3(): Collection<Reporting> {
val reportings = mutableSetOf<Reporting>()
var currentContext = context
val boundStatements = mutableListOf<BoundExecutable<*>>()
for (astStatement in declaration.statements) {
val boundStatement = astStatement.bindTo(currentContext)
if (this.expectedReturnType != null) {
boundStatement.enforceReturnType(this.expectedReturnType!!)
}
reportings += boundStatement.semanticAnalysisPhase1()
reportings += boundStatement.semanticAnalysisPhase2()
reportings += boundStatement.semanticAnalysisPhase3()
boundStatements.add(boundStatement)
currentContext = boundStatement.modified(currentContext)
}
this.statements = boundStatements
return reportings
}
override fun enforceReturnType(type: BaseTypeReference) {
this.expectedReturnType = type
}
override fun findReadsBeyond(boundary: CTContext): Collection<BoundExecutable<Executable<*>>> {
if (statements == null) throw InternalCompilerError("Illegal state: invoke this function after semantic analysis phase 3 is completed.")
return statements!!.flatMap {
try {
throwOnCycle(this) { it.findReadsBeyond(boundary) }
} catch (ex: EarlyStackOverflowException) {
emptySet()
}
}
}
override fun findWritesBeyond(boundary: CTContext): Collection<BoundExecutable<Executable<*>>> {
if (statements == null) throw InternalCompilerError("Illegal state: invoke this function after semantic analysis phase 3 is completed.")
return statements!!.flatMap {
try {
throwOnCycle(this) { it.findWritesBeyond(boundary) }
} catch (ex: EarlyStackOverflowException) {
emptySet()
}
}
}
}
| lgpl-3.0 | 48fcbe52ad06d0c4305128b2e16501af | 35.970874 | 144 | 0.696166 | 5.077333 | false | false | false | false |
trivago/reportoire | core/src/test/kotlin/com/trivago/reportoire/core/common/MemorySourceSpec.kt | 1 | 2719 | /*********************************************************************************
* Copyright 2017-present trivago GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**********************************************************************************/
package com.trivago.reportoire.core.common
import com.trivago.reportoire.core.sources.Source
import org.jetbrains.spek.api.Spek
import kotlin.test.assertFalse
import kotlin.test.assertTrue
// Spec
class MemorySourceSpec : Spek({
given("A MemoryCacheSource") {
val memorySource = MemorySource<String, String>()
context("if it has an invalid model") {
beforeEach {
memorySource.setModel("key", null)
}
it("returns an Error when getting the result") {
val result = memorySource.getResult("key")
assertTrue(result is Source.Result.Error && result.throwable is IllegalStateException)
}
}
context("if it has a valid model") {
beforeEach {
memorySource.setModel("key", "value")
}
it("returns an Error when accessing a non existing key") {
val result = memorySource.getResult("some different key")
assertTrue(result is Source.Result.Error && result.throwable is IllegalStateException)
}
it("returns the correct model when requesting it") {
val result = memorySource.getResult("key")
assertTrue(result is Source.Result.Success && result.model == "value")
}
context("when it is resetted") {
beforeEach {
memorySource.reset()
}
it("returns an Error when getting the result") {
val result = memorySource.getResult("key")
assertTrue(result is Source.Result.Error && result.throwable is IllegalStateException)
}
}
}
it("returns false when checking if a result is currently gotten") {
val isGettingModel = memorySource.isGettingResult()
assertFalse(isGettingModel)
}
}
})
| apache-2.0 | c448b65998f7ac5999270f8d580fcb2c | 35.253333 | 106 | 0.578154 | 5.179048 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/manga/chapter/ChaptersAdapter.kt | 3 | 1399 | package eu.kanade.tachiyomi.ui.manga.chapter
import android.content.Context
import android.view.MenuItem
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.getResourceColor
import java.text.DateFormat
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
class ChaptersAdapter(
controller: ChaptersController,
context: Context
) : FlexibleAdapter<ChapterItem>(null, controller, true) {
var items: List<ChapterItem> = emptyList()
val menuItemListener: OnMenuItemClickListener = controller
val readColor = context.getResourceColor(android.R.attr.textColorHint)
val unreadColor = context.getResourceColor(android.R.attr.textColorPrimary)
val bookmarkedColor = context.getResourceColor(R.attr.colorAccent)
val decimalFormat = DecimalFormat("#.###", DecimalFormatSymbols()
.apply { decimalSeparator = '.' })
val dateFormat: DateFormat = DateFormat.getDateInstance(DateFormat.SHORT)
override fun updateDataSet(items: List<ChapterItem>?) {
this.items = items ?: emptyList()
super.updateDataSet(items)
}
fun indexOf(item: ChapterItem): Int {
return items.indexOf(item)
}
interface OnMenuItemClickListener {
fun onMenuItemClick(position: Int, item: MenuItem)
}
}
| apache-2.0 | 2359943bdb7813034c32240e615d6037 | 29.088889 | 79 | 0.71837 | 4.791096 | false | false | false | false |
http4k/http4k | http4k-contract/src/main/kotlin/org/http4k/contract/ContractRoute.kt | 1 | 4275 | package org.http4k.contract
import org.http4k.contract.PreFlightExtraction.Companion
import org.http4k.core.Filter
import org.http4k.core.HttpHandler
import org.http4k.core.Method
import org.http4k.core.Method.OPTIONS
import org.http4k.core.NoOp
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.BAD_REQUEST
import org.http4k.core.Status.Companion.METHOD_NOT_ALLOWED
import org.http4k.core.Status.Companion.NOT_FOUND
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Uri
import org.http4k.core.then
import org.http4k.core.toPathSegmentDecoded
import org.http4k.filter.ServerFilters
import org.http4k.lens.LensFailure
import org.http4k.lens.PathLens
import org.http4k.routing.Router
import org.http4k.routing.RouterMatch
import org.http4k.routing.RouterMatch.MatchedWithoutHandler
import org.http4k.routing.RouterMatch.MatchingHandler
import org.http4k.routing.RouterMatch.MethodNotMatched
import org.http4k.routing.RouterMatch.Unmatched
class ContractRoute internal constructor(val method: Method,
val spec: ContractRouteSpec,
val meta: RouteMeta,
internal val toHandler: (ExtractedParts) -> HttpHandler) : HttpHandler {
val nonBodyParams = meta.requestParams.plus(spec.pathLenses).flatten()
val tags = meta.tags.toSet().sortedBy { it.name }
fun newRequest(baseUri: Uri) = Request(method, "").uri(baseUri.path(spec.describe(Root)))
internal fun toRouter(contractRoot: PathSegments) = object : Router {
override fun toString(): String = "${method.name}: ${spec.describe(contractRoot)}"
override fun match(request: Request): RouterMatch =
if ((request.method == OPTIONS || request.method == method) && request.pathSegments().startsWith(spec.pathFn(contractRoot))) {
try {
request.without(spec.pathFn(contractRoot))
.extract(spec.pathLenses.toList())
?.let {
MatchingHandler(
if (request.method == OPTIONS) {
{ Response(OK) }
} else toHandler(it), description)
} ?: Unmatched(description)
} catch (e: LensFailure) {
Unmatched(description)
}
} else Unmatched(description)
}
fun describeFor(contractRoot: PathSegments) = spec.describe(contractRoot)
/**
* ContractRoutes are chiefly designed to operate within a contract {} block and not directly as an HttpHandler,
* but this function exists to enable the testing of the ContractRoute logic outside of a wider contract context.
* This means that certain behaviour is defaulted - chiefly the generation of NOT_FOUND and BAD_REQUEST responses.
*/
override fun invoke(request: Request): Response {
return when (val matchResult = toRouter(Root).match(request)) {
is MatchingHandler -> {
(meta.security?.filter ?: Filter.NoOp)
.then(ServerFilters.CatchLensFailure { Response(BAD_REQUEST) })
.then(PreFlightExtractionFilter(meta, Companion.All))
.then(matchResult)(request)
}
is MethodNotMatched -> Response(METHOD_NOT_ALLOWED)
is Unmatched -> Response(NOT_FOUND)
is MatchedWithoutHandler -> Response(NOT_FOUND)
}
}
override fun toString() = "${method.name}: ${spec.describe(Root)}"
}
internal class ExtractedParts(private val mapping: Map<PathLens<*>, *>) {
@Suppress("UNCHECKED_CAST")
operator fun <T> get(lens: PathLens<T>): T = mapping[lens] as T
}
private operator fun <T> PathSegments.invoke(index: Int, fn: (String) -> T): T? = toList().let { if (it.size > index) fn(it[index]) else null }
private fun PathSegments.extract(lenses: List<PathLens<*>>): ExtractedParts? =
when (toList().size) {
lenses.size -> ExtractedParts(
lenses.mapIndexed { i, lens -> lens to this(i) { lens(it.toPathSegmentDecoded()) } }.toMap()
)
else -> null
}
| apache-2.0 | c90122f4fc5e262564ac7785baa0f9ae | 44 | 143 | 0.646082 | 4.253731 | false | false | false | false |
pnemonic78/RemoveDuplicates | duplicates-android/app/src/main/java/com/github/duplicates/message/MessageDeleteTask.kt | 1 | 4101 | /*
* Copyright 2016, Moshe Waisberg
*
* 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.github.duplicates.message
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.provider.Telephony
import androidx.preference.PreferenceManager
import com.github.duplicates.DuplicateDeleteTask
import com.github.duplicates.DuplicateDeleteTaskListener
/**
* Task to find duplicate messages.
*
* @author moshe.w
*/
class MessageDeleteTask<L : DuplicateDeleteTaskListener<MessageItem>>(
context: Context,
listener: L
) : DuplicateDeleteTask<MessageItem, L>(context, listener) {
override fun createProvider(context: Context): MessageProvider {
return MessageProvider(context)
}
override fun checkPermissions(activity: Activity) {
if (checkDefaultSmsPackage(activity)) {
super.checkPermissions(activity)
} else {
setDefaultSmsPackage(activity)
}
}
override fun onPostExecute(result: Unit) {
super.onPostExecute(result)
restoreDefaultSmsPackage()
}
/**
* Android 4.4 (KitKat) makes the existing APIs public and adds the concept of a default SMS app, which the user can select in system settings.
*
* @param context The context.
*/
protected fun checkDefaultSmsPackage(context: Context): Boolean {
val defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(context)
val packageName = context.packageName
return packageName == defaultSmsApp
}
/**
* Set this app as the default SMS app.
*
* @param activity the activity.
*/
private fun setDefaultSmsPackage(activity: Activity) {
val defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(activity)
val packageName = activity.packageName
val prefs = PreferenceManager.getDefaultSharedPreferences(activity)
prefs.edit().putString(KEY_SMS_PACKAGE, defaultSmsApp).apply()
val intent = Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT)
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName)
activity.startActivityForResult(intent, ACTIVITY_SMS_PACKAGE)
}
/**
* Restore the default SMS app.
*/
private fun restoreDefaultSmsPackage() {
val context = context
var defaultSmsApp: String? = Telephony.Sms.getDefaultSmsPackage(context)
val packageName = context.packageName
if (packageName == defaultSmsApp) {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
defaultSmsApp = prefs.getString(KEY_SMS_PACKAGE, null)
if (defaultSmsApp != null) {
val intent = Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT)
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, defaultSmsApp)
context.startActivity(intent)
}
}
}
override fun onActivityResult(
activity: Activity,
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(activity, requestCode, resultCode, data)
if (requestCode == ACTIVITY_SMS_PACKAGE) {
if (checkDefaultSmsPackage(activity)) {
super.checkPermissions(activity)
}
}
}
override fun onCancelled() {
super.onCancelled()
restoreDefaultSmsPackage()
}
companion object {
private const val KEY_SMS_PACKAGE = "defaultSmsPackage"
const val ACTIVITY_SMS_PACKAGE = 30
}
}
| apache-2.0 | 99c6784c6b4ebf874aadcfab4e51badc | 31.291339 | 147 | 0.679834 | 4.735566 | false | false | false | false |
msebire/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/inference.kt | 1 | 3324 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors.inference
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil.extractIterableTypeParameter
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.SpreadState
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager
import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil.getQualifierType
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.api.JustTypeArgument
import org.jetbrains.plugins.groovy.lang.resolve.api.UnknownArgument
import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint
fun getTopLevelType(expression: GrExpression): PsiType? {
if (expression is GrMethodCall) {
val resolved = expression.advancedResolve() as? GroovyMethodResult
resolved?.candidate?.let {
val session = GroovyInferenceSessionBuilder(expression, it, resolved.contextSubstitutor)
.resolveMode(false)
.build()
return session.inferSubst().substitute(PsiUtil.getSmartReturnType(it.method))
}
return null
}
if (expression is GrClosableBlock) {
return TypesUtil.createTypeByFQClassName(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, expression)
}
return expression.type
}
fun getTopLevelTypeCached(expression: GrExpression): PsiType? {
return GroovyPsiManager.getInstance(expression.project).getTopLevelType(expression)
}
fun buildQualifier(ref: GrReferenceExpression?, state: ResolveState): Argument {
val qualifierExpression = ref?.qualifierExpression
val spreadState = state[SpreadState.SPREAD_STATE]
if (qualifierExpression != null && spreadState == null) {
return ExpressionArgument(qualifierExpression)
}
val resolvedThis = state[ClassHint.THIS_TYPE]
if (resolvedThis != null) {
return JustTypeArgument(resolvedThis)
}
val type = ref?.let(::getQualifierType)
when {
spreadState == null -> return JustTypeArgument(type)
type == null -> return UnknownArgument
else -> return JustTypeArgument(extractIterableTypeParameter(type, false))
}
}
fun PsiSubstitutor.putAll(parameters: Array<out PsiTypeParameter>, arguments: Array<out PsiType>): PsiSubstitutor {
if (arguments.size != parameters.size) return this
return parameters.zip(arguments).fold(this) { acc, (param, arg) ->
acc.put(param, arg)
}
}
fun PsiClass.type(): PsiClassType {
return PsiElementFactory.SERVICE.getInstance(project).createType(this, PsiSubstitutor.EMPTY)
}
| apache-2.0 | 57b6463a929732a64e5192b045e757da | 43.32 | 140 | 0.797834 | 4.272494 | false | false | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/ui/TaskerItemPickerActivity.kt | 1 | 5950 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.ui
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import androidx.core.content.edit
import androidx.core.os.bundleOf
import com.google.android.material.button.MaterialButton
import org.openhab.habdroid.R
import org.openhab.habdroid.model.Item
import org.openhab.habdroid.util.PrefKeys
import org.openhab.habdroid.util.SuggestedCommandsFactory
import org.openhab.habdroid.util.TaskerIntent
import org.openhab.habdroid.util.TaskerPlugin
import org.openhab.habdroid.util.getPrefs
import org.openhab.habdroid.util.isTaskerPluginEnabled
import org.openhab.habdroid.util.showToast
class TaskerItemPickerActivity(
override var hintMessageId: Int = R.string.settings_tasker_plugin_summary,
override var hintButtonMessageId: Int = R.string.turn_on,
override var hintIconId: Int = R.drawable.ic_connection_error
) : AbstractItemPickerActivity(), View.OnClickListener {
private var relevantVars: Array<String>? = null
private lateinit var commandButton: MaterialButton
private lateinit var updateButton: MaterialButton
override val forItemCommandOnly: Boolean = false
@LayoutRes override val additionalConfigLayoutRes: Int = R.layout.tasker_item_picker_config
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retryButton.setOnClickListener {
if (needToShowHint) {
getPrefs().edit {
putBoolean(PrefKeys.TASKER_PLUGIN_ENABLED, true)
}
needToShowHint = false
}
loadItems()
}
if (!getPrefs().isTaskerPluginEnabled()) {
needToShowHint = true
updateViewVisibility(loading = false, loadError = false, showHint = true)
}
val editItem = intent.getBundleExtra(TaskerIntent.EXTRA_BUNDLE)
initialHighlightItemName = editItem?.getString(EXTRA_ITEM_NAME)
commandButton = findViewById(R.id.button_item_command)
updateButton = findViewById(R.id.button_item_update)
commandButton.setOnClickListener(this)
updateButton.setOnClickListener(this)
if (intent.getBundleExtra(TaskerIntent.EXTRA_BUNDLE)?.getBoolean(EXTRA_ITEM_AS_COMMAND, true) == false) {
updateButton.isChecked = true
} else {
commandButton.isChecked = true
}
if (TaskerPlugin.hostSupportsRelevantVariables(intent.extras)) {
relevantVars = TaskerPlugin.getRelevantVariableList(intent.extras)
}
}
override fun addAdditionalCommands(
suggestedCommands: SuggestedCommandsFactory.SuggestedCommands,
entries: MutableList<CommandEntry>
) {
relevantVars?.forEach {
entries.add(CommandEntry(it, getString(R.string.item_picker_tasker_variable, it)))
}
}
override fun finish(item: Item, state: String?, mappedState: String?, tag: Any?) {
if (state == null || mappedState == null) {
return
}
var asCommand = commandButton.isChecked
if (asCommand && item.type == Item.Type.Contact) {
asCommand = false
showToast(R.string.item_picker_contact_no_command)
}
val resultBundle = bundleOf(
EXTRA_ITEM_NAME to item.name,
EXTRA_ITEM_LABEL to item.label,
EXTRA_ITEM_STATE to state,
EXTRA_ITEM_MAPPED_STATE to mappedState,
EXTRA_ITEM_AS_COMMAND to asCommand
)
val resultIntent = Intent().apply {
@StringRes val blurbRes =
if (asCommand) R.string.item_picker_blurb_command else R.string.item_picker_blurb_update
val blurb = getString(blurbRes, item.label, item.name, state)
putExtra(TaskerIntent.EXTRA_STRING_BLURB, blurb)
putExtra(TaskerIntent.EXTRA_BUNDLE, resultBundle)
}
if (TaskerPlugin.Setting.hostSupportsOnFireVariableReplacement(this)) {
TaskerPlugin.Setting.setVariableReplaceKeys(resultBundle,
arrayOf(EXTRA_ITEM_STATE, EXTRA_ITEM_MAPPED_STATE)
)
}
if (TaskerPlugin.Setting.hostSupportsSynchronousExecution(intent.extras)) {
TaskerPlugin.Setting.requestTimeoutMS(resultIntent, TaskerPlugin.Setting.REQUESTED_TIMEOUT_MS_MAX)
}
if (TaskerPlugin.hostSupportsRelevantVariables(intent.extras)) {
TaskerPlugin.addRelevantVariableList(resultIntent,
arrayOf("$VAR_HTTP_CODE\nHTTP code\nHTTP code returned by the server"))
}
setResult(RESULT_OK, resultIntent)
finish()
}
companion object {
const val EXTRA_ITEM_NAME = "itemName"
const val EXTRA_ITEM_LABEL = "itemLabel"
const val EXTRA_ITEM_STATE = "itemState"
const val EXTRA_ITEM_MAPPED_STATE = "itemMappedState"
const val RESULT_CODE_PLUGIN_DISABLED = TaskerPlugin.Setting.RESULT_CODE_FAILED_PLUGIN_FIRST
const val RESULT_CODE_NO_CONNECTION = TaskerPlugin.Setting.RESULT_CODE_FAILED_PLUGIN_FIRST + 1
fun getResultCodeForHttpFailure(httpCode: Int): Int {
return 1000 + httpCode
}
const val VAR_HTTP_CODE = "%httpcode"
const val EXTRA_ITEM_AS_COMMAND = "asCommand"
}
override fun onClick(view: View) {
// Make sure one can't uncheck buttons by clicking a checked one
(view as MaterialButton).isChecked = true
}
}
| epl-1.0 | b57e7a35bbaf16bff273290174b7e83b | 36.898089 | 113 | 0.681008 | 4.413947 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/MyAccount.kt | 1 | 15017 | /***************************************************************************************
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.appcompat.widget.Toolbar
import androidx.core.content.edit
import com.google.android.material.textfield.TextInputLayout
import com.ichi2.anim.ActivityTransitionAnimation
import com.ichi2.anki.snackbar.showSnackbar
import com.ichi2.anki.web.HostNumFactory.getInstance
import com.ichi2.async.Connection
import com.ichi2.libanki.sync.CustomSyncServerUrlException
import com.ichi2.themes.StyledProgressDialog
import com.ichi2.ui.TextInputEditField
import com.ichi2.utils.AdaptionUtil.isUserATestClient
import com.ichi2.utils.KotlinCleanup
import net.ankiweb.rsdroid.BackendFactory
import timber.log.Timber
import java.net.UnknownHostException
/**
* Note: [LoginActivity] extends this and should not handle account creation
*/
open class MyAccount : AnkiActivity() {
private lateinit var mLoginToMyAccountView: View
private lateinit var mLoggedIntoMyAccountView: View
private lateinit var mUsername: EditText
private lateinit var mPassword: TextInputEditField
private lateinit var mUsernameLoggedIn: TextView
@Suppress("Deprecation")
private var mProgressDialog: android.app.ProgressDialog? = null
var toolbar: Toolbar? = null
private lateinit var mPasswordLayout: TextInputLayout
private lateinit var mAnkidroidLogo: ImageView
open fun switchToState(newState: Int) {
when (newState) {
STATE_LOGGED_IN -> {
val username = AnkiDroidApp.getSharedPrefs(baseContext).getString("username", "")
mUsernameLoggedIn.text = username
toolbar = mLoggedIntoMyAccountView.findViewById(R.id.toolbar)
if (toolbar != null) {
toolbar!!.title = getString(R.string.sync_account) // This can be cleaned up if all three main layouts are guaranteed to share the same toolbar object
setSupportActionBar(toolbar)
}
setContentView(mLoggedIntoMyAccountView)
}
STATE_LOG_IN -> {
toolbar = mLoginToMyAccountView.findViewById(R.id.toolbar)
if (toolbar != null) {
toolbar!!.title = getString(R.string.sync_account) // This can be cleaned up if all three main layouts are guaranteed to share the same toolbar object
setSupportActionBar(toolbar)
}
setContentView(mLoginToMyAccountView)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
if (showedActivityFailedScreen(savedInstanceState)) {
return
}
super.onCreate(savedInstanceState)
if (isUserATestClient) {
finishWithoutAnimation()
return
}
mayOpenUrl(Uri.parse(resources.getString(R.string.register_url)))
initAllContentViews()
if (isLoggedIn()) {
switchToState(STATE_LOGGED_IN)
} else {
switchToState(STATE_LOG_IN)
}
if (isScreenSmall && this.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
mAnkidroidLogo.visibility = View.GONE
} else {
mAnkidroidLogo.visibility = View.VISIBLE
}
}
private fun attemptLogin() {
val username = mUsername.text.toString().trim { it <= ' ' } // trim spaces, issue 1586
val password = mPassword.text.toString()
if (username.isEmpty() || password.isEmpty()) {
Timber.i("Auto-login cancelled - username/password missing")
return
}
Timber.i("Attempting auto-login")
if (!BackendFactory.defaultLegacySchema) {
handleNewLogin(username, password)
} else {
Connection.login(
mLoginListener,
Connection.Payload(
arrayOf(
username, password,
getInstance(this)
)
)
)
}
}
private fun saveUserInformation(username: String, hkey: String) {
val preferences = AnkiDroidApp.getSharedPrefs(baseContext)
preferences.edit {
putString("username", username)
putString("hkey", hkey)
}
}
private fun login() {
// Hide soft keyboard
val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(mUsername.windowToken, 0)
val username = mUsername.text.toString().trim { it <= ' ' } // trim spaces, issue 1586
val password = mPassword.text.toString()
if (username.isEmpty()) {
mUsername.error = getString(R.string.email_id_empty)
mUsername.requestFocus()
return
}
if (password.isEmpty()) {
mPassword.error = getString(R.string.password_empty)
mPassword.requestFocus()
return
}
if (!BackendFactory.defaultLegacySchema) {
handleNewLogin(username, password)
} else {
Connection.login(
mLoginListener,
Connection.Payload(
arrayOf(
username, password,
getInstance(this)
)
)
)
}
}
private fun logout() {
val preferences = AnkiDroidApp.getSharedPrefs(baseContext)
preferences.edit {
putString("username", "")
putString("hkey", "")
}
getInstance(this).reset()
// force media resync on deauth
col.media.forceResync()
switchToState(STATE_LOG_IN)
}
private fun resetPassword() {
super.openUrl(Uri.parse(resources.getString(R.string.resetpw_url)))
}
private fun initAllContentViews() {
mLoginToMyAccountView = layoutInflater.inflate(R.layout.my_account, null)
mLoginToMyAccountView.let {
mUsername = it.findViewById(R.id.username)
mPassword = it.findViewById(R.id.password)
mPasswordLayout = it.findViewById(R.id.password_layout)
mAnkidroidLogo = it.findViewById(R.id.ankidroid_logo)
}
mPassword.setOnKeyListener(
View.OnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
if (event.action == KeyEvent.ACTION_DOWN) {
when (keyCode) {
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> {
login()
return@OnKeyListener true
}
else -> {}
}
}
false
}
)
val loginButton = mLoginToMyAccountView.findViewById<Button>(R.id.login_button)
loginButton.setOnClickListener { login() }
val resetPWButton = mLoginToMyAccountView.findViewById<Button>(R.id.reset_password_button)
resetPWButton.setOnClickListener { resetPassword() }
val signUpButton = mLoginToMyAccountView.findViewById<Button>(R.id.sign_up_button)
val url = Uri.parse(resources.getString(R.string.register_url))
signUpButton.setOnClickListener { openUrl(url) }
// Add button to link to instructions on how to find AnkiWeb email
val lostEmail = mLoginToMyAccountView.findViewById<Button>(R.id.lost_mail_instructions)
val lostMailUrl = Uri.parse(resources.getString(R.string.link_ankiweb_lost_email_instructions))
lostEmail.setOnClickListener { openUrl(lostMailUrl) }
mLoggedIntoMyAccountView = layoutInflater.inflate(R.layout.my_account_logged_in, null)
mUsernameLoggedIn = mLoggedIntoMyAccountView.findViewById(R.id.username_logged_in)
val logoutButton = mLoggedIntoMyAccountView.findViewById<Button>(R.id.logout_button)
logoutButton.setOnClickListener { logout() }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mPassword.setAutoFillListener {
// disable "show password".
mPasswordLayout.isEndIconVisible = false
Timber.i("Attempting login from autofill")
attemptLogin()
}
}
}
private fun showLoginLogMessage(@StringRes messageResource: Int, loginMessage: String?) {
run {
if (loginMessage.isNullOrEmpty()) {
if (messageResource == R.string.youre_offline && !Connection.allowLoginSyncOnNoConnection) {
// #6396 - Add a temporary "Try Anyway" button until we sort out `isOnline`
showSnackbar(messageResource) {
setAction(R.string.sync_even_if_offline) {
Connection.allowLoginSyncOnNoConnection = true
login()
}
}
} else {
showSnackbar(messageResource)
}
} else {
val res = AnkiDroidApp.appResources
showSimpleMessageDialog(title = res.getString(messageResource), message = loginMessage)
}
}
}
/**
* Listeners
*/
private val mLoginListener: Connection.TaskListener = object : Connection.TaskListener {
override fun onProgressUpdate(vararg values: Any?) {
// Pass
}
override fun onPreExecute() {
Timber.d("loginListener.onPreExecute()")
if (mProgressDialog == null || !mProgressDialog!!.isShowing) {
mProgressDialog = StyledProgressDialog.show(
this@MyAccount, null,
resources.getString(R.string.alert_logging_message), false
)
}
}
override fun onPostExecute(data: Connection.Payload) {
if (mProgressDialog != null) {
mProgressDialog!!.dismiss()
}
if (data.success) {
Timber.i("User successfully logged in!")
saveUserInformation(data.data[0] as String, data.data[1] as String)
val i = [email protected]
if (i.hasExtra("notLoggedIn") && i.extras!!.getBoolean("notLoggedIn", false)) {
[email protected](RESULT_OK, i)
finishWithAnimation(ActivityTransitionAnimation.Direction.FADE)
} else {
// Show logged view
mUsernameLoggedIn.text = data.data[0] as String
switchToState(STATE_LOGGED_IN)
}
} else {
Timber.e("Login failed, error code %d", data.returnType)
if (data.returnType == 403) {
showSnackbar(R.string.invalid_username_password)
} else {
val message = resources.getString(R.string.connection_error_message)
val result = data.result
if (result.isNotEmpty() && result[0] is Exception) {
showSimpleMessageDialog(
title = message,
message = getHumanReadableLoginErrorMessage(result[0] as Exception),
reload = false
)
} else {
showSnackbar(message)
}
}
}
}
override fun onDisconnected() {
showLoginLogMessage(R.string.youre_offline, "")
}
}
protected fun getHumanReadableLoginErrorMessage(exception: Exception?): String? {
if (exception == null) {
return ""
}
if (exception is CustomSyncServerUrlException) {
val url = exception.url
return resources.getString(R.string.sync_error_invalid_sync_server, url)
}
if (exception.cause != null) {
val cause = exception.cause
if (cause is UnknownHostException) {
return getString(R.string.sync_error_unknown_host_readable, exception.localizedMessage)
}
}
return exception.localizedMessage
}
private val isScreenSmall: Boolean
get() = (
(
this.applicationContext.resources.configuration.screenLayout
and Configuration.SCREENLAYOUT_SIZE_MASK
)
< Configuration.SCREENLAYOUT_SIZE_LARGE
)
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
if (isScreenSmall && newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
mAnkidroidLogo.visibility = View.GONE
} else {
mAnkidroidLogo.visibility = View.VISIBLE
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) {
Timber.i("MyAccount - onBackPressed()")
finishWithAnimation(ActivityTransitionAnimation.Direction.FADE)
return true
}
return super.onKeyDown(keyCode, event)
}
companion object {
@KotlinCleanup("change to enum")
internal const val STATE_LOG_IN = 1
internal const val STATE_LOGGED_IN = 2
}
}
| gpl-3.0 | aa5a6229b1e30e6c1d6bd68d4cd4d53e | 40.598338 | 170 | 0.579743 | 5.176491 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/PublishersFragment.kt | 1 | 5413 | package com.boardgamegeek.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.RecyclerView
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentPublishersBinding
import com.boardgamegeek.databinding.RowPublisherBinding
import com.boardgamegeek.entities.CompanyEntity
import com.boardgamegeek.extensions.inflate
import com.boardgamegeek.extensions.loadThumbnailInList
import com.boardgamegeek.ui.adapter.AutoUpdatableAdapter
import com.boardgamegeek.ui.viewmodel.PublishersViewModel
import com.boardgamegeek.ui.widget.RecyclerSectionItemDecoration
import kotlin.properties.Delegates
class PublishersFragment : Fragment() {
private var _binding: FragmentPublishersBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<PublishersViewModel>()
private val adapter: PublisherAdapter by lazy { PublisherAdapter(viewModel) }
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentPublishersBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.adapter = adapter
binding.recyclerView.addItemDecoration(
RecyclerSectionItemDecoration(resources.getDimensionPixelSize(R.dimen.recycler_section_header_height), adapter)
)
binding.swipeRefresh.setOnRefreshListener { viewModel.refresh() }
viewModel.publishers.observe(viewLifecycleOwner) {
adapter.publishers = it
binding.recyclerView.isVisible = adapter.itemCount > 0
binding.emptyTextView.isVisible = adapter.itemCount == 0
binding.progressBar.hide()
binding.swipeRefresh.isRefreshing = false
}
viewModel.progress.observe(viewLifecycleOwner) {
if (it == null) {
binding.horizontalProgressBar.progressContainer.isVisible = false
} else {
binding.horizontalProgressBar.progressContainer.isVisible = it.second > 0
binding.horizontalProgressBar.progressView.max = it.second
binding.horizontalProgressBar.progressView.progress = it.first
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
class PublisherAdapter(private val viewModel: PublishersViewModel) : RecyclerView.Adapter<PublisherAdapter.PublisherViewHolder>(),
AutoUpdatableAdapter, RecyclerSectionItemDecoration.SectionCallback {
var publishers: List<CompanyEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue ->
autoNotify(oldValue, newValue) { old, new ->
old.id == new.id
}
}
init {
setHasStableIds(true)
}
override fun getItemCount() = publishers.size
override fun getItemId(position: Int) = publishers.getOrNull(position)?.id?.toLong() ?: RecyclerView.NO_ID
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PublisherViewHolder {
return PublisherViewHolder(parent.inflate(R.layout.row_publisher))
}
override fun onBindViewHolder(holder: PublisherViewHolder, position: Int) {
holder.bind(publishers.getOrNull(position))
}
override fun isSection(position: Int): Boolean {
if (position == RecyclerView.NO_POSITION) return false
if (publishers.isEmpty()) return false
if (position == 0) return true
val thisLetter = viewModel.getSectionHeader(publishers.getOrNull(position))
val lastLetter = viewModel.getSectionHeader(publishers.getOrNull(position - 1))
return thisLetter != lastLetter
}
override fun getSectionHeader(position: Int): CharSequence {
return when {
position == RecyclerView.NO_POSITION -> "-"
publishers.isEmpty() -> "-"
else -> viewModel.getSectionHeader(publishers.getOrNull(position))
}
}
inner class PublisherViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val binding = RowPublisherBinding.bind(itemView)
fun bind(publisher: CompanyEntity?) {
publisher?.let { p ->
binding.thumbnailView.loadThumbnailInList(p.thumbnailUrl)
binding.nameView.text = p.name
binding.countView.text = itemView.context.resources.getQuantityString(R.plurals.games_suffix, p.itemCount, p.itemCount)
binding.whitmoreScoreView.text = itemView.context.getString(R.string.whitmore_score).plus(" ${p.whitmoreScore}")
itemView.setOnClickListener {
PersonActivity.startForPublisher(itemView.context, p.id, p.name)
}
}
}
}
}
}
| gpl-3.0 | 7b844e3293df5d4dea8f761fffe31c33 | 41.960317 | 139 | 0.682616 | 5.240077 | false | false | false | false |
Deanveloper/Overcraft | src/main/java/com/deanveloper/overcraft/Overcraft.kt | 1 | 3335 | package com.deanveloper.overcraft
import com.deanveloper.overcraft.commands.HeroCommand
import com.deanveloper.overcraft.util.OcPlayer
import org.bukkit.Bukkit
import org.bukkit.entity.*
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.entity.EntityDamageByEntityEvent
import org.bukkit.event.entity.EntityDamageEvent
import org.bukkit.event.entity.PlayerDeathEvent
import org.bukkit.event.player.PlayerItemDamageEvent
import org.bukkit.plugin.java.JavaPlugin
/**
* @author Dean
*/
private var _PLUGIN: Overcraft? = null
val PLUGIN: Overcraft
get() = _PLUGIN!!
class Overcraft : JavaPlugin() {
override fun onEnable() {
_PLUGIN = this
Bukkit.getPluginManager().registerEvents(GeneralListener, this)
getCommand("hero").executor = HeroCommand
getCommand("hero").tabCompleter = HeroCommand
}
}
val Player.oc: OcPlayer
get() = OcPlayer[this]
object GeneralListener : Listener {
@EventHandler
fun onDeath(d: PlayerDeathEvent) {
d.deathMessage = "${d.entity.displayName} was killed"
val p = OcPlayer[d.entity]
val lastAttacker = p.lastAttacker
if (lastAttacker !== null) {
d.deathMessage += " by ${lastAttacker.displayName}"
}
d.keepInventory = true
d.keepLevel = true
d.drops.clear()
p.onDeath()
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
fun cancelNonCustom(e: EntityDamageByEntityEvent) {
val ent = e.entity
val damager = e.damager
// if a player has a hero selected, make sure that their hits don't register
// unless the plugin does it for them
if (damager is Projectile) {
val shooter = damager.shooter
// if a hero is selected
if (shooter is Player) {
if (shooter.oc.hero !== null) {
if(e.cause !== EntityDamageEvent.DamageCause.CUSTOM) {
e.isCancelled = true
}
}
}
} else if (damager.type === EntityType.PLAYER) {
damager as Player
// if a hero is selected
if (damager.oc.hero !== null) {
// refuse damage dealt by them if it is not magic
if(e.cause !== EntityDamageEvent.DamageCause.CUSTOM) {
e.isCancelled = true
}
}
}
if (ent.type.isAlive) {
ent as LivingEntity
ent.noDamageTicks = 0
ent.maximumNoDamageTicks = 0
}
}
fun noItemDamage(e: PlayerItemDamageEvent) {
if(e.player?.oc?.hero === null) {
e.isCancelled = true
}
}
}
fun LivingEntity.hurt(damage: Double, from: Entity) {
if (this.type === EntityType.PLAYER) {
this as Player // smart cast
if (from is Projectile && from.shooter is Player) {
from as Player // smart cast
this.oc.lastAttacker = from.oc
} else if (from.type === EntityType.PLAYER) {
from as Player // smart cast
this.oc.lastAttacker = from.oc
}
}
this.damage(damage)
this.maximumNoDamageTicks = 0
this.noDamageTicks = 0
} | mit | 3c432f001ef03a421608bf81cb34e0c7 | 29.605505 | 84 | 0.604798 | 4.205549 | false | false | false | false |
cfig/Android_boot_image_editor | bbootimg/src/main/kotlin/bootimg/cpio/AndroidCpio.kt | 1 | 13539 | // 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 cfig.bootimg.cpio
import cfig.helper.Helper
import cfig.utils.EnvironmentVerifier
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream
import org.apache.commons.compress.archivers.cpio.CpioConstants
import org.slf4j.LoggerFactory
import java.io.*
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.regex.Pattern
class AndroidCpio {
private var inodeNumber: Long = 0L
private val fsConfig: MutableSet<AndroidCpioEntry> = mutableSetOf()
private val fsConfigTemplate: List<FsConfigTemplate> = loadFsConfigTemplate()
data class FsConfigTemplate(
var type: String = "REG",
var mode: String = "",
var uid: Int = 0,
var gid: Int = 0,
var prefix: String = ""
)
private fun packItem(root: File, item: File, outStream: OutputStream) {
if ((item.path == root.path) && !Files.isDirectory(item.toPath())) {
throw IllegalArgumentException("root path is not dir")
}
if (item.path == root.path) { //first visit to root
val fileList = item.listFiles()?.apply { sortBy { it.name } }
if (fileList != null) {
for (subItem in fileList) {
packItem(root, subItem, outStream)
}
}
} else { //later visit
val newOutname = if (EnvironmentVerifier().isWindows) {
item.path.substring(root.path.length + 1).replace("\\", "/")
} else {
item.path.substring(root.path.length + 1) //remove leading slash
}
log.debug(item.path + " ~ " + root.path + " => " + newOutname)
val entry = when {
Files.isSymbolicLink(item.toPath()) -> {
val target = Files.readSymbolicLink(Paths.get(item.path))
log.debug("LNK: " + item.path + " --> " + target)
AndroidCpioEntry(
name = newOutname,
statMode = java.lang.Long.valueOf("120644", 8),
data = target.toString().toByteArray(),
ino = inodeNumber++
)
}
Files.isDirectory(item.toPath()) -> {
log.debug("DIR: " + item.path + ", " + item.toPath())
AndroidCpioEntry(
name = newOutname,
statMode = java.lang.Long.valueOf("40755", 8),
data = byteArrayOf(),
ino = inodeNumber++
)
}
Files.isRegularFile(item.toPath()) -> {
log.debug("REG: " + item.path)
AndroidCpioEntry(
name = newOutname,
statMode = java.lang.Long.valueOf("100644", 8),
data = item.readBytes(),
ino = inodeNumber++
)
}
else -> {
throw IllegalArgumentException("do not support file " + item.name)
}
}
log.debug("_eject: " + item.path)
//fix_stat
fixStat(entry)
outStream.write(entry.encode())
if (Files.isDirectory(item.toPath()) && !Files.isSymbolicLink(item.toPath())) {
val fileList = item.listFiles()?.apply { sortBy { it.name } }
if (fileList != null) {
for (subItem in fileList) {
packItem(root, subItem, outStream)
}
}
}
}
}
private fun fnmatch(fileName: String, pattern: String): Boolean {
return if (fileName == pattern) {
true
} else {
Pattern.compile(
"^" + pattern.replace(".", "\\.")
.replace("/", "\\/")
.replace("*", ".*") + "$"
).matcher(fileName).find()
}
}
private fun fixStat(entry: AndroidCpioEntry) {
val itemConfig = fsConfig.filter { it.name == entry.name }
when (itemConfig.size) {
0 -> { /* do nothing */
val matches = fsConfigTemplate
.filter { fnmatch(entry.name, it.prefix) }
.sortedByDescending { it.prefix.length }
if (matches.isNotEmpty()) {
val ftBits = NewAsciiCpio(c_mode = entry.statMode).let {
when {
it.isSymbolicLink() -> CpioConstants.C_ISLNK
it.isRegularFile() -> CpioConstants.C_ISREG
it.isDirectory() -> CpioConstants.C_ISDIR
else -> throw IllegalArgumentException("unsupported st_mode " + it.c_mode)
}
}
entry.statMode = ftBits.toLong() or java.lang.Long.valueOf(matches[0].mode, 8)
log.warn("${entry.name} ~ " + matches.map { it.prefix }.reduce { acc, s -> "$acc, $s" }
+ ", stMode=" + java.lang.Long.toOctalString(entry.statMode))
} else {
log.warn("${entry.name} has NO fsconfig/prefix match")
}
}
1 -> {
log.debug("${entry.name} == preset fsconfig")
entry.statMode = itemConfig[0].statMode
}
else -> {
//Issue #75: https://github.com/cfig/Android_boot_image_editor/issues/75
//Reason: cpio may have multiple entries with the same name, that's caused by man-made errors
val msg = "(${entry.name} has multiple exact-match fsConfig, " +
"check https://github.com/cfig/Android_boot_image_editor/issues/75"
errLog.warn("IllegalArgumentException$msg")
if (Helper.prop("config.allow_cpio_duplicate") == "true") {
log.warn("IllegalArgumentException$msg")
entry.statMode = itemConfig[0].statMode
} else {
throw IllegalArgumentException(msg)
}
}
}
}
fun pack(inDir: String, outFile: String, propFile: String? = null) {
inodeNumber = 300000L
fsConfig.clear()
propFile?.let {
if (File(propFile).exists()) {
log.info("loading $propFile")
File(propFile).readLines().forEach { line ->
fsConfig.add(ObjectMapper().readValue(line, AndroidCpioEntry::class.java))
}
} else {
log.warn("fsConfig file $propFile has been deleted, using fsConfig prefix matcher")
}
}
FileOutputStream(outFile).use { fos ->
packItem(File(inDir), File(inDir), fos)
val trailer = AndroidCpioEntry(
name = "TRAILER!!!",
statMode = java.lang.Long.valueOf("0755", 8),
ino = inodeNumber++
)
fixStat(trailer)
fos.write(trailer.encode())
}
val len = File(outFile).length()
val rounded = Helper.round_to_multiple(len, 256) //file in page 256
if (len != rounded) {
FileOutputStream(outFile, true).use { fos ->
fos.write(ByteArray((rounded - len).toInt()))
}
}
}
private fun loadFsConfigTemplate(): List<FsConfigTemplate> {
val reader =
BufferedReader(InputStreamReader(AndroidCpio::class.java.classLoader.getResourceAsStream("fsconfig.txt")!!))
val oM = ObjectMapper().apply {
configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
}
return reader.readLines().map { oM.readValue(it, FsConfigTemplate::class.java) }
}
companion object {
private val log = LoggerFactory.getLogger(AndroidCpio::class.java)
private val errLog = LoggerFactory.getLogger("uiderrors")
private val PERM_MASK = java.lang.Long.valueOf("777", 8)
fun decompressCPIO(cpioFile: String, outDir: String, fileList: String? = null) {
run { //clean up
if (File(outDir).exists()) {
log.info("Cleaning $outDir ...")
File(outDir).deleteRecursively()
}
File(outDir).mkdir()
}
val cis = CpioArchiveInputStream(FileInputStream(cpioFile))
val fileListDump = if (fileList != null) FileOutputStream(fileList) else null
while (true) {
val entry = cis.nextCPIOEntry ?: break
val entryInfo = AndroidCpioEntry(
name = entry.name,
statMode = entry.mode,
ino = entry.inode,
note = String.format(Locale.getDefault(), "%6s", java.lang.Long.toOctalString(entry.mode))
)
if (!cis.canReadEntryData(entry)) {
throw RuntimeException("can not read entry ??")
}
val buffer = ByteArray(entry.size.toInt())
cis.read(buffer)
val outEntryName = File(outDir + "/" + entry.name).path
if (((entry.mode and PERM_MASK).shr(7)).toInt() != 0b11) {
//@formatter:off
log.warn(" root/${entry.name} has improper file mode "
+ String.format(Locale.getDefault(), "%03o, ", entry.mode and PERM_MASK) + "fix it"
)
//@formatter:on
}
when {
entry.isSymbolicLink -> {
entryInfo.note = ("LNK " + entryInfo.note)
if (EnvironmentVerifier().isWindows) {
File(outEntryName).writeBytes(buffer)
} else {
Files.createSymbolicLink(Paths.get(outEntryName), Paths.get(String(buffer)))
}
}
entry.isRegularFile -> {
entryInfo.note = ("REG " + entryInfo.note)
File(outEntryName).also { it.parentFile.mkdirs() }.writeBytes(buffer)
if (EnvironmentVerifier().isWindows) {
//Windows: Posix not supported
} else {
Files.setPosixFilePermissions(
Paths.get(outEntryName),
Helper.modeToPermissions(((entry.mode and PERM_MASK) or 0b111_000_000).toInt())
)
}
}
entry.isDirectory -> {
entryInfo.note = ("DIR " + entryInfo.note)
File(outEntryName).mkdir()
if (!EnvironmentVerifier().isWindows) {
Files.setPosixFilePermissions(
Paths.get(outEntryName),
Helper.modeToPermissions(((entry.mode and PERM_MASK) or 0b111_000_000).toInt())
)
} else {
//Windows
}
}
else -> throw IllegalArgumentException("??? type unknown")
}
File(outEntryName).setLastModified(entry.time)
log.debug(entryInfo.toString())
fileListDump?.write(ObjectMapper().writeValueAsString(entryInfo).toByteArray())
fileListDump?.write("\n".toByteArray())
}
val bytesRead = cis.bytesRead
cis.close()
val remaining = FileInputStream(cpioFile).use { fis ->
fis.skip(bytesRead - 128)
fis.readBytes()
}
val foundIndex = String(remaining, Charsets.UTF_8).lastIndexOf("070701")
val entryInfo = AndroidCpioEntry(
name = CpioConstants.CPIO_TRAILER,
statMode = java.lang.Long.valueOf("755", 8)
)
if (foundIndex != -1) {
val statusModeStr = String(remaining, Charsets.UTF_8).substring(foundIndex + 14, foundIndex + 22)
entryInfo.statMode = java.lang.Long.valueOf(statusModeStr, 16)
log.info("cpio trailer found, mode=$statusModeStr")
} else {
log.error("no cpio trailer found")
}
fileListDump?.write(ObjectMapper().writeValueAsString(entryInfo).toByteArray())
fileListDump?.close()
}
}
}
| apache-2.0 | 7853cb49269aedf838153aef6ff80dd3 | 43.536184 | 120 | 0.502991 | 4.768933 | false | true | false | false |
RoverPlatform/rover-android | core/src/main/kotlin/io/rover/sdk/core/platform/StringExtensions.kt | 1 | 2006 | @file:JvmName("StringExtensions")
package io.rover.sdk.core.platform
import android.os.Build
import android.text.Html
import android.text.SpannableStringBuilder
fun String.roverTextHtmlAsSpanned(): SpannableStringBuilder {
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
@Suppress("DEPRECATION")
val spannedBuilder = Html.fromHtml(this) as SpannableStringBuilder
// the legacy version of android.text.Html (ie without
// Html.FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH), Html.fromHtml() returns one additional
// excessive newline (specifically, a \n character) per each paragraph in the source HTML.
// So, for every run of newlines in the output spannable, we want to remove one of the
// newlines.
val indexesOfSuperfluousNewlines = spannedBuilder.foldIndexed(listOf<Int>()) { index, accumulatedIndexes, character ->
if (character != '\n' && index > 0 && spannedBuilder[index - 1] == '\n') {
// a sequence of \n's is terminating. drop the last one.
// TODO: the append operation here is causing unnecessary copies
accumulatedIndexes + (index - 1)
} else {
accumulatedIndexes
}
}
// now to remove all of these discovered extra newlines.
var deletionDeflection = 0
indexesOfSuperfluousNewlines.forEach {
// mutate the spanned builder.
spannedBuilder.delete(it + deletionDeflection, it + deletionDeflection + 1)
deletionDeflection -= 1
}
spannedBuilder
} else {
Html.fromHtml(this, Html.FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH) as SpannableStringBuilder
}
}
/**
* Parse the given string as URI query parameters.
*/
fun String.parseAsQueryParameters(): Map<String, String> {
return split("&").map {
val keyAndValue = it.split("=")
Pair(keyAndValue.first(), keyAndValue[1])
}.associate { it }
}
| apache-2.0 | aaf82f3dfa7965055ce8152564c33c0a | 38.333333 | 126 | 0.649551 | 4.611494 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/services/preloading/PreloadManager.kt | 1 | 4737 | package com.pr0gramm.app.services.preloading
import com.pr0gramm.app.Duration
import com.pr0gramm.app.Instant
import com.pr0gramm.app.Logger
import com.pr0gramm.app.db.PreloadItemQueries
import com.pr0gramm.app.ui.base.AsyncScope
import com.pr0gramm.app.util.*
import com.squareup.sqldelight.runtime.coroutines.asFlow
import com.squareup.sqldelight.runtime.coroutines.mapToList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.runInterruptible
import java.io.File
private fun intervalFlow(): Flow<Unit> {
return flow {
while (true) {
emit(Unit)
delay(Duration.minutes(10))
}
}
}
/**
*/
class PreloadManager(private val db: PreloadItemQueries) {
private val logger = Logger("PreloadManager")
@Volatile
private var preloadCache = LongSparseArray<PreloadItem>()
private val observeAllItems = intervalFlow()
.flatMapLatest { db.all(this::mapper).asFlow().mapToList() }
.map { items -> validateItems(items) }
init {
AsyncScope.launch {
// initialize and cache in background for polling
observeAllItems.collect { preloadCache = it }
}
}
private fun mapper(itemId: Long, creationTime: Long, media: String, thumbnail: String, fullThumbnail: String?): PreloadItem {
return PreloadItem(
itemId = itemId,
creation = Instant(creationTime),
media = File(media),
thumbnail = File(thumbnail),
thumbnailFull = fullThumbnail?.let(::File)
)
}
private suspend fun validateItems(items: List<PreloadItem>): LongSparseArray<PreloadItem> {
val missing = mutableListOf<PreloadItem>()
val available = mutableListOf<PreloadItem>()
runInterruptible(Dispatchers.IO) {
// check if all files still exist
for (item in items) {
if (!item.thumbnail.exists() || !item.media.exists()) {
missing += item
} else {
available += item
}
}
}
if (missing.isNotEmpty()) {
// delete missing entries in background.
doInBackground { deleteItems(missing) }
}
return longSparseArrayOf(available) { it.itemId }
}
/**
* Inserts the given entry blockingly into the database. Must not be run on the main thread.
*/
fun store(entry: PreloadItem) {
checkNotMainThread()
db.save(entry.itemId, entry.creation.millis, entry.media.path, entry.thumbnail.path, entry.thumbnailFull?.path)
}
/**
* Checks if an entry with the given itemId already exists in the database.
*/
fun exists(itemId: Long): Boolean {
return preloadCache.containsKey(itemId)
}
/**
* Returns the [PreloadItem] with a given id.
*/
operator fun get(itemId: Long): PreloadItem? {
return preloadCache[itemId]
}
fun deleteOlderThan(threshold: Instant) {
logger.info { "Removing all files preloaded before $threshold" }
deleteItems(preloadCache.values().filter { it.creation < threshold })
}
private fun deleteItems(items: Iterable<PreloadItem>) {
checkNotMainThread()
db.transaction {
for (item in items) {
logger.info { "Removing files for itemId=${item.itemId}" }
if (!item.media.delete()) {
logger.warn { "Could not delete media file ${item.media}" }
}
if (!item.thumbnail.delete()) {
logger.warn { "Could not delete thumbnail file ${item.thumbnail}" }
}
if (item.thumbnailFull?.delete() == false) {
logger.warn { "Could not delete thumbnail file ${item.thumbnailFull}" }
}
// delete entry from database
db.deleteOne(item.itemId)
}
}
}
val currentItems: LongSparseArray<PreloadItem>
get() = preloadCache.clone()
val items: Flow<LongSparseArray<PreloadItem>> = observeAllItems
/**
* A item that was preloaded.
*/
class PreloadItem(val itemId: Long, val creation: Instant, val media: File, val thumbnail: File, val thumbnailFull: File?) {
override fun hashCode(): Int = itemId.hashCode()
override fun equals(other: Any?): Boolean {
return other is PreloadItem && other.itemId == itemId
}
}
}
| mit | 5629686e787405e8806c789965903496 | 30.370861 | 129 | 0.612624 | 4.585673 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/fragments/OverscrollLinearSmoothScroller.kt | 1 | 1470 | package com.pr0gramm.app.ui.fragments
import android.content.Context
import androidx.recyclerview.widget.LinearSmoothScroller
import kotlin.math.absoluteValue
class OverscrollLinearSmoothScroller(
context: Context, idx: Int,
private val dontScrollIfVisible: Boolean,
private val offsetTop: Int,
private val offsetBottom: Int) : LinearSmoothScroller(context) {
init {
targetPosition = idx
}
override fun calculateDtToFit(viewStart: Int, viewEnd: Int, boxStart: Int, boxEnd: Int, snapPreference: Int): Int {
val dTop = boxStart - (viewStart - offsetTop)
val dBot = boxEnd - (viewEnd + offsetBottom)
return if (dTop.absoluteValue < dBot.absoluteValue) {
if (dontScrollIfVisible && dTop < 0) 0 else dTop
} else {
if (dontScrollIfVisible && dBot > 0) 0 else dBot
}
}
}
class CenterLinearSmoothScroller(ctx: Context, idx: Int) : LinearSmoothScroller(ctx) {
init {
targetPosition = idx
}
override fun calculateDtToFit(viewStart: Int, viewEnd: Int, boxStart: Int, boxEnd: Int, snapPreference: Int): Int {
return boxStart + (boxEnd - boxStart) / 2 - (viewStart + (viewEnd - viewStart) / 2)
}
}
class EndOfViewSmoothScroller(context: Context, idx: Int) : LinearSmoothScroller(context) {
init {
targetPosition = idx
}
override fun getVerticalSnapPreference(): Int {
return SNAP_TO_END
}
}
| mit | 9a9f75077f3344e83e48074a647b8bc3 | 30.956522 | 119 | 0.667347 | 3.930481 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/providers/medialibrary/VideosProvider.kt | 1 | 3484 | /*****************************************************************************
* VideosProvider.kt
*****************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc.providers.medialibrary
import android.content.Context
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import org.videolan.medialibrary.interfaces.media.Folder
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.medialibrary.interfaces.media.VideoGroup
import org.videolan.vlc.media.getAll
import org.videolan.vlc.viewmodels.SortableModel
@ExperimentalCoroutinesApi
class VideosProvider(val folder : Folder?, val group: VideoGroup?, context: Context, model: SortableModel) : MedialibraryProvider<MediaWrapper>(context, model){
override fun canSortByFileNameName() = true
override fun canSortByDuration() = true
override fun canSortByLastModified() = folder == null
override fun getTotalCount() = if (model.filterQuery == null) when {
folder !== null -> folder.mediaCount(Folder.TYPE_FOLDER_VIDEO)
group !== null -> group.mediaCount()
else -> medialibrary.videoCount
} else when {
folder !== null -> folder.searchTracksCount(model.filterQuery, Folder.TYPE_FOLDER_VIDEO)
group !== null -> group.searchTracksCount(model.filterQuery)
else -> medialibrary.getVideoCount(model.filterQuery)
}
override fun getPage(loadSize: Int, startposition: Int): Array<MediaWrapper> {
val list = if (model.filterQuery == null) when {
folder !== null -> folder.media(Folder.TYPE_FOLDER_VIDEO, sort, desc, loadSize, startposition)
group !== null -> group.media(sort, desc, loadSize, startposition)
else -> medialibrary.getPagedVideos(sort, desc, loadSize, startposition)
} else when {
folder !== null -> folder.searchTracks(model.filterQuery, Folder.TYPE_FOLDER_VIDEO, sort, desc, loadSize, startposition)
group !== null -> group.searchTracks(model.filterQuery, sort, desc, loadSize, startposition)
else -> medialibrary.searchVideo(model.filterQuery, sort, desc, loadSize, startposition)
}
model.viewModelScope.launch { completeHeaders(list, startposition) }
return list
}
override fun getAll(): Array<MediaWrapper> = when {
folder !== null -> folder.getAll(Folder.TYPE_FOLDER_VIDEO, sort, desc).toTypedArray()
group !== null -> group.getAll(sort, desc).toTypedArray()
else -> medialibrary.getVideos(sort, desc)
}
}
| gpl-2.0 | 963adf1eed2d8c8a368cf13a851053e6 | 48.757143 | 160 | 0.674419 | 4.732337 | false | false | false | false |
NextFaze/dev-fun | devfun/src/main/java/com/nextfaze/devfun/core/DefinitionsProcessor.kt | 1 | 7480 | package com.nextfaze.devfun.core
import android.os.Debug
import android.text.SpannableStringBuilder
import com.nextfaze.devfun.category.CategoryDefinition
import com.nextfaze.devfun.category.CategoryItem
import com.nextfaze.devfun.error.ErrorHandler
import com.nextfaze.devfun.function.FunctionDefinition
import com.nextfaze.devfun.function.FunctionItem
import com.nextfaze.devfun.function.FunctionTransformer
import com.nextfaze.devfun.internal.exception.ExceptionCategoryItem
import com.nextfaze.devfun.internal.exception.stackTraceAsString
import com.nextfaze.devfun.internal.log.*
import com.nextfaze.devfun.internal.prop.*
import com.nextfaze.devfun.internal.splitSimpleName
import com.nextfaze.devfun.internal.string.*
import java.util.concurrent.atomic.AtomicInteger
import kotlin.reflect.KClass
internal class DefinitionsProcessor(private val devFun: DevFun) {
private val log = logger()
private val transformers by lazy { TRANSFORMERS.map { devFun.instanceOf(it) } }
private val errorHandler by lazy { devFun.get<ErrorHandler>() }
private val userDefinedCategories by lazy {
devFun.definitions
.flatMap { it.categoryDefinitions }
.toSet()
.associateBy { it.clazz }
}
private val categoryDefinitions by lazy { userDefinedCategories.mapKeys { it.value.displayString }.toMutableMap() }
@Suppress("ConstantConditionIf")
private val tracing by threadLocal { if (false) AtomicInteger(0) else null }
fun getTransformedDefinitions(): List<CategoryItem> {
if (tracing?.getAndIncrement() == 0) {
Debug.startMethodTracing("DefinitionsProcessor.getTransformedDefinitions.${Thread.currentThread().id}")
}
return try {
transformedDefinitions()
} catch (t: Throwable) {
errorHandler.onError(t, "Generate Categories", "Exception while attempting to generate categories.")
listOf(ExceptionCategoryItem(t.stackTraceAsString))
} finally {
if (tracing?.decrementAndGet() == 0) {
Debug.stopMethodTracing()
}
}
}
private fun transformedDefinitions(): List<CategoryItem> {
val functionItems = mutableListOf<FunctionItem>()
devFun.definitions
.flatMap { it.functionDefinitions }
.toSet()
.forEach {
try {
it.applyTransformers(transformers, functionItems)
} catch (t: Throwable) {
errorHandler.onError(
t,
"Function Transformation",
SpannableStringBuilder().apply {
this += u("Failed to transform function definition:\n")
this += pre(it.toString())
this += u("\nOn method:\n")
this += pre(it.method.toString())
}
)
}
}
return functionItems
.groupBy {
// determine category name for item
it.category.name ?: it.category.clazz?.splitSimpleName ?: "Misc"
}
.mapKeys { (categoryName, functionItems) ->
// create category object for items and determine order
val order = functionItems.firstOrNull { it.category.order != null }?.category?.order ?: 0
SimpleCategoryItem(categoryName, functionItems, order)
}
.keys
.sortedWith(compareBy<SimpleCategoryItem> { it.order }.thenBy { it.name.toString() })
}
private fun FunctionDefinition.applyTransformers(transformers: List<FunctionTransformer>, functionItems: MutableList<FunctionItem>) {
log.t { "Processing ${clazz.java.simpleName}::$name" }
val resolvedCategory = resolveCategoryDefinition()
transformers.forEach { transformer ->
if (!transformer.accept(this)) {
log.t { "Transformer $transformer ignored item" }
return@forEach
}
val items = transformer.apply(this, resolvedCategory)
log.t { "Transformer $transformer accepted item and returned ${items?.size} items: ${items?.joinToString { it.name }}" }
if (items != null) {
functionItems.addAll(items)
return // accepted and transformed by transformer - halt further transformations
}
}
}
private fun FunctionDefinition.resolveCategoryDefinition(): CategoryDefinition {
val category = category
?: return getOrCreateCategoryDefinitionForClass(categoryClass) // not defined at function - use class
val categoryName = category.name?.toString()
if (categoryName == null) { // they're overriding some class-level category
val parentCategory = getOrCreateCategoryDefinitionForClass(categoryClass)
return InheritingCategoryDefinition(parentCategory, category)
}
val parentCategory = categoryDefinitions[categoryName]
if (parentCategory == null) { // defining a new category
categoryDefinitions[categoryName] = category
return category
}
// inheriting some other previously defined category
return InheritingCategoryDefinition(parentCategory, category)
}
/** If a function definition is declared in a Companion object we want to use the "real" (outer) class for the category definition. */
private val resolvedCategoryClasses = mutableMapOf<KClass<*>, KClass<*>>()
private val FunctionDefinition.categoryClass: KClass<*>
get() = resolvedCategoryClasses[clazz]
?: try {
when {
clazz.java.enclosingClass != null && clazz.isCompanion -> clazz.java.enclosingClass!!.kotlin
else -> clazz
}
} catch (ignore: UnsupportedOperationException) {
clazz // happens with top-level functions (reflection not supported for them yet)
}.also {
resolvedCategoryClasses[clazz] = it
}
private fun getOrCreateCategoryDefinitionForClass(clazz: KClass<*>) =
userDefinedCategories[clazz] ?: getOrCreateCategoryDefinitionForName(clazz.splitSimpleName)
private fun getOrCreateCategoryDefinitionForName(name: String) =
categoryDefinitions.getOrPut(name) { SimpleCategoryDefinition(name) }
private val CategoryDefinition.displayString: String
get() = name?.toString() ?: clazz?.splitSimpleName ?: "Misc"
}
private class SimpleCategoryItem(
override val name: CharSequence,
override val items: List<FunctionItem>,
override val order: Int = 0
) : CategoryItem {
override fun equals(other: Any?) = if (other is CategoryItem) name == other.name else false
override fun hashCode() = name.hashCode()
}
private data class SimpleCategoryDefinition(override val name: String) : CategoryDefinition
private data class InheritingCategoryDefinition(val parent: CategoryDefinition, val child: CategoryDefinition) : CategoryDefinition {
override val clazz get() = child.clazz ?: parent.clazz
override val name get() = child.name ?: parent.name
override val group get() = child.group ?: parent.group
override val order get() = child.order ?: parent.order
}
| apache-2.0 | 561b899f749ce01821065a4a648118f8 | 42.488372 | 138 | 0.645053 | 5.278758 | false | false | false | false |
AoEiuV020/PaNovel | api/src/main/java/cc/aoeiuv020/panovel/api/site/liudatxt.kt | 1 | 5323 | package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.base.jar.ownTextListSplitWhitespace
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
/**
*
* Created by AoEiuV020 on 2017.10.11-19:39:27.
*/
class Liudatxt : DslJsoupNovelContext() { init {
site {
name = "溜达小说"
baseUrl = "http://www.txtshuku.org"
logo = "https://imgsa.baidu.com/forum/w%3D580/sign=1b4c19b5f0edab6474724dc8c737af81/4afa9ae93901213f074d29a25fe736d12e2e95b9.jpg"
}
search {
post {
url = "/search.php"
data {
"searchkey" to it
}
}
/*
<dl>
<dt>
<a href='/5447/'>
<img alt='都市之特种狂兵全文阅读' src="/headimgs/5/5447/s5447.jpg" onerror="this.src='/res/images/blank.jpg'" height="155">
</a>
</dt>
<dd>
<h3>
<a href='/so/5447/'>都市之特种狂兵</a>
<span class="alias"></span>
</h3>
</dd>
<dd class="book_other">作者:
<span>枯木</span>状态:
<span>连载中</span>分类:
<span>都市言情</span>字数:
<span>7211327</span>
</dd>
<dd class="book_des"> 一手夺命金针,一身玄奇功法!天才少年陆辰自深山中走出,凭借着一手神奇医术与霸道武学,一路...</dd>
<dd class="book_other">最新章节:
<a href='/so/5447/11558786.html'>正文 正文_第三千二百六十七章 血蛟战死</a> 更新时间:
<span>2018-05-21 01:59:56</span>
</dd>
</dl>
*/
document {
items("#sitembox > dl") {
name("> dd:nth-child(2) > h3 > a")
author("> dd:nth-child(3) > span:nth-child(1)")
}
}
}
// http://www.liudatxt.com/2034/
detailPageTemplate = "/%s/"
detail {
/*
<div class="bookright">
<div class="booktitle">
<h1>完美至尊</h1>
<span id="author">作者:<a href="/author/观鱼/" target="_blank" rel="nofollow">观鱼</a></span>
</div>
<div class="count">
<ul>
<li>分 类:<span>玄幻奇幻</span></li>
<li>周点击:<span>94</span></li>
<li>月点击:<span>5677</span></li>
<li>总点击:<span id="Hits">2951590</span></li>
<li>状 态:<span>连载中</span></li>
<li>总推荐:<span>95</span></li>
<li>总字数:<span>10445478</span></li>
</ul>
</div>
<div id="bookintro">
<p> 时代天运,武道纵横!少年林凌自小被封印,受尽欺辱,当一双神秘的眼瞳觉醒时,曾经的强者,古老的神话,神秘的遗迹出现在他双眼!他看到了逝去的时光,看到了远古神魔的秘密,他看到了古代顶阶功法,所有消失在历史长河的强者,通通被他看到了,借着古代强者的指点,他从渺小蝼蚁的世界底层,一步一个脚印,走上俾睨天下之路。</p>
</div>
<div class="new">
<span class="uptime">最后更新:<span>2018-05-21 10:23:05</span></span>
</div>
</div>
*/
document {
val bookright = element("#bookinfo > div.bookright")
novel {
name("> div.booktitle > h1", parent = bookright)
author(" > div.booktitle > span#author > a", parent = bookright)
}
image("#bookimg > img")
introduction("#bookintro > p", parent = bookright)
update(" > div.new > span > span", parent = bookright, format = "yyyy-MM-dd HH:mm:ss")
}
}
// http://www.liudatxt.com/so/2034/
chaptersPageTemplate = "/so/%s/"
chapters {
/*
<li><a href="/so/2034/529879.html" title="正文_第十四章 前往山望镇" target="_blank">正文_第十四章 前往山望镇</a></li>
*/
document {
items("#readerlist > ul > li > a")
lastUpdate("#smallcons > span:nth-child(6)", format = "yyyy-MM-dd HH:mm:ss")
}
}
// http://www.liudatxt.com/so/2034/529879.html
contentPageTemplate = "/so/%s.html"
content {
/*
<div id="content" style="font-size: 24px; font-family: 华文楷体;">
第十四章 前往山望镇
<br> "去不去山望镇?那里有拍卖会呢,说不定能买到不错的东西!"
<br><i><a href="/8843/">万神之祖最新章节</a></i>
<br> 众人从蚰蜒落下,向着山望镇走去,这里有着十万大山各方武者,除此外,还有四大门派的弟子,其分别是飞雪宫,狂刀派,落叶门与古颜派!
</div>
*/
document {
// 去广告,"#content > i"都是广告,
items("#content") {
it.ownTextListSplitWhitespace()
}
}
}
}
}
| gpl-3.0 | 27fcbceb15a0c0c2fe79b13232bde336 | 33.960317 | 174 | 0.482633 | 2.640887 | false | false | false | false |
didi/DoraemonKit | Android/dokit-test/src/main/java/com/didichuxing/doraemonkit/kit/test/event/AccessibilityEventNode.kt | 1 | 1367 | package com.didichuxing.doraemonkit.kit.test.event
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/12/14-11:37
* 描 述:
* 修订历史:
* ================================================
*/
data class AccessibilityEventNode(
/**
* View comm & clicked & long clicked & focused Event Property
*/
val eventType: Int? = -1,
val className: String? = "",
val packageName: String? = "",
val eventTime: Long? = -1,
/**
* View Text Changed Event Property
*/
//val text: MutableList<CharSequence>?,
val beforeText: String? = "",
val fromIndex: Int? = -1,
val addedCount: Int? = -1,
val removedCount: Int? = -1,
/**
* View text traversed at movement granularity
*/
val movementGranularity: Int? = -1,
val toIndex: Int? = -1,
val action: Int? = -1,
/**
* View scrolled
*/
val maxScrollX: Int? = -1,
val maxScrollY: Int? = -1,
val scrollDeltaX: Int? = -1,
val scrollDeltaY: Int? = -1,
val scrollX: Int? = -1,
val scrollY: Int? = -1,
val scrollable: Boolean? = false,
/**
* Window state changed & Window content changed
*/
val contentChangeTypes: Int? = -1,
/**
*Windows changed
*/
val windowChanges: Int? = -1
)
| apache-2.0 | 04185559d7d97680bb4c7d60586a1441 | 24.403846 | 66 | 0.514762 | 3.70028 | false | false | false | false |
free5ty1e/primestationone-control-android | app/src/main/java/com/chrisprime/primestationonecontrol/utilities/TimeFormatter.kt | 1 | 7794 | package com.chrisprime.primestationonecontrol.utilities
import android.content.res.Resources
import android.support.annotation.StringRes
import android.support.v4.util.TimeUtils
import com.chrisprime.primestationonecontrol.PrimeStationOneControlApplication
import com.chrisprime.primestationonecontrol.R
import java.text.SimpleDateFormat
import java.util.*
/**
* A semi-sophisticated time formatter, that formats time in human relative terms.
*/
class TimeFormatter(internal val mResources: Resources) {
/**
* Formats the specified time. The placeholder %1$s in the specified resource will be replaced
* by the month and day (for future and past days) or the time (for today).
*
*
* If the time is some date in the future then it will use the
* format specified by resourceIdForFutureDay (example "Launches on Nov 27").
*
*
* If the time is today and the specified time is in the future it will use the
* resourceIdForTodayInFuture (example "Launches at 5:00pm).
*
*
* If the time is today and the specified time is in the past it will use the
* resourceIfForTodayInPast (example "Launched at 5:00pm" or "CLOSED")
*
*
* If the time is some date in the past then it will use the format specified
* by resourceIdForPastDay (example "Launched on Nov 27")
*
*
* If now is equal to the milliseconds to the specified time then it will use the
* resourceIdForTodayInFuture
*
*
* Please note this uses the TimeManagers time to determine relative time.
* @param resourceIdForFutureDay resource to use if date in future
* *
* @param resourceIdForTodayInFuture resource to use if time in future and it is today
* *
* @param resourceIdForTodayInPast resource to use if time is in the past and it is today
* *
* @param resourceIdForPastDay resource to use if the date is in the past
* *
* @param time the time to format
*/
fun formatAsHumanReadable(@StringRes resourceIdForFutureDay: Int,
@StringRes resourceIdForTodayInFuture: Int,
@StringRes resourceIdForTodayInPast: Int,
@StringRes resourceIdForPastDay: Int, time: Long): String {
val results: String
val nowInMs = TimeManager.instance.currentTimeMillis()
val now = Calendar.getInstance()
now.timeInMillis = nowInMs
now.timeZone = TimeZone.getDefault() //use the user's time zone, not UTC to figure out what is "now"
val importantDateAndTime = Calendar.getInstance()
importantDateAndTime.timeInMillis = time
importantDateAndTime.timeZone = TimeZone.getDefault()
if (now.get(Calendar.YEAR) == importantDateAndTime.get(Calendar.YEAR) && now.get(Calendar.DAY_OF_YEAR) == importantDateAndTime.get(Calendar.DAY_OF_YEAR)) {
//it is today
val formatter = SimpleDateFormat("h:mm a", Locale.US)
if (time >= nowInMs) {
// future & today
results = String.format(mResources.getString(resourceIdForTodayInFuture), formatter.format(time))
} else {
// today in the past
results = String.format(mResources.getString(resourceIdForTodayInPast), formatter.format(time))
}
} else if (time >= nowInMs) {
//future & not today
val formatter = SimpleDateFormat("MMM dd", Locale.US)
results = String.format(mResources.getString(resourceIdForFutureDay), formatter.format(time))
} else { //(time < nowInMs)
// that is the past & not today
val formatter = SimpleDateFormat("MMM dd", Locale.US)
results = String.format(mResources.getString(resourceIdForPastDay), formatter.format(time))
}
return results
}
companion object {
fun getFriendlyTime(periodInMilliseconds: Long, inPast: Boolean): String {
val appResourcesContext = PrimeStationOneControlApplication.instance
val stringBuilder = StringBuilder()
var remainingTimeDifference = periodInMilliseconds / 1000
val seconds = if (remainingTimeDifference >= 60) remainingTimeDifference % 60 else remainingTimeDifference
remainingTimeDifference = Math.ceil(remainingTimeDifference.toDouble() / 60).toLong()
val minutes = if (remainingTimeDifference >= 60) remainingTimeDifference % 60 else remainingTimeDifference
remainingTimeDifference /= 60
val hours = if (remainingTimeDifference >= 24) remainingTimeDifference % 24 else remainingTimeDifference
remainingTimeDifference /= 24
val days = if (remainingTimeDifference >= 30) remainingTimeDifference % 30 else remainingTimeDifference
remainingTimeDifference /= 30
val months = if (remainingTimeDifference >= 12) remainingTimeDifference % 12 else remainingTimeDifference
val years = remainingTimeDifference / 12
if (years > 0) {
stringBuilder.append(appResourcesContext.resources.getQuantityString(R.plurals.plural_years, years.toInt(), years.toInt()))
} else if (months > 0) {
stringBuilder.append(appResourcesContext.resources.getQuantityString(R.plurals.plural_months, months.toInt(), months.toInt()))
} else if (days > 0) {
stringBuilder.append(appResourcesContext.resources.getQuantityString(R.plurals.plural_days, days.toInt(), days.toInt()))
} else if (hours > 0) {
stringBuilder.append(appResourcesContext.resources.getQuantityString(R.plurals.plural_hours, hours.toInt(), hours.toInt()))
} else if (minutes > 0) {
stringBuilder.append(appResourcesContext.resources.getQuantityString(R.plurals.plural_minutes, minutes.toInt(), minutes.toInt()))
} else {
stringBuilder.append(appResourcesContext.resources.getQuantityString(R.plurals.plural_seconds, seconds.toInt(), seconds.toInt()))
}
if (inPast) {
stringBuilder.append(appResourcesContext.getString(R.string.friendly_time_ago))
}
return stringBuilder.toString()
}
fun getPrettyPrintTime(calendar: Calendar?): String? {
return format("yyyy-MM-dd HH:mm:ss", calendar, false)
}
fun getTwelveHourTime(timeInMillis: Long): String {
val dateFormat = SimpleDateFormat("h:mma", Locale.US)
return dateFormat.format(Date(timeInMillis))
}
fun getDurationString(durationInMillis: Long): String {
// Just for debugging; not internationalized.
val sb = StringBuilder()
TimeUtils.formatDuration(durationInMillis, sb)
return sb.toString()
}
fun format(@StringRes templateRes: Int, calendar: Calendar?, lowerCaseAmPm: Boolean): String? {
return format(PrimeStationOneControlApplication.instance.getString(templateRes), calendar, lowerCaseAmPm)
}
fun format(template: String, calendar: Calendar?, lowerCaseAmPm: Boolean): String? {
if (calendar == null) {
return null
}
val formatter = SimpleDateFormat(template, Locale.US)
if (lowerCaseAmPm) {
// force lowercase AM/PM (no way to do it via format)
val symbols = formatter.dateFormatSymbols
symbols.amPmStrings = arrayOf("am", "pm")
formatter.dateFormatSymbols = symbols
}
return formatter.format(calendar.time)
}
}
}
| mit | a7ee5ba5f21b16ceae2daa74bb275cc7 | 46.236364 | 163 | 0.650115 | 4.868207 | false | false | false | false |
olivierg13/EtherTracker | app/src/main/java/com/og/finance/ether/utilities/NotificationUtilities.kt | 1 | 2561 | /**
* Copyright 2013 Olivier Goutay (olivierg13)
*
*
* 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.og.finance.ether.utilities
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.support.v4.app.NotificationCompat
import com.og.finance.ether.R
import com.og.finance.ether.activities.MainActivity
import com.og.finance.ether.network.apis.AbstractEtherApi
import com.og.finance.ether.network.apis.CoinMarketEtherApi
/**
* Created by olivier.goutay on 2/29/16.
*/
object NotificationUtilities {
/**
* Show a notification containing the [infos][CoinMarketEtherApi]
* @param etherApi The latest [CoinMarketEtherApi]
*/
fun showNotification(context: Context, etherApi: AbstractEtherApi?) {
val intent = Intent(context, MainActivity::class.java)
val contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val b = NotificationCompat.Builder(context)
b.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Ether Tracker")
.setOngoing(true)
.setContentText(PriceFormatUtilities.getPriceFormatted(context, etherApi))
.setDefaults(Notification.DEFAULT_LIGHTS)
.setSound(Uri.EMPTY)
.setContentIntent(contentIntent)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, b.build())
}
/**
* Cancel the current [Notification]
*/
fun cancelNotification(context: Context) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancelAll()
}
}
| apache-2.0 | 5c60d01749c7737576c4ed327c7e420f | 34.569444 | 111 | 0.717298 | 4.469459 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsStructItem.kt | 1 | 1175 | package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsElementTypes.UNION
import org.rust.lang.core.psi.RsStructItem
import org.rust.lang.core.psi.RustPsiImplUtil
import org.rust.lang.core.stubs.RsStructItemStub
import javax.swing.Icon
val RsStructItem.union: PsiElement?
get() = node.findChildByType(UNION)?.psi
enum class RsStructKind {
STRUCT,
UNION
}
val RsStructItem.kind: RsStructKind get() = when {
union != null -> RsStructKind.UNION
else -> RsStructKind.STRUCT
}
abstract class RsStructItemImplMixin : RsStubbedNamedElementImpl<RsStructItemStub>, RsStructItem {
constructor(node: ASTNode) : super(node)
constructor(stub: RsStructItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getIcon(flags: Int): Icon =
iconWithVisibility(flags, RsIcons.STRUCT)
override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub)
override val crateRelativePath: String? get() = RustPsiImplUtil.crateRelativePath(this)
}
| mit | 509d9efe86a229cba75686dae3fb5ed3 | 29.128205 | 98 | 0.76766 | 4.037801 | false | false | false | false |
antoniolg/Bandhook-Kotlin | app/src/main/java/com/antonioleiva/bandhookkotlin/ui/custom/SquareImageView.kt | 1 | 1539 | /*
* Copyright (C) 2015 Antonio Leiva
*
* 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.antonioleiva.bandhookkotlin.ui.custom
import android.content.Context
import android.util.AttributeSet
import android.view.ViewManager
import android.widget.ImageView
import org.jetbrains.anko.custom.ankoView
class SquareImageView : ImageView {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = measuredWidth
setMeasuredDimension(width, width)
}
}
fun ViewManager.squareImageView(theme: Int = 0) = squareImageView(theme) {}
inline fun ViewManager.squareImageView(theme: Int = 0, init: SquareImageView.() -> Unit) = ankoView(::SquareImageView, theme, init)
| apache-2.0 | 4dadfab23d566470305f3c4d95b2e32d | 36.536585 | 131 | 0.753086 | 4.384615 | false | false | false | false |
maxirosson/jdroid-googleplay-publisher | jdroid-java-googleplay-publisher/src/main/java/com/jdroid/android/googleplay/publisher/VoidedPurchasesService.kt | 1 | 750 | package com.jdroid.android.googleplay.publisher
import com.google.api.services.androidpublisher.model.VoidedPurchasesListResponse
class VoidedPurchasesService : AbstractGooglePlayPublisher() {
fun getVoidedPurchases(app: App, maxResults: Long? = null, paginationToken: String? = null, startIndex: Long? = null, startTime: Long? = null, endTime: Long? = null, type: Int? = null): VoidedPurchasesListResponse {
val list = init(app.appContext).purchases().voidedpurchases().list(app.applicationId)
list.maxResults = maxResults
list.token = paginationToken
list.startIndex = startIndex
list.startTime = startTime
list.endTime = endTime
list.type = type
return list.execute()
}
}
| apache-2.0 | 411f32030f755aa1a066cd903348a414 | 43.117647 | 219 | 0.716 | 4.213483 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/view/ViewCollision.kt | 1 | 8057 | package com.soywiz.korge.view
import com.soywiz.kds.iterators.*
import com.soywiz.korio.lang.Cancellable
import com.soywiz.korio.lang.threadLocal
import com.soywiz.korma.geom.*
import com.soywiz.korma.geom.shape.*
import com.soywiz.korma.geom.vector.*
@PublishedApi
internal class ViewCollisionContext {
val tempMat = Matrix()
val tempRect1 = Rectangle()
val tempRect2 = Rectangle()
val tempVectorPath1 = listOf(VectorPath())
val tempVectorPath2 = listOf(VectorPath())
val ident = Matrix()
val lmat = Matrix()
val rmat = Matrix()
fun getVectorPath(view: View, out: List<VectorPath>): List<VectorPath> {
val hitShape = view.hitShape
val hitShapes = view.hitShapes
if (hitShapes != null) return hitShapes
if (hitShape != null) return listOf(hitShape)
view.getLocalBounds(tempRect1)
out[0].clear()
val dispX = view.anchorDispX
val dispY = view.anchorDispY
out[0].rect(tempRect1.x + dispX, tempRect1.y + dispY, tempRect1.width, tempRect1.height)
return out
}
fun collidesWith(left: View, right: View, kind: CollisionKind): Boolean {
left.getGlobalBounds(tempRect1)
right.getGlobalBounds(tempRect2)
if (!tempRect1.intersects(tempRect2)) return false
if (kind == CollisionKind.SHAPE) {
val leftShape = left.hitShape2d
val rightShape = right.hitShape2d
val ml = left.getGlobalMatrixWithAnchor(lmat)
val mr = right.getGlobalMatrixWithAnchor(rmat)
//println("intersects[$result]: left=$leftShape, right=$rightShape, ml=$ml, mr=$mr")
return Shape2d.intersects(leftShape, ml, rightShape, mr, tempMat)
}
return true
}
}
private val collisionContext by threadLocal { ViewCollisionContext() }
enum class CollisionKind { GLOBAL_RECT, SHAPE }
fun View.collidesWith(other: View, kind: CollisionKind = CollisionKind.GLOBAL_RECT): Boolean {
return collisionContext.collidesWith(this, other, kind)
}
fun View.collidesWith(otherList: List<View>, kind: CollisionKind = CollisionKind.GLOBAL_RECT): Boolean {
val ctx = collisionContext
otherList.fastForEach { other ->
if (ctx.collidesWith(this, other, kind)) return true
}
return false
}
fun View.collidesWithGlobalBoundingBox(other: View): Boolean = collidesWith(other, CollisionKind.GLOBAL_RECT)
fun View.collidesWithGlobalBoundingBox(otherList: List<View>): Boolean = collidesWith(otherList, CollisionKind.GLOBAL_RECT)
fun View.collidesWithShape(other: View): Boolean = collidesWith(other, CollisionKind.SHAPE)
fun View.collidesWithShape(otherList: List<View>): Boolean = collidesWith(otherList, CollisionKind.SHAPE)
inline fun <reified T : View> Container.findCollision(subject: View): T? = findCollision(subject) { it is T && it != subject } as T?
fun Container.findCollision(subject: View, kind: CollisionKind = CollisionKind.GLOBAL_RECT, matcher: (View) -> Boolean): View? {
var collides: View? = null
this.foreachDescendant {
if (matcher(it)) {
if (subject.collidesWith(it, kind)) {
collides = it
}
}
}
return collides
}
/**
* Adds a component to [this] that checks each frame for collisions against descendant views of [root] that matches the [filter],
* when a collision is found [callback] is executed with this view as receiver, and the collision target as first parameter.
* if no [root] is provided, it computes the root of the view [this] each frame, you can specify a collision [kind]
*/
fun View.onCollision(filter: (View) -> Boolean = { true }, root: View? = null, kind: CollisionKind = CollisionKind.GLOBAL_RECT, callback: View.(View) -> Unit): Cancellable {
return addUpdater {
(root ?: this.root).foreachDescendant {
if (this != it && filter(it) && this.collidesWith(it, kind)) {
callback(this, it)
}
}
}
}
fun List<View>.onCollision(filter: (View) -> Boolean = { true }, root: View? = null, kind: CollisionKind = CollisionKind.GLOBAL_RECT, callback: View.(View) -> Unit): Cancellable =
Cancellable(this.map { it.onCollision(filter, root, kind, callback) })
fun View.onCollisionShape(filter: (View) -> Boolean = { true }, root: View? = null, callback: View.(View) -> Unit): Cancellable {
return onCollision(filter, root, kind = CollisionKind.SHAPE, callback = callback)
}
/**
* Adds a component to [this] that checks collisions each frame of descendants views of [root] matching [filterSrc], matching against descendant views matching [filterDst].
* When a collision is found, [callback] is called. It returns a [Cancellable] to remove the component.
*/
fun View.onDescendantCollision(root: View = this, filterSrc: (View) -> Boolean = { true }, filterDst: (View) -> Boolean = { true }, kind: CollisionKind = CollisionKind.GLOBAL_RECT, callback: View.(View) -> Unit): Cancellable {
return addUpdater {
root.foreachDescendant { src ->
if (filterSrc(src)) {
root.foreachDescendant { dst ->
if (src !== dst && filterDst(dst) && src.collidesWith(dst, kind)) {
callback(src, dst)
}
}
}
}
}
}
/**
* Adds a component to [this] that checks each frame for collisions against descendant views of [root] that matches the [filter],
* when a collision is found, it remembers it and the next time the collision does not occur, [callback] is executed with this view as receiver,
* and the collision target as first parameter. if no [root] is provided, it computes the root of the view [this] each frame, you can specify a collision [kind]
*/
fun View.onCollisionExit(
filter: (View) -> Boolean = { true },
root: View? = null,
kind: CollisionKind = CollisionKind.GLOBAL_RECT,
callback: View.(View) -> Unit
): Cancellable {
val collisionState = mutableMapOf<View, Boolean>()
return addUpdater {
(root ?: this.root).foreachDescendant {
if (this != it && filter(it)) {
if (this.collidesWith(it, kind)) {
collisionState[it] = true
} else if (collisionState[it] == true) {
callback(this, it)
collisionState[it] = false
}
}
}
}
}
fun View.onCollisionShapeExit(filter: (View) -> Boolean = { true }, root: View? = null, callback: View.(View) -> Unit): Cancellable {
return onCollisionExit(filter, root, kind = CollisionKind.SHAPE, callback = callback)
}
fun List<View>.onCollisionExit(filter: (View) -> Boolean = { true }, root: View? = null, kind: CollisionKind = CollisionKind.GLOBAL_RECT, callback: View.(View) -> Unit): Cancellable =
Cancellable(this.map { it.onCollisionExit(filter, root, kind, callback) })
/**
* Adds a component to [this] that checks collisions each frame of descendants views of [root] matching [filterSrc], matching against descendant views matching [filterDst].
* When a collision is found, it remembers it and the next time the collision does not occur, [callback] is called. It returns a [Cancellable] to remove the component.
*/
fun View.onDescendantCollisionExit(root: View = this, filterSrc: (View) -> Boolean = { true }, filterDst: (View) -> Boolean = { true }, kind: CollisionKind = CollisionKind.GLOBAL_RECT, callback: View.(View) -> Unit): Cancellable {
val collisionState = mutableMapOf<Pair<View, View>, Boolean>()
return addUpdater {
root.foreachDescendant { src ->
if (filterSrc(src)) {
root.foreachDescendant { dst ->
if (src !== dst && filterDst(dst)) {
if (src.collidesWith(dst, kind)) {
println("collide")
collisionState[Pair(src, dst)] = true
} else if (collisionState[Pair(src, dst)] == true) {
callback(src, dst)
collisionState[Pair(src, dst)] = false
}
}
}
}
}
}
}
| apache-2.0 | f99609238c345f78a6804f2dede32cda | 43.027322 | 230 | 0.656696 | 3.899806 | false | false | false | false |
pushtorefresh/storio | storio-common-annotations-processor/src/main/kotlin/com/pushtorefresh/storio3/common/annotations/processor/introspection/JavaType.kt | 3 | 2382 | package com.pushtorefresh.storio3.common.annotations.processor.introspection
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
enum class JavaType {
BOOLEAN,
BOOLEAN_OBJECT,
SHORT,
SHORT_OBJECT,
INTEGER,
INTEGER_OBJECT,
LONG,
LONG_OBJECT,
FLOAT,
FLOAT_OBJECT,
DOUBLE,
DOUBLE_OBJECT,
STRING,
BYTE_ARRAY;
val isBoxedType: Boolean
get() = when (this) {
BOOLEAN_OBJECT, SHORT_OBJECT, INTEGER_OBJECT, LONG_OBJECT, FLOAT_OBJECT, DOUBLE_OBJECT -> true
else -> false
}
companion object {
fun from(typeMirror: TypeMirror): JavaType {
val typeKind = typeMirror.kind
val typeName = typeMirror.toString() // fqn of type, for example java.lang.String
return when {
typeKind == TypeKind.BOOLEAN -> BOOLEAN
typeName == Boolean::class.javaObjectType.canonicalName -> BOOLEAN_OBJECT
typeKind == TypeKind.SHORT -> SHORT
typeName == Short::class.javaObjectType.canonicalName -> SHORT_OBJECT
typeKind == TypeKind.INT -> INTEGER
typeName == Integer::class.javaObjectType.canonicalName -> INTEGER_OBJECT
typeKind == TypeKind.LONG -> LONG
typeName == Long::class.javaObjectType.canonicalName -> LONG_OBJECT
typeKind == TypeKind.FLOAT -> FLOAT
typeName == Float::class.javaObjectType.canonicalName -> FLOAT_OBJECT
typeKind == TypeKind.DOUBLE -> DOUBLE
typeName == Double::class.javaObjectType.canonicalName -> DOUBLE_OBJECT
typeName == String::class.javaObjectType.canonicalName -> STRING
typeName == ByteArray::class.java.canonicalName -> BYTE_ARRAY
else -> throw IllegalArgumentException("Unsupported type: $typeMirror")
}
}
}
val sqliteType: String
get() = when (this) {
BOOLEAN,
BOOLEAN_OBJECT,
SHORT,
SHORT_OBJECT,
INTEGER,
INTEGER_OBJECT,
LONG,
LONG_OBJECT -> "INTEGER"
FLOAT,
FLOAT_OBJECT,
DOUBLE,
DOUBLE_OBJECT -> "REAL"
STRING -> "TEXT"
BYTE_ARRAY -> "BLOB"
}
} | apache-2.0 | bd684225a342778b98a4c7836df86589 | 32.097222 | 106 | 0.572208 | 5.144708 | false | false | false | false |
is00hcw/anko | preview/robowrapper/test/org/jetbrains/kotlin/android/robowrapper/ViewHierarchyParserTest.kt | 2 | 6149 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.robowrapper
import android.app.Activity
import android.view.Gravity
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import android.view.ViewGroup.LayoutParams.*
import android.content.Context
import android.view.View
import org.jetbrains.kotlin.android.robowrapper.test.SomeView
import android.widget.ImageView
import kotlin.test.*
import android.view.ViewGroup
import org.jetbrains.kotlin.android.attrs.Attr
Config(manifest = Config.NONE)
RunWith(RobolectricTestRunner::class)
public class ViewHierarchyParserTest() {
Test
public fun testGetViewHierarchy() {
val a = Robolectric.setupActivity(Activity::class.java)
val frameLayout = FrameLayout(a)
val linearLayout = LinearLayout(a)
val textView = TextView(a)
textView.setPadding(10, 20, 30, 40)
val button = Button(a)
button.text = "Button text"
linearLayout.addView(textView)
linearLayout.addView(button)
frameLayout.addView(linearLayout)
val viewNode = parseView(frameLayout)
assertTrue(viewNode.view is FrameLayout)
assertEquals(1, viewNode.children.size())
assertTrue(viewNode.children[0].view is LinearLayout)
assertTrue(viewNode.children[0].children[0].view is TextView)
assertTrue(viewNode.children[0].children[1].view is Button)
val t = viewNode.children[0].children[0]
val b = viewNode.children[0].children[1]
with (t.attrs.fetch("paddingLeft")) {
assertEquals("paddingLeft", first)
assertNotNull(second.first)
assertEquals(1, second.first!!.format.size())
assertEquals("dimension", second.first!!.format[0])
assertEquals(10, second.second)
}
with (b.attrs.fetch("text")) {
assertEquals("text", first)
assertNotNull(second.first)
assertEquals(1, second.first!!.format.size())
assertEquals("string", second.first!!.format[0])
assertEquals("Button text", second.second)
}
}
Test
public fun testLayoutParams() {
val a = Robolectric.setupActivity(Activity::class.java)
val linearLayout = LinearLayout(a)
val textView = TextView(a)
val textViewLP = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
textViewLP.gravity = Gravity.CENTER
linearLayout.addView(textView, textViewLP)
val viewNode = parseView(linearLayout)
assertEquals(1, viewNode.children.size())
assertTrue(viewNode.children[0].view is TextView)
val t = viewNode.children[0]
with (t.attrs.fetch("layoutParams")) {
assertEquals("layoutParams", first)
assertNull(second.first)
assertTrue(second.second is LinearLayout.LayoutParams)
val lp = second.second as LinearLayout.LayoutParams
assertEquals(MATCH_PARENT, lp.width)
assertEquals(WRAP_CONTENT, lp.height)
assertEquals(Gravity.CENTER, lp.gravity)
}
}
Test
public fun testSpecialProperty() {
val a = Robolectric.setupActivity(Activity::class.java)
val textView = TextView(a)
val imageView = ImageView(a)
//special
assertEquals("src", resolveSpecialProperty(imageView, "drawable"))
//nothing special
assertEquals("text", resolveSpecialProperty(textView, "text"))
assertEquals("paddingRight", resolveSpecialProperty(imageView, "paddingRight"))
}
Test
public fun testXmlName() {
val a = Robolectric.setupActivity(Activity::class.java)
val linearLayout = LinearLayout(a)
val view = View(a)
val textView = TextView(a)
val someView = SomeView(a)
assertEquals("LinearLayout", parseView(linearLayout).getXmlName())
assertEquals("View", parseView(view).getXmlName())
assertEquals("TextView", parseView(textView).getXmlName())
assertEquals("org.jetbrains.kotlin.android.robowrapper.test.SomeView", parseView(someView).getXmlName())
}
Test
public fun testStyleableNames() {
Robolectric.setupActivity(Activity::class.java)
assertEquals(listOf("TextView"), TextView::class.java.getStyleableNames())
assertEquals(listOf("View"), View::class.java.getStyleableNames())
assertEquals(listOf("ViewGroup"), ViewGroup::class.java.getStyleableNames())
assertEquals(listOf("LinearLayout_Layout"),
LinearLayout.LayoutParams::class.java.getStyleableNames())
assertEquals(listOf("ViewGroup_Layout", "ViewGroup_MarginLayout"),
ViewGroup.LayoutParams::class.java.getStyleableNames())
}
Test
public fun testUnwrapClass() {
Robolectric.setupActivity(Activity::class.java)
assertEquals("android.widget.LinearLayout",
unwrapClass(_LinearLayout::class.java).name)
assertEquals("org.jetbrains.kotlin.android.robowrapper._NonWrapper1Class",
unwrapClass(_NonWrapper1Class::class.java).name)
assertEquals("org.jetbrains.kotlin.android.robowrapper._NonWrapper2Class",
unwrapClass(_NonWrapper2Class::class.java).name)
}
private fun Set<Pair<String, Pair<Attr?, Any>>>.fetch(name: String): Pair<String, Pair<Attr?, Any>> {
for (item in this) {
if (item.first == name)
return item;
}
throw Exception("Can't find property $name")
}
}
public class _LinearLayout(ctx: Context?): LinearLayout(ctx)
public class _NonWrapper1Class(ctx: Context?): View(ctx)
//has strange name (not _LinearLayout)
public class _NonWrapper2Class(ctx: Context?): LinearLayout(ctx) | apache-2.0 | 45d0395527943a3dcba78233fdd8ed7d | 32.606557 | 108 | 0.732802 | 4.146325 | false | true | false | false |
rhdunn/marklogic-intellij-plugin | src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/query/MarkLogicQuery.kt | 1 | 1428 | /*
* Copyright (C) 2017 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.marklogic.query
import org.apache.commons.compress.utils.IOUtils
// region Server Queries
val MARKLOGIC_VERSION_XQUERY = MarkLogicQuery("queries/server/marklogic-version.xqy")
val LIST_APPSERVERS_XQUERY = MarkLogicQuery("queries/server/list-appservers.xqy")
val LIST_DATABASES_XQUERY = MarkLogicQuery("queries/server/list-databases.xqy")
// endregion
// region Run Configuration Queries
val RUN_QUERY = MarkLogicQuery("queries/run/run-query.xqy")
val RUN_QUERY_AS_RDF = MarkLogicQuery("queries/run/run-query-as-rdf.xqy")
// endregion
class MarkLogicQuery(path: String) {
val query: String
init {
val loader = this::class.java.classLoader
val data = loader.getResourceAsStream(path)
query = String(IOUtils.toByteArray(data), Charsets.UTF_8)
}
}
| apache-2.0 | b4858aa0da8dbde9d97be607abb644f4 | 30.733333 | 85 | 0.743697 | 3.777778 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/cardviewer/TypeAnswer.kt | 1 | 12436 | /*
* Copyright (c) 2021 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.cardviewer
import android.content.SharedPreferences
import android.content.res.Resources
import android.text.TextUtils
import androidx.annotation.VisibleForTesting
import com.ichi2.anki.R
import com.ichi2.anki.servicelayer.LanguageHint
import com.ichi2.anki.servicelayer.LanguageHintService
import com.ichi2.libanki.Card
import com.ichi2.libanki.Sound
import com.ichi2.libanki.Utils
import com.ichi2.utils.DiffEngine
import com.ichi2.utils.JSONArray
import timber.log.Timber
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
class TypeAnswer(
@get:JvmName("useInputTag") val useInputTag: Boolean,
@get:JvmName("doNotUseCodeFormatting") val doNotUseCodeFormatting: Boolean,
/** Preference: Whether the user wants to focus "type in answer" */
val autoFocus: Boolean
) {
/** The correct answer in the compare to field if answer should be given by learner. Null if no answer is expected. */
var correct: String? = null
private set
/** What the learner actually typed (externally mutable) */
var input = ""
/** Font face of the 'compare to' field */
var font = ""
private set
/** The font size of the 'compare to' field */
var size = 0
private set
var languageHint: LanguageHint? = null
private set
/**
* Optional warning for when a typed answer can't be displayed
*
* * empty card [R.string.empty_card_warning]
* * unknown field specified [R.string.unknown_type_field_warning]
* */
var warning: String? = null
private set
/**
* @return true If entering input via EditText
* and if the current card has a {{type:field}} on the card template
*/
fun validForEditText(): Boolean {
return !useInputTag && correct != null
}
fun autoFocusEditText(): Boolean {
return validForEditText() && autoFocus
}
/**
* Extract type answer/cloze text and font/size
* @param card The next card to display
*/
fun updateInfo(card: Card, res: Resources) {
correct = null
val q = card.q(false)
val m = PATTERN.matcher(q)
var clozeIdx = 0
if (!m.find()) {
return
}
var fldTag = m.group(1)!!
// if it's a cloze, extract data
if (fldTag.startsWith("cloze:")) {
// get field and cloze position
clozeIdx = card.ord + 1
fldTag = fldTag.split(":").toTypedArray()[1]
}
// loop through fields for a match
val flds: JSONArray = card.model().getJSONArray("flds")
for (fld in flds.jsonObjectIterable()) {
val name = fld.getString("name")
if (name == fldTag) {
correct = card.note().getItem(name)
if (clozeIdx != 0) {
// narrow to cloze
correct = contentForCloze(correct!!, clozeIdx)
}
font = fld.getString("font")
size = fld.getInt("size")
languageHint = LanguageHintService.getLanguageHintForField(fld)
break
}
}
when (correct) {
null -> {
warning = if (clozeIdx != 0) {
res.getString(R.string.empty_card_warning)
} else {
res.getString(R.string.unknown_type_field_warning, fldTag)
}
}
"" -> {
correct = null
}
else -> {
warning = null
}
}
}
/**
* Format question field when it contains typeAnswer or clozes. If there was an error during type text extraction, a
* warning is displayed
*
* @param buf The question text
* @return The formatted question text
*/
fun filterQuestion(buf: String): String {
val m = PATTERN.matcher(buf)
if (warning != null) {
return m.replaceFirst(warning!!)
}
val sb = java.lang.StringBuilder()
if (useInputTag) {
// These functions are defined in the JavaScript file assets/scripts/card.js. We get the text back in
// shouldOverrideUrlLoading() in createWebView() in this file.
sb.append(
"""<center>
<input type="text" name="typed" id="typeans" onfocus="taFocus();" onblur="taBlur(this);" onKeyPress="return taKey(this, event)" autocomplete="off" """
)
// We have to watch out. For the preview we don’t know the font or font size. Skip those there. (Anki
// desktop just doesn’t show the input tag there. Do it with standard values here instead.)
if (!TextUtils.isEmpty(font) && size > 0) {
sb.append("style=\"font-family: '").append(font).append("'; font-size: ")
.append(size).append("px;\" ")
}
sb.append(">\n</center>\n")
} else {
sb.append("<span id=\"typeans\" class=\"typePrompt")
if (useInputTag) {
sb.append(" typeOff")
}
sb.append("\">........</span>")
}
return m.replaceAll(sb.toString())
}
/**
* Fill the placeholder for the type comparison: `[[type:(.+?)]]`
*
* Replaces with the HTML for the correct answer, and the comparison to the correct answer if appropriate.
*
* @param answer The card content on the back of the card
*
* @return The formatted answer text with `[[type:(.+?)]]` replaced with HTML
*/
fun filterAnswer(answer: String): String {
val userAnswer = cleanTypedAnswer(input)
val correctAnswer = cleanCorrectAnswer(correct)
Timber.d("correct answer = %s", correctAnswer)
Timber.d("user answer = %s", userAnswer)
return filterAnswer(answer, userAnswer, correctAnswer)
}
/**
* Fill the placeholder for the type comparison. Show the correct answer, and the comparison if appropriate.
*
* @param answer The answer text
* @param userAnswer Text typed by the user, or empty.
* @param correctAnswer The correct answer, taken from the note.
* @return The formatted answer text
*/
fun filterAnswer(answer: String, userAnswer: String, correctAnswer: String): String {
val m: Matcher = PATTERN.matcher(answer)
val diffEngine = DiffEngine()
val sb = StringBuilder()
sb.append(if (doNotUseCodeFormatting) "<div><span id=\"typeans\">" else "<div><code id=\"typeans\">")
// We have to use Matcher.quoteReplacement because the inputs here might have $ or \.
if (userAnswer.isNotEmpty()) {
// The user did type something.
if (userAnswer == correctAnswer) {
// and it was right.
sb.append(Matcher.quoteReplacement(DiffEngine.wrapGood(correctAnswer)))
sb.append("<span id=\"typecheckmark\">\u2714</span>") // Heavy check mark
} else {
// Answer not correct.
// Only use the complex diff code when needed, that is when we have some typed text that is not
// exactly the same as the correct text.
val diffedStrings = diffEngine.diffedHtmlStrings(correctAnswer, userAnswer)
// We know we get back two strings.
sb.append(Matcher.quoteReplacement(diffedStrings[0]))
sb.append("<br><span id=\"typearrow\">↓</span><br>")
sb.append(Matcher.quoteReplacement(diffedStrings[1]))
}
} else {
if (!useInputTag) {
sb.append(Matcher.quoteReplacement(DiffEngine.wrapMissing(correctAnswer)))
} else {
sb.append(Matcher.quoteReplacement(correctAnswer))
}
}
sb.append(if (doNotUseCodeFormatting) "</span></div>" else "</code></div>")
return m.replaceAll(sb.toString())
}
companion object {
@JvmField
/** Regular expression in card data for a 'type answer' after processing has occurred */
val PATTERN: Pattern = Pattern.compile("\\[\\[type:(.+?)]]")
@JvmStatic
fun createInstance(preferences: SharedPreferences): TypeAnswer {
return TypeAnswer(
useInputTag = preferences.getBoolean("useInputTag", false),
doNotUseCodeFormatting = preferences.getBoolean("noCodeFormatting", false),
autoFocus = preferences.getBoolean("autoFocusTypeInAnswer", false)
)
}
/** Regex pattern used in removing tags from text before diff */
private val spanPattern = Pattern.compile("</?span[^>]*>")
private val brPattern = Pattern.compile("<br\\s?/?>")
/**
* Clean up the correct answer text, so it can be used for the comparison with the typed text
*
* @param answer The content of the field the text typed by the user is compared to.
* @return The correct answer text, with actual HTML and media references removed, and HTML entities unescaped.
*/
@JvmStatic
fun cleanCorrectAnswer(answer: String?): String {
if (answer == null || "" == answer) {
return ""
}
var matcher = spanPattern.matcher(Utils.stripHTML(answer.trim { it <= ' ' }))
var answerText = matcher.replaceAll("")
matcher = brPattern.matcher(answerText)
answerText = matcher.replaceAll("\n")
matcher = Sound.SOUND_PATTERN.matcher(answerText)
answerText = matcher.replaceAll("")
return Utils.nfcNormalized(answerText)
}
/**
* Clean up the typed answer text, so it can be used for the comparison with the correct answer
*
* @param answer The answer text typed by the user.
* @return The typed answer text, cleaned up.
*/
@JvmStatic
fun cleanTypedAnswer(answer: String?): String {
return if (answer == null || "" == answer) {
""
} else Utils.nfcNormalized(answer.trim())
}
/**
* Return the correct answer to use for {{type::cloze::NN}} fields.
*
* @param txt The field text with the clozes
* @param idx The index of the cloze to use
* @return If the cloze strings are the same, return a single cloze string, otherwise, return
* a string with a comma-separeted list of strings with the correct index.
*/
@VisibleForTesting
fun contentForCloze(txt: String, idx: Int): String? {
// In Android, } should be escaped
val re = Pattern.compile("\\{\\{c$idx::(.+?)\\}\\}")
val m = re.matcher(txt)
val matches: MutableList<String?> = ArrayList()
var groupOne: String
while (m.find()) {
groupOne = m.group(1)!!
val colonColonIndex = groupOne.indexOf("::")
if (colonColonIndex > -1) {
// Cut out the hint.
groupOne = groupOne.substring(0, colonColonIndex)
}
matches.add(groupOne)
}
val uniqMatches: Set<String?> = HashSet(matches) // Allow to check whether there are distinct strings
// Make it consistent with the Desktop version (see issue #8229)
return if (uniqMatches.size == 1) {
matches[0]
} else {
TextUtils.join(", ", matches)
}
}
}
}
| gpl-3.0 | 5d2ef239cffb562e69ff023f77ac9518 | 38.71885 | 150 | 0.584379 | 4.497829 | false | false | false | false |
icapps/niddler-ui | niddler-ui/src/main/kotlin/com/icapps/niddler/ui/form/NiddlerConnectCellRenderer.kt | 1 | 2772 | package com.icapps.niddler.ui.form
import com.icapps.niddler.ui.isBright
import com.icapps.niddler.ui.toHex
import org.apache.http.util.TextUtils
import java.awt.Color
import java.awt.Component
import javax.swing.JTree
import javax.swing.tree.DefaultTreeCellRenderer
/**
* @author Koen Van Looveren
*/
class NiddlerConnectCellRenderer : DefaultTreeCellRenderer() {
private val secondaryTextNonSelectionColor: String
private val secondaryTextSelectionColor: String
init {
isOpaque = true
secondaryTextNonSelectionColor = if (textNonSelectionColor.isBright())
Color(0x41, 0x3F, 0x39).toHex()
else
textNonSelectionColor
.brighter().brighter()
.brighter().brighter().toHex()
secondaryTextSelectionColor = if (textSelectionColor.isBright())
Color(0xC2, 0xC2, 0xC2).toHex()
else
textSelectionColor
.brighter().brighter()
.brighter().brighter().toHex()
}
override fun getTreeCellRendererComponent(tree: JTree?, rowObject: Any?, sel: Boolean, expanded: Boolean,
leaf: Boolean, row: Int, hasFocus: Boolean): Component {
super.getTreeCellRendererComponent(tree, rowObject, sel, expanded, leaf, row, hasFocus)
background = null
val hexColor: String
if (selected) {
background = backgroundSelectionColor
foreground = textSelectionColor
hexColor = secondaryTextSelectionColor
} else {
background = null
foreground = textNonSelectionColor
hexColor = secondaryTextNonSelectionColor
}
if (rowObject is NiddlerConnectDeviceTreeNode) {
val device = rowObject.device
if (device == null) {
text = "No connected devices"
icon = null
toolTipText = null
return this
}
icon = device.icon
if (TextUtils.isEmpty(device.name)) {
text = device.serialNr
} else {
text = String.format("<html>%s <font color='%s'>%s</font>", device.name, hexColor, device.extraInfo)
toolTipText = device.serialNr
}
} else if (rowObject is NiddlerConnectProcessTreeNode) {
text = String.format("<html>%s <font color='%s'>(Port: %s)</font>",
rowObject.session.packageName, hexColor, rowObject.session.port)
icon = null
toolTipText = null
} else {
text = "No connected devices"
icon = null
toolTipText = null
}
return this
}
}
| apache-2.0 | 01684e1e560a3f1c9727f70bf2c8bc62 | 34.088608 | 116 | 0.585498 | 5.021739 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/person/RelationshipFragment.kt | 1 | 2187 | package ffc.app.person
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import ffc.android.onClick
import ffc.app.R
import ffc.app.person.genogram.GenogramActivity
import ffc.entity.Person
import kotlinx.android.synthetic.main.person_relationship_fragment.genogramButton
import kotlinx.android.synthetic.main.person_relationship_fragment.recycleView
import org.jetbrains.anko.startActivity
class RelationshipFragment : Fragment() {
var person: Person? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.person_relationship_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
person?.let {
with(recycleView) {
adapter = RelationshipAdapter(it.relationships.sortedBy { it.relate })
layoutManager = GridLayoutManager(context!!, 2)
}
genogramButton.onClick {
activity!!.startActivity<GenogramActivity>("personId" to person?.id)
}
}
}
class RelationshipAdapter(
val relationships: List<Person.Relationship>
) : RecyclerView.Adapter<RelationViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, type: Int): RelationViewHolder {
return RelationViewHolder(RelationshipView(parent.context))
}
override fun getItemCount() = relationships.size
override fun onBindViewHolder(holder: RelationViewHolder, position: Int) {
with((holder.itemView as RelationshipView)) {
relationship = relationships[position]
onClick {
context!!.startActivity<PersonActivitiy>("personId" to it.relationship!!.id)
}
}
}
}
class RelationViewHolder(view: View) : RecyclerView.ViewHolder(view)
}
| apache-2.0 | 111fa5df718fb1b77e9cbb0377db6137 | 34.852459 | 116 | 0.698674 | 4.936795 | false | false | false | false |
stripe/stripe-android | stripe-core/src/main/java/com/stripe/android/core/model/parsers/StripeErrorJsonParser.kt | 1 | 2233 | package com.stripe.android.core.model.parsers
import androidx.annotation.RestrictTo
import androidx.annotation.VisibleForTesting
import com.stripe.android.core.StripeError
import com.stripe.android.core.model.StripeJsonUtils.optString
import org.json.JSONObject
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class StripeErrorJsonParser : ModelJsonParser<StripeError> {
override fun parse(json: JSONObject): StripeError {
return runCatching {
json.getJSONObject(FIELD_ERROR).let { errorObject ->
StripeError(
charge = optString(errorObject, FIELD_CHARGE),
code = optString(errorObject, FIELD_CODE),
declineCode = optString(errorObject, FIELD_DECLINE_CODE),
message = optString(errorObject, FIELD_MESSAGE),
param = optString(errorObject, FIELD_PARAM),
type = optString(errorObject, FIELD_TYPE),
docUrl = optString(errorObject, FIELD_DOC_URL),
extraFields = errorObject
.optJSONObject(FIELD_EXTRA_FIELDS)?.let { extraFieldsJson ->
extraFieldsJson.keys().asSequence()
.map { key -> key to extraFieldsJson.get(key).toString() }
.toMap()
}
)
}
}.getOrDefault(
StripeError(
message = MALFORMED_RESPONSE_MESSAGE
)
)
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
companion object {
@VisibleForTesting
internal const val MALFORMED_RESPONSE_MESSAGE =
"An improperly formatted error response was found."
private const val FIELD_CHARGE = "charge"
private const val FIELD_CODE = "code"
private const val FIELD_DECLINE_CODE = "decline_code"
private const val FIELD_EXTRA_FIELDS = "extra_fields"
private const val FIELD_DOC_URL = "doc_url"
private const val FIELD_ERROR = "error"
private const val FIELD_MESSAGE = "message"
private const val FIELD_PARAM = "param"
private const val FIELD_TYPE = "type"
}
}
| mit | 45b02ef326e5138c2d1bd379c55ca3dd | 40.351852 | 90 | 0.59785 | 4.918502 | false | false | false | false |
Mashape/httpsnippet | test/fixtures/output/kotlin/okhttp/jsonObj-null-value.kt | 1 | 329 | val client = OkHttpClient()
val mediaType = MediaType.parse("application/json")
val body = RequestBody.create(mediaType, "{\"foo\":null}")
val request = Request.Builder()
.url("http://mockbin.com/har")
.post(body)
.addHeader("content-type", "application/json")
.build()
val response = client.newCall(request).execute()
| mit | 874404d19458d8eb25a6ffe6e641d4ab | 28.909091 | 58 | 0.705167 | 3.615385 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/visibility/MakePubCrateIntention.kt | 3 | 805 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions.visibility
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.rust.lang.core.psi.ext.RsVisibility
import org.rust.lang.core.psi.ext.RsVisibilityOwner
class MakePubCrateIntention : ChangeVisibilityIntention() {
override val visibility: String = "pub(crate)"
override fun isApplicable(element: RsVisibilityOwner): Boolean {
val visibility = element.visibility
return !(visibility is RsVisibility.Restricted && visibility.inMod == element.crateRoot)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
makePublic(ctx.element, crateRestricted = true)
}
}
| mit | 0060825d05bf6b94c95f213fe3101369 | 32.541667 | 96 | 0.746584 | 4.065657 | false | false | false | false |
deva666/anko | anko/library/generator/src/org/jetbrains/android/anko/generator/layoutParamsUtils.kt | 2 | 2844 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.generator
import org.jetbrains.android.anko.annotations.ExternalAnnotation
import org.jetbrains.android.anko.isPublic
import org.jetbrains.android.anko.parameterRawTypes
import org.jetbrains.android.anko.returnType
import org.jetbrains.android.anko.utils.fqName
import org.jetbrains.android.anko.utils.getConstructors
import org.jetbrains.android.anko.utils.unique
import org.objectweb.asm.tree.ClassNode
//return a pair<viewGroup, layoutParams> or null if the viewGroup doesn't contain custom LayoutParams
fun GenerationState.extractLayoutParams(viewGroup: ClassNode): LayoutElement? {
fun findActualLayoutParamsClass(viewGroup: ClassNode): ClassNode? {
fun findForParent() = findActualLayoutParamsClass(classTree.findNode(viewGroup)!!.parent!!.data)
val generateMethod = viewGroup.methods.firstOrNull { method ->
method.name == "generateLayoutParams"
&& method.parameterRawTypes.unique?.internalName == "android/util/AttributeSet"
} ?: return findForParent()
val returnTypeClass = classTree.findNode(generateMethod.returnType.internalName)!!.data
if (!returnTypeClass.fqName.startsWith(viewGroup.fqName)) return findForParent()
return if (returnTypeClass.isLayoutParams) returnTypeClass else findForParent()
}
val lpInnerClassName = viewGroup.innerClasses?.firstOrNull { it.name.contains("LayoutParams") }
val lpInnerClass = lpInnerClassName?.let { classTree.findNode(it.name)!!.data }
val externalAnnotations = annotationManager.findExternalAnnotations(viewGroup.fqName)
val hasGenerateLayoutAnnotation = ExternalAnnotation.GenerateLayout in externalAnnotations
val hasGenerateViewAnnotation = ExternalAnnotation.GenerateView in externalAnnotations
if (hasGenerateViewAnnotation || (lpInnerClass == null && !hasGenerateLayoutAnnotation)) return null
val actualLayoutParamsClass = findActualLayoutParamsClass(viewGroup).let {
if (it != null && it.name != "android/view/ViewGroup\$LayoutParams") it else null
}
return (actualLayoutParamsClass ?: lpInnerClass)?.let { clazz ->
LayoutElement(viewGroup, clazz, clazz.getConstructors().filter { it.isPublic })
}
} | apache-2.0 | 5eeedbe1462d3f851c4953f4b339eada | 48.051724 | 104 | 0.764416 | 4.716418 | false | false | false | false |
androidx/androidx | wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/ScalingLazyColumnSample.kt | 3 | 5163 | /*
* 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.wear.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.AutoCenteringParams
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.ListHeader
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.ScalingLazyColumnDefaults
import androidx.wear.compose.material.ScalingLazyListAnchorType
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.rememberScalingLazyListState
import kotlinx.coroutines.launch
@Sampled
@Composable
fun SimpleScalingLazyColumn() {
ScalingLazyColumn(
modifier = Modifier.fillMaxWidth()
) {
item {
ListHeader {
Text(text = "List Header")
}
}
items(20) {
Chip(
onClick = { },
label = { Text("List item $it") },
colors = ChipDefaults.secondaryChipColors()
)
}
}
}
@Sampled
@Composable
fun SimpleScalingLazyColumnWithSnap() {
val state = rememberScalingLazyListState()
ScalingLazyColumn(
modifier = Modifier.fillMaxWidth(),
state = state,
flingBehavior = ScalingLazyColumnDefaults.snapFlingBehavior(state = state)
) {
item {
ListHeader {
Text(text = "List Header")
}
}
items(20) {
Chip(
onClick = { },
label = { Text("List item $it") },
colors = ChipDefaults.secondaryChipColors()
)
}
}
}
@Sampled
@Composable
fun ScalingLazyColumnEdgeAnchoredAndAnimatedScrollTo() {
val coroutineScope = rememberCoroutineScope()
val itemSpacing = 6.dp
// Line up the gap between the items on the center-line
val scrollOffset = with(LocalDensity.current) {
-(itemSpacing / 2).roundToPx()
}
val state = rememberScalingLazyListState(
initialCenterItemIndex = 1,
initialCenterItemScrollOffset = scrollOffset
)
ScalingLazyColumn(
modifier = Modifier.fillMaxWidth(),
anchorType = ScalingLazyListAnchorType.ItemStart,
verticalArrangement = Arrangement.spacedBy(itemSpacing),
state = state,
autoCentering = AutoCenteringParams(itemOffset = scrollOffset)
) {
item {
ListHeader {
Text(text = "List Header")
}
}
items(20) {
Chip(
onClick = {
coroutineScope.launch {
// Add +1 to allow for the ListHeader
state.animateScrollToItem(it + 1, scrollOffset)
}
},
label = { Text("List item $it") },
colors = ChipDefaults.secondaryChipColors()
)
}
}
}
@Sampled
@Composable
fun SimpleScalingLazyColumnWithContentPadding() {
ScalingLazyColumn(
modifier = Modifier.fillMaxWidth(),
contentPadding = PaddingValues(top = 20.dp, bottom = 20.dp),
autoCentering = null
) {
item {
ListHeader {
Text(text = "List Header")
}
}
items(20) {
Chip(
onClick = { },
label = { Text("List item $it") },
colors = ChipDefaults.secondaryChipColors()
)
}
}
}
@Sampled
@Composable
fun ScalingLazyColumnWithHeaders() {
ScalingLazyColumn(
modifier = Modifier.fillMaxWidth(),
) {
item { ListHeader { Text("Header1") } }
items(5) {
Chip(
onClick = { },
label = { Text("List item $it") },
colors = ChipDefaults.secondaryChipColors()
)
}
item { ListHeader { Text("Header2") } }
items(5) {
Chip(
onClick = { },
label = { Text("List item ${it + 5}") },
colors = ChipDefaults.secondaryChipColors()
)
}
}
}
| apache-2.0 | 5801d437c82e248eccd072f1d8ffcc32 | 29.192982 | 82 | 0.605268 | 4.978785 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/test/kotlin/androidx/compose/ui/input/pointer/PointerInputTest.kt | 3 | 19775 | /*
* 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.input.pointer
import androidx.compose.ui.geometry.Offset
import com.google.common.truth.FailureMetadata
import com.google.common.truth.Subject
import com.google.common.truth.Subject.Factory
import com.google.common.truth.Truth
import com.google.common.truth.Truth.assertThat
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual.equalTo
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
// TODO(shepshapard): Write the following tests when functionality is done.
// consumeDownChange_noChangeOccurred_throwsException
// consumeDownChange_alreadyConsumed_throwsException
// consumePositionChange_noChangeOccurred_throwsException
// consumePositionChange_changeOverConsumed_throwsException
// consumePositionChange_consumedInWrongDirection_throwsException
@RunWith(JUnit4::class)
class PointerInputTest {
@Test
fun changedToDown_didNotChange_returnsFalse() {
val pointerInputChange1 =
createPointerInputChange(0f, 0f, false, 0f, 0f, false, 0f, 0f, false)
val pointerInputChange2 =
createPointerInputChange(0f, 0f, false, 0f, 0f, true, 0f, 0f, false)
val pointerInputChange3 =
createPointerInputChange(0f, 0f, true, 0f, 0f, true, 0f, 0f, false)
assertThat(pointerInputChange1.changedToDown(), `is`(false))
assertThat(pointerInputChange2.changedToDown(), `is`(false))
assertThat(pointerInputChange3.changedToDown(), `is`(false))
}
@Test
fun changedToDown_changeNotConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(0f, 0f, true, 0f, 0f, false, 0f, 0f, false)
assertThat(pointerInputChange.changedToDown(), `is`(true))
}
@Test
fun changedToDown_changeNotConsumed_returnsFalse() {
val pointerInputChange = createPointerInputChange(0f, 0f, true, 0f, 0f, false, 0f, 0f, true)
assertThat(pointerInputChange.changedToDown(), `is`(false))
}
@Test
fun changedToDownIgnoreConsumed_didNotChange_returnsFalse() {
val pointerInputChange1 =
createPointerInputChange(0f, 0f, false, 0f, 0f, false, 0f, 0f, false)
val pointerInputChange2 =
createPointerInputChange(0f, 0f, false, 0f, 0f, true, 0f, 0f, false)
val pointerInputChange3 =
createPointerInputChange(0f, 0f, true, 0f, 0f, true, 0f, 0f, false)
assertThat(
pointerInputChange1.changedToDownIgnoreConsumed(),
`is`(false)
)
assertThat(
pointerInputChange2.changedToDownIgnoreConsumed(),
`is`(false)
)
assertThat(
pointerInputChange3.changedToDownIgnoreConsumed(),
`is`(false)
)
}
@Test
fun changedToDownIgnoreConsumed_changedNotConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(0f, 0f, true, 0f, 0f, false, 0f, 0f, false)
assertThat(
pointerInputChange.changedToDownIgnoreConsumed(),
`is`(true)
)
}
@Test
fun changedToDownIgnoreConsumed_changedConsumed_returnsTrue() {
val pointerInputChange = createPointerInputChange(0f, 0f, true, 0f, 0f, false, 0f, 0f, true)
assertThat(
pointerInputChange.changedToDownIgnoreConsumed(),
`is`(true)
)
}
@Test
fun changedToUp_didNotChange_returnsFalse() {
val pointerInputChange1 =
createPointerInputChange(0f, 0f, false, 0f, 0f, false, 0f, 0f, false)
val pointerInputChange2 =
createPointerInputChange(0f, 0f, true, 0f, 0f, false, 0f, 0f, false)
val pointerInputChange3 =
createPointerInputChange(0f, 0f, true, 0f, 0f, true, 0f, 0f, false)
assertThat(pointerInputChange1.changedToUp(), `is`(false))
assertThat(pointerInputChange2.changedToUp(), `is`(false))
assertThat(pointerInputChange3.changedToUp(), `is`(false))
}
@Test
fun changedToUp_changeNotConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(0f, 0f, false, 0f, 0f, true, 0f, 0f, false)
assertThat(pointerInputChange.changedToUp(), `is`(true))
}
@Test
fun changedToUp_changeNotConsumed_returnsFalse() {
val pointerInputChange = createPointerInputChange(0f, 0f, false, 0f, 0f, true, 0f, 0f, true)
assertThat(pointerInputChange.changedToUp(), `is`(false))
}
@Test
fun changedToUpIgnoreConsumed_didNotChange_returnsFalse() {
val pointerInputChange1 =
createPointerInputChange(0f, 0f, false, 0f, 0f, false, 0f, 0f, false)
val pointerInputChange2 =
createPointerInputChange(0f, 0f, true, 0f, 0f, false, 0f, 0f, false)
val pointerInputChange3 =
createPointerInputChange(0f, 0f, true, 0f, 0f, true, 0f, 0f, false)
assertThat(
pointerInputChange1.changedToUpIgnoreConsumed(),
`is`(false)
)
assertThat(
pointerInputChange2.changedToUpIgnoreConsumed(),
`is`(false)
)
assertThat(
pointerInputChange3.changedToUpIgnoreConsumed(),
`is`(false)
)
}
@Test
fun changedToUpIgnoreConsumed_changedNotConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(0f, 0f, false, 0f, 0f, true, 0f, 0f, false)
assertThat(
pointerInputChange.changedToUpIgnoreConsumed(),
`is`(true)
)
}
@Test
fun changedToUpIgnoreConsumed_changedConsumed_returnsTrue() {
val pointerInputChange = createPointerInputChange(0f, 0f, false, 0f, 0f, true, 0f, 0f, true)
assertThat(
pointerInputChange.changedToUpIgnoreConsumed(),
`is`(true)
)
}
// TODO(shepshapard): Test more variations of positions?
@Test
fun positionChange_didNotChange_returnsZeroOffset() {
val pointerInputChange =
createPointerInputChange(11f, 13f, true, 11f, 13f, true, 0f, 0f, false)
assertThat(
pointerInputChange.positionChange(),
`is`(equalTo(Offset.Zero))
)
}
@Test
fun positionChange_changedNotConsumed_returnsFullOffset() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 0f, 0f, false)
assertThat(
pointerInputChange.positionChange(),
`is`(equalTo(Offset(6f, 12f)))
)
}
@Test
fun positionChange_changedFullConsumed_returnsZeroOffset() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 6f, 12f, false)
assertThat(
pointerInputChange.positionChange(),
`is`(equalTo(Offset.Zero))
)
}
@Test
fun positionChangeIgnoreConsumed_didNotChange_returnsZeroOffset() {
val pointerInputChange =
createPointerInputChange(11f, 13f, true, 11f, 13f, true, 0f, 0f, false)
assertThat(
pointerInputChange.positionChangeIgnoreConsumed(),
`is`(equalTo(Offset.Zero))
)
}
@Test
fun positionChangeIgnoreConsumed_changedNotConsumed_returnsFullOffset() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 0f, 0f, false)
assertThat(
pointerInputChange.positionChangeIgnoreConsumed(),
`is`(equalTo(Offset(6f, 12f)))
)
}
@Test
fun positionChangeIgnoreConsumed_changedPartiallyConsumed_returnsFullOffset() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 5f, 9f, false)
assertThat(
pointerInputChange.positionChangeIgnoreConsumed(),
`is`(equalTo(Offset(6f, 12f)))
)
}
@Test
fun positionChangeIgnoreConsumed_changedFullConsumed_returnsFullOffset() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 6f, 12f, false)
assertThat(
pointerInputChange.positionChangeIgnoreConsumed(),
`is`(equalTo(Offset(6f, 12f)))
)
}
@Test
fun positionChanged_didNotChange_returnsFalse() {
val pointerInputChange =
createPointerInputChange(11f, 13f, true, 11f, 13f, true, 0f, 0f, false)
assertThat(pointerInputChange.positionChanged(), `is`(false))
}
@Test
fun positionChanged_changedNotConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 0f, 0f, false)
assertThat(pointerInputChange.positionChanged(), `is`(true))
}
@Test
fun positionChanged_changedFullConsumed_returnsFalse() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 6f, 12f, false)
assertThat(pointerInputChange.positionChanged(), `is`(false))
}
@Test
fun positionChangedIgnoreConsumed_didNotChange_returnsFalse() {
val pointerInputChange =
createPointerInputChange(11f, 13f, true, 11f, 13f, true, 0f, 0f, false)
assertThat(
pointerInputChange.positionChangedIgnoreConsumed(),
`is`(false)
)
}
@Test
fun positionChangedIgnoreConsumed_changedNotConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 0f, 0f, false)
assertThat(
pointerInputChange.positionChangedIgnoreConsumed(),
`is`(true)
)
}
@Test
fun positionChangedIgnoreConsumed_changedPartiallyConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 5f, 9f, false)
assertThat(
pointerInputChange.positionChangedIgnoreConsumed(),
`is`(true)
)
}
@Test
fun positionChangedIgnoreConsumed_changedFullConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 6f, 12f, false)
assertThat(
pointerInputChange.positionChangedIgnoreConsumed(),
`is`(true)
)
}
@Test
fun anyPositionChangeConsumed_changedNotConsumed_returnsFalse() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 0f, 0f, false)
assertThat(
pointerInputChange.isConsumed,
`is`(false)
)
}
@Test
fun anyPositionChangeConsumed_changedPartiallyConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 5f, 9f, false)
assertThat(
pointerInputChange.isConsumed,
`is`(true)
)
}
@Test
fun anyPositionChangeConsumed_changedFullConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 6f, 12f, false)
assertThat(
pointerInputChange.isConsumed,
`is`(true)
)
}
@Test
fun anyChangeConsumed_noChangeConsumed_returnsFalse() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, false, 0f, 0f, false)
assertThat(pointerInputChange.isConsumed).isFalse()
}
@Test
fun consume_noChanges_returnsTrue() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 8f, 16f, true, 0f, 0f, false)
pointerInputChange.consume()
assertThat(pointerInputChange.isConsumed).isTrue()
assertThat(pointerInputChange.isConsumed).isTrue()
}
@Test
fun anyChangeConsumed_downConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, false, 0f, 0f, true)
assertThat(pointerInputChange.isConsumed).isTrue()
}
@Test
fun anyChangeConsumed_movementConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, false, 1f, 3f, false)
assertThat(pointerInputChange.isConsumed).isTrue()
}
@Test
fun anyChangeConsumed_allConsumed_returnsTrue() {
val pointerInputChange =
createPointerInputChange(8f, 16f, true, 2f, 4f, false, 1f, 3f, true)
assertThat(pointerInputChange.isConsumed).isTrue()
}
@Test
fun consumeDownChange_changeOccurred_consumes() {
val pointerInputChange1 =
createPointerInputChange(0f, 0f, false, 0f, 0f, true, 0f, 0f, false)
val pointerInputChange2 =
createPointerInputChange(0f, 0f, true, 0f, 0f, false, 0f, 0f, false)
val consumed =
pointerInputChange1.apply { if (pressed != previousPressed) consume() }.isConsumed
val consumed1 =
pointerInputChange2.apply { if (pressed != previousPressed) consume() }.isConsumed
assertThat(consumed, `is`(true))
assertThat(consumed1, `is`(true))
}
@Test
fun consumeDownChange_changeDidntOccur_doesNotConsume() {
val pointerInputChange1 =
createPointerInputChange(0f, 0f, true, 0f, 0f, true, 0f, 0f, false)
val pointerInputChange2 =
createPointerInputChange(0f, 0f, false, 0f, 0f, false, 0f, 0f, false)
val consumed =
pointerInputChange1.apply { if (pressed != previousPressed) consume() }.isConsumed
val consumed1 =
pointerInputChange2.apply { if (pressed != previousPressed) consume() }.isConsumed
assertThat(consumed, `is`(false))
assertThat(consumed1, `is`(false))
}
@Test
fun consumePositionChange_consumesAll_consumes() {
val pointerInputChange1 =
createPointerInputChange(8f, 16f, true, 2f, 4f, true, 0f, 0f, false)
val pointerInputChangeResult1 =
pointerInputChange1.deepCopy().apply { consume() }
PointerInputChangeSubject
.assertThat(pointerInputChangeResult1).positionChangeConsumed()
}
@Test
fun consumeAllChanges_nothingChanged_stillConsumed() {
val pointerInputChange1 =
createPointerInputChange(1f, 2f, false, 1f, 2f, false, 0f, 0f, false)
val pointerInputChange2 =
createPointerInputChange(2f, 1f, true, 2f, 1f, true, 0f, 0f, false)
val actual1 = pointerInputChange1.apply { consume() }
val actual2 = pointerInputChange2.apply { consume() }
PointerInputChangeSubject
.assertThat(actual1).positionChangeConsumed()
PointerInputChangeSubject
.assertThat(actual2).positionChangeConsumed()
}
@Test
fun consumeAllChanges_downChanged_downChangeConsumed() {
val pointerInputChange1 =
createPointerInputChange(1f, 2f, true, 1f, 2f, false, 0f, 0f, false)
val pointerInputChange2 =
createPointerInputChange(2f, 1f, false, 2f, 1f, true, 0f, 0f, false)
val actual1 = pointerInputChange1.apply { consume() }
val actual2 = pointerInputChange2.apply { consume() }
PointerInputChangeSubject.assertThat(actual1).downConsumed()
PointerInputChangeSubject.assertThat(actual2).downConsumed()
}
@Test
fun consumeAllChanges_movementChanged_movementFullyConsumed() {
val pointerInputChange =
createPointerInputChange(1f, 2f, true, 11f, 21f, true, 0f, 0f, false)
val actual = pointerInputChange.apply { consume() }
PointerInputChangeSubject.assertThat(actual).positionChangeConsumed()
}
@Test
fun consumeAllChanges_movementChangedAndPartiallyConsumed_movementFullyConsumed() {
val pointerInputChange =
createPointerInputChange(1f, 2f, true, 11f, 21f, true, -3f, -5f, false)
val actual = pointerInputChange.apply { consume() }
PointerInputChangeSubject.assertThat(actual).positionChangeConsumed()
}
@Test
fun consumeAllChanges_allChanged_allConsumed() {
val pointerInputChange1 =
createPointerInputChange(1f, 2f, true, 11f, 21f, false, -3f, -5f, false)
val pointerInputChange2 =
createPointerInputChange(1f, 2f, false, 11f, 21f, true, -7f, -11f, false)
val actual1 = pointerInputChange1.apply { consume() }
val actual2 = pointerInputChange2.apply { consume() }
PointerInputChangeSubject.assertThat(actual1).downConsumed()
PointerInputChangeSubject.assertThat(actual1).positionChangeConsumed()
PointerInputChangeSubject.assertThat(actual2).downConsumed()
PointerInputChangeSubject.assertThat(actual2).positionChangeConsumed()
}
// Private Helper
private fun createPointerInputChange(
currentX: Float,
currentY: Float,
currentDown: Boolean,
previousX: Float,
previousY: Float,
previousDown: Boolean,
consumedX: Float,
consumedY: Float,
consumedDown: Boolean
): PointerInputChange {
return PointerInputChange(
PointerId(0),
100,
Offset(currentX, currentY),
currentDown,
0,
Offset(previousX, previousY),
previousDown,
isInitiallyConsumed = consumedX != 0f || consumedY != 0f || consumedDown
)
}
}
private class PointerInputChangeSubject(
metaData: FailureMetadata,
val actual: PointerInputChange
) : Subject(metaData, actual) {
companion object {
private val Factory =
Factory<PointerInputChangeSubject, PointerInputChange> { metadata, actual ->
PointerInputChangeSubject(metadata, actual)
}
fun assertThat(actual: PointerInputChange): PointerInputChangeSubject {
return Truth.assertAbout(Factory).that(actual)
}
}
fun nothingConsumed() {
downNotConsumed()
positionChangeNotConsumed()
}
fun downConsumed() {
check("consumed.downChange").that(actual.isConsumed).isEqualTo(true)
}
fun downNotConsumed() {
check("consumed.downChange").that(actual.isConsumed).isEqualTo(false)
}
fun positionChangeConsumed() {
check("consumed.positionChangeConsumed")
.that(actual.isConsumed)
.isEqualTo(true)
}
fun positionChangeNotConsumed() {
check("consumed.positionChange not Consumed")
.that(actual.isConsumed)
.isEqualTo(false)
}
}
private fun PointerInputChange.deepCopy(): PointerInputChange = PointerInputChange(
id = this.id,
uptimeMillis = this.uptimeMillis,
position = this.position,
pressed = this.pressed,
previousUptimeMillis = this.previousUptimeMillis,
previousPosition = this.previousPosition,
previousPressed = this.previousPressed,
isInitiallyConsumed = this.isConsumed,
type = this.type,
scrollDelta = this.scrollDelta
)
| apache-2.0 | ce0e59f8e33de8e5d0d2045fc9347f8a | 33.692982 | 100 | 0.652491 | 4.353809 | false | true | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/organizeImports/KotlinOrganizeImportsAction.kt | 1 | 6597 | /*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.editors.organizeImports
import org.eclipse.jdt.core.search.TypeNameMatch
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds
import org.eclipse.jdt.internal.ui.actions.ActionMessages
import org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog
import org.eclipse.jdt.internal.ui.util.TypeNameMatchLabelProvider
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds
import org.eclipse.jdt.ui.actions.SelectionDispatchAction
import org.eclipse.jface.window.Window
import org.eclipse.ui.PlatformUI
import org.jetbrains.kotlin.core.builder.KotlinPsiManager
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.eclipse.ui.utils.getBindingContext
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
import org.jetbrains.kotlin.idea.imports.OptimizedImportsBuilder
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.ui.editors.KotlinCommonEditor
import org.jetbrains.kotlin.ui.editors.quickfix.findApplicableTypes
import org.jetbrains.kotlin.ui.editors.quickfix.placeImports
import org.jetbrains.kotlin.ui.editors.quickfix.replaceImports
import org.jetbrains.kotlin.ui.formatter.settings
import java.util.ArrayList
class KotlinOrganizeImportsAction(private val editor: KotlinCommonEditor) : SelectionDispatchAction(editor.site) {
init {
setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS)
setText(ActionMessages.OrganizeImportsAction_label);
setToolTipText(ActionMessages.OrganizeImportsAction_tooltip);
setDescription(ActionMessages.OrganizeImportsAction_description);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION);
}
companion object {
val ACTION_ID = "OrganizeImports"
}
override fun run() {
val bindingContext = getBindingContext(editor) ?: return
val ktFile = editor.parsedFile ?: return
val file = editor.eclipseFile ?: return
val typeNamesToImport = bindingContext.diagnostics
.filter { it.factory == Errors.UNRESOLVED_REFERENCE && it.psiFile == ktFile }
.map { it.psiElement.text }
.distinct()
val (uniqueImports, ambiguousImports) = findTypesToImport(typeNamesToImport)
val allRequiredImports = ArrayList(uniqueImports)
if (ambiguousImports.isNotEmpty()) {
val chosenImports = chooseImports(ambiguousImports)
if (chosenImports == null) return
allRequiredImports.addAll(chosenImports)
}
placeImports(allRequiredImports, file, editor.document)
KotlinPsiManager.commitFile(file, editor.document)
optimizeImports()
}
private fun optimizeImports() {
val ktFile = editor.parsedFile ?: return
val file = editor.eclipseFile ?: return
val descriptorsToImport = collectDescriptorsToImport(ktFile)
val optimizedImports = prepareOptimizedImports(ktFile, descriptorsToImport) ?: return
replaceImports(optimizedImports.map { it.toString() }, file, editor.document)
}
// null signalizes about cancelling operation
private fun chooseImports(ambiguousImports: List<List<TypeNameMatch>>): List<TypeNameMatch>? {
val labelProvider = TypeNameMatchLabelProvider(TypeNameMatchLabelProvider.SHOW_FULLYQUALIFIED)
val dialog = MultiElementListSelectionDialog(getShell(), labelProvider)
dialog.setTitle(ActionMessages.OrganizeImportsAction_selectiondialog_title)
dialog.setMessage(ActionMessages.OrganizeImportsAction_selectiondialog_message)
val arrayImports = Array<Array<TypeNameMatch>>(ambiguousImports.size) { i ->
Array<TypeNameMatch>(ambiguousImports[i].size) { j ->
ambiguousImports[i][j]
}
}
dialog.setElements(arrayImports)
return if (dialog.open() == Window.OK) {
dialog.result.mapNotNull { (it as Array<*>).firstOrNull() as? TypeNameMatch }
} else {
null
}
}
private fun findTypesToImport(typeNames: List<String>): UniqueAndAmbiguousImports {
val uniqueImports = arrayListOf<TypeNameMatch>()
val ambiguousImports = arrayListOf<List<TypeNameMatch>>()
loop@ for (typeName in typeNames) {
val typesToImport = findApplicableTypes(typeName)
when (typesToImport.size) {
0 -> continue@loop
1 -> uniqueImports.add(typesToImport.first())
else -> ambiguousImports.add(typesToImport)
}
}
return UniqueAndAmbiguousImports(uniqueImports, ambiguousImports)
}
private data class UniqueAndAmbiguousImports(
val uniqueImports: List<TypeNameMatch>,
val ambiguousImports: List<List<TypeNameMatch>>)
}
fun prepareOptimizedImports(file: KtFile,
descriptorsToImport: Collection<DeclarationDescriptor>): List<ImportPath>? {
val settings = settings.getCustomSettings(KotlinCodeStyleSettings::class.java)
return OptimizedImportsBuilder(
file,
OptimizedImportsBuilder.InputData(descriptorsToImport.toSet(), emptyList()),
OptimizedImportsBuilder.Options(
settings.NAME_COUNT_TO_USE_STAR_IMPORT,
settings.NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS,
{ fqName -> fqName.asString() in settings.PACKAGES_TO_USE_STAR_IMPORTS })
).buildOptimizedImports()
} | apache-2.0 | e11fdfd6f74e6022cc06fb6fd015fa4e | 42.695364 | 114 | 0.687888 | 4.890289 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_multisample.kt | 1 | 4292 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val ARB_multisample = "ARBMultisample".nativeClassGL("ARB_multisample", postfix = ARB) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension provides a mechanism to antialias all GL primitives: points, lines, polygons, bitmaps, and images. The technique is to sample all
primitives multiple times at each pixel. The color sample values are resolved to a single, displayable color each time a pixel is updated, so the
antialiasing appears to be automatic at the application level. Because each sample includes depth and stencil information, the depth and stencil
functions perform equivalently to the single-sample mode.
An additional buffer, called the multisample buffer, is added to the framebuffer. Pixel sample values, including color, depth, and stencil values, are
stored in this buffer. When the framebuffer includes a multisample buffer, it does not also include separate depth or stencil buffers, even if the
multisample buffer does not store depth or stencil values. Color buffers (left/right, front/back, and aux) do coexist with the multisample buffer,
however.
Multisample antialiasing is most valuable for rendering polygons, because it requires no sorting for hidden surface elimination, and it correctly
handles adjacent polygons, object silhouettes, and even intersecting polygons. If only points or lines are being rendered, the "smooth" antialiasing
mechanism provided by the base GL may result in a higher quality image. This extension is designed to allow multisample and smooth antialiasing
techniques to be alternated during the rendering of a single scene.
"""
IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev.
""",
"MULTISAMPLE_ARB"..0x809D,
"SAMPLE_ALPHA_TO_COVERAGE_ARB"..0x809E,
"SAMPLE_ALPHA_TO_ONE_ARB"..0x809F,
"SAMPLE_COVERAGE_ARB"..0x80A0
)
IntConstant(
"Accepted by the {@code mask} parameter of PushAttrib.",
"MULTISAMPLE_BIT_ARB"..0x20000000
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv.",
"SAMPLE_BUFFERS_ARB"..0x80A8,
"SAMPLES_ARB"..0x80A9,
"SAMPLE_COVERAGE_VALUE_ARB"..0x80AA,
"SAMPLE_COVERAGE_INVERT_ARB"..0x80AB
)
void(
"SampleCoverageARB",
"""
Specifies simultaneously the values of #SAMPLE_COVERAGE_VALUE_ARB and #SAMPLE_COVERAGE_INVERT_ARB.
If #SAMPLE_COVERAGE_ARB is enabled, the fragment coverage is ANDed with another temporary coverage. This temporary coverage is a function of the value
of #SAMPLE_COVERAGE_VALUE_ARB. If #SAMPLE_COVERAGE_INVERT_ARB is GL11#TRUE, the temporary coverage is inverted (all bit values are inverted) before it
is ANDed with the fragment coverage.
""",
GLfloat.IN("value", "the desired coverage value"),
GLboolean.IN(
"invert",
"if true, the temporary coverage is inverted",
"GL11#TRUE GL11#FALSE"
)
)
}
val GLX_ARB_multisample = "GLXARBMultisample".nativeClassGLX("GLX_ARB_multisample", ARB) {
documentation =
"""
Native bindings to the ${registryLink("ARB", "multisample")} extension.
See ##ARBMultisample for details.
"""
IntConstant(
"Accepted by the {@code attribList} parameter of GLX#ChooseVisual(), and by the {@code attrib} parameter of GLX#GetConfig().",
"SAMPLE_BUFFERS_ARB".."100000",
"SAMPLES_ARB".."100001"
)
}
val WGL_ARB_multisample = "WGLARBMultisample".nativeClassWGL("WGL_ARB_multisample", ARB) {
documentation =
"""
Native bindings to the ${registryLink("ARB", "multisample")} extension.
See ##ARBMultisample for details.
Requires ${WGL_EXT_extensions_string.link} and ${WGL_ARB_pixel_format.link}.
"""
IntConstant(
"""
Accepted by the {@code attributes} parameter of WGLARBPixelFormat#GetPixelFormatAttribiARB(),
WGLARBPixelFormat#GetPixelFormatAttribfARB(), and the {@code attribIList} and {@code attribFList} of
WGLARBPixelFormat#ChoosePixelFormatARB().
""",
"SAMPLE_BUFFERS_ARB"..0x2041,
"SAMPLES_ARB"..0x2042
)
} | bsd-3-clause | b3cfcf178ac945d012ade8ccaf98980d | 36.99115 | 153 | 0.749767 | 3.828724 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/test/kotlin/com/tang/intellij/test/completion/TestModule.kt | 2 | 2387 | /*
* Copyright (c) 2017. tangzx([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 com.tang.intellij.test.completion
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.tang.intellij.test.fileTreeFromText
class TestModule : TestCompletionBase() {
fun `test module type`() {
fileTreeFromText("""
--- moduleA.lua
---@module TypeA
module("TypeA")
name = "a"
--- B.lua
local a ---@type TypeA
a.--[[caret]]
""").createAndOpenFileWithCaretMarker()
FileDocumentManager.getInstance().saveAllDocuments()
myFixture.completeBasic()
val elementStrings = myFixture.lookupElementStrings
assertTrue(elementStrings!!.contains("name"))
}
fun `test module field completion`() {
fileTreeFromText("""
--- moduleA.lua
---@module TypeA
module("TypeA")
name = "a"
--[[caret]]
""").createAndOpenFileWithCaretMarker()
FileDocumentManager.getInstance().saveAllDocuments()
myFixture.completeBasic()
val elementStrings = myFixture.lookupElementStrings
assertTrue(elementStrings!!.contains("name"))
}
fun `test module members visibility`() {
fileTreeFromText("""
--- moduleA.lua
---@module TypeA
module("TypeA")
myFieldName = "a"
function myFunction() end
--- B.lua
--[[caret]]
""").createAndOpenFileWithCaretMarker()
FileDocumentManager.getInstance().saveAllDocuments()
myFixture.completeBasic()
val elementStrings = myFixture.lookupElementStrings
assertFalse(elementStrings!!.containsAll(listOf("myFieldName", "myFunction")))
}
} | apache-2.0 | 8c2a310981e4d4543e4531eebcfdd7b2 | 29.227848 | 86 | 0.623377 | 5.089552 | false | true | false | false |
hastebrot/protokola | src/main/kotlin/demo/protokola/reflect/property2.kt | 1 | 4619 | package demo.protokola.reflect
import protokola.demo
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KProperty1
class FooVars(var str: String? = null,
var int: Int? = null,
var bool: Boolean? = null,
var list: MutableList<String?>? = null,
var coll: Collection<Int>? = null)
class FooVals(val str: String,
val int: Int,
val bool: Boolean,
val list: MutableList<String?>,
val coll: Collection<Int>)
fun main(args: Array<String>) {
demo("foo vars") {
val foo = FooVars()
FooVars::str.set(foo, "a")
FooVars::int.set(foo, 1)
FooVars::bool.set(foo, true)
FooVars::list.set(foo, mutableListOf("a", "b"))
FooVars::list.get(foo)!!.addAll(listOf("c", "d"))
FooVars::coll.set(foo, mutableListOf(1, 2))
// FooVars::coll.get(foo)!!.addAll(listOf(3, 4))
}
demo("foo vals") {
val foo = FooVals("a", 1, true, mutableListOf("a", "b"), listOf(1, 2))
FooVals::str.get(foo)
FooVals::int.get(foo)
FooVals::bool.get(foo)
FooVals::list.get(foo)
FooVals::coll.get(foo)
}
demo("wrapper foo vars push") {
val foo = FooVars("a", 1, true, mutableListOf("a", "b"), listOf(1, 2))
println(foo.str)
println(foo.list)
MutableWrapper(foo, FooVars::str).set("b")
Wrapper(foo, FooVars::list).push(listOf("c", "d"))
println(foo.str)
println(foo.list)
MutableWrapper(foo, FooVars::str).set(null)
Wrapper(foo, FooVars::list).push(listOf(null))
println(foo.str)
println(foo.list)
}
demo("wrapper foo vals push") {
val foo = FooVals("a", 1, true, mutableListOf("a", "b"), mutableListOf(1, 2))
println(foo.str)
println(foo.list)
// Wrapper(foo, FooVals::str).set("b")
Wrapper(foo, FooVals::list).push(listOf("c", "d"))
println(foo.str)
println(foo.list)
// Wrapper(foo, FooVals::str).set(null)
Wrapper(foo, FooVals::list).push(listOf(null))
println(foo.str)
println(foo.list)
}
demo("wrapper foo vars splice") {
val foo = FooVars(list = mutableListOf("a", "b", "c", "d", "e"))
println(foo.list)
Wrapper(foo, FooVars::list).splice(2, 2, listOf("x", "y", "z"))
println(foo.list)
}
}
class Wrapper<T, out R>(val bean: T,
val property: KProperty1<T, R?>)
class MutableWrapper<T, R>(val bean: T,
val property: KMutableProperty1<T, R?>)
private fun <T, R : Any?> Wrapper<T, R>.get(): R?
= get(bean, property)
private fun <T, R : Any?> MutableWrapper<T, R>.set(value: R?)
= set(bean, property, value)
private fun <T, R : MutableList<V>?, V : Any?> Wrapper<T, R>.push(addedItems: Collection<V>)
= push(bean, property, addedItems)
private fun <T, R : MutableList<V>?, V : Any?> Wrapper<T, R>.pop()
= pop(bean, property)
private fun <T, R : MutableList<V>?, V : Any?> Wrapper<T, R>.splice(startIndex: Int,
removedCount: Int,
addedItems: Collection<V>)
= splice(bean, property, startIndex, removedCount, addedItems)
fun <T, R : Any?> get(bean: T,
property: KProperty1<T, R?>): R?
= property.get(bean)
fun <T, R : Any?> set(bean: T,
property: KMutableProperty1<T, R?>,
value: R): Unit
= property.set(bean, value)
fun <T, R : MutableList<V>?, V : Any?> push(bean: T,
property: KProperty1<T, R>,
addedItems: Collection<V>): Unit
= property.get(bean)!!.run { this!!.addAll(addedItems) }
fun <T, R : MutableList<V>?, V : Any?> pop(bean: T,
property: KProperty1<T, R?>): V
= property.get(bean)!!.run { this!!.removeAt(size - 1) }
fun <T, R : MutableList<V>?, V : Any?> splice(bean: T,
property: KProperty1<T, R>,
startIndex: Int,
removedCount: Int,
addedItems: Collection<V>): Unit
= property.get(bean)!!.subList(startIndex, startIndex + removedCount)
.apply { clear() }
.run { addAll(addedItems) }
| apache-2.0 | 134150a091ef2658839e0676ba327285 | 34.806202 | 117 | 0.510067 | 3.707063 | false | false | false | false |
artspb/1d34-3v4l-pl4g1n | src/main/kotlin/me/artspb/idea/eval/plugin/EvalAction.kt | 1 | 1457 | package me.artspb.idea.eval.plugin
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAware
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicNameValuePair
class EvalAction : AnAction(), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val file = e.dataContext.getData(CommonDataKeys.VIRTUAL_FILE)
if (file != null) {
val content = getContent(e, file)
val post = HttpPost("https://3v4l.org/new")
post.entity = UrlEncodedFormEntity(listOf(
BasicNameValuePair("title", file.name),
BasicNameValuePair("code", content)
))
val response = HttpClients.createDefault().execute(post)
val location = response.getFirstHeader("location")
if (location != null) {
val value = location.value
val url: String
if (value.startsWith("https://")) {
url = value
} else {
url = "https://3v4l.org$value"
}
BrowserUtil.browse(url)
}
}
}
}
| apache-2.0 | 80868b49d23dccfbac7181cf053c43b3 | 38.378378 | 69 | 0.624571 | 4.596215 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/overview/NoInternetCard.kt | 1 | 1872 | package de.tum.`in`.tumcampusapp.component.ui.overview
import android.content.Context
import android.content.SharedPreferences
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder
import de.tum.`in`.tumcampusapp.component.ui.overview.card.StickyCard
import de.tum.`in`.tumcampusapp.service.DownloadWorker
import de.tum.`in`.tumcampusapp.utils.NetUtils
import org.joda.time.DateTime
/**
* Card that informs that no internet connection is available
*/
class NoInternetCard(context: Context) : StickyCard(CardManager.CARD_NO_INTERNET, context) {
override fun updateViewHolder(viewHolder: RecyclerView.ViewHolder) {
super.updateViewHolder(viewHolder)
val view = viewHolder.itemView
val lastUpdate = view.findViewById<TextView>(R.id.card_last_update)
val lastUpdated = DateTime(DownloadWorker.lastUpdate(context))
val time = DateUtils.getRelativeTimeSpanString(
lastUpdated.millis,
System.currentTimeMillis(),
DateUtils.SECOND_IN_MILLIS).toString()
lastUpdate.text = String.format(context.getString(R.string.last_updated), time)
}
override fun shouldShow(prefs: SharedPreferences) = !NetUtils.isConnected(context)
override fun getId() = 0
companion object {
fun inflateViewHolder(
parent: ViewGroup,
interactionListener: CardInteractionListener
): CardViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.card_no_internet, parent, false)
return CardViewHolder(view, interactionListener)
}
}
}
| gpl-3.0 | 13347679fa4a3c658b639daa25d54bed | 36.44 | 92 | 0.725962 | 4.622222 | false | false | false | false |
grueni75/GeoDiscoverer | Source/Platform/Target/Android/mobile/src/main/java/com/untouchableapps/android/geodiscoverer/ui/component/GDDropdownMenu.kt | 1 | 2008 | //============================================================================
// Name : GDDropdownMenu.kt
// Author : Matthias Gruenewald
// Copyright : Copyright 2010-2022 Matthias Gruenewald
//
// This file is part of GeoDiscoverer.
//
// GeoDiscoverer 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.
//
// GeoDiscoverer 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 GeoDiscoverer. If not, see <http://www.gnu.org/licenses/>.
//
//============================================================================
package com.untouchableapps.android.geodiscoverer.ui.component
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import com.untouchableapps.android.geodiscoverer.ui.theme.Material2Theme
// Missing component in material3
// Replace later when eventually available
@Composable
fun GDDropdownMenu(
expanded: Boolean,
onDismissRequest: () -> Unit,
modifier: Modifier = Modifier,
offset: DpOffset = DpOffset(0.dp, 0.dp),
properties: PopupProperties = PopupProperties(focusable = true),
content: @Composable ColumnScope.() -> Unit
) {
DropdownMenu(
expanded = expanded,
onDismissRequest = onDismissRequest,
modifier = modifier,
offset = offset,
properties = properties,
content = content
)
}
| gpl-3.0 | adf66dfdc0374e448688eef0033c2234 | 36.185185 | 78 | 0.703187 | 4.365217 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/xray/format/xunit/XRayXUnitTestFailure.kt | 1 | 1837 | /*
* Copyright (C) 2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.marklogic.xray.format.xunit
import uk.co.reecedunn.intellij.plugin.core.xml.dom.XmlElement
import uk.co.reecedunn.intellij.plugin.processor.test.TestAssert
import uk.co.reecedunn.intellij.plugin.processor.test.TestResult
class XRayXUnitTestFailure(private val failure: XmlElement) : TestAssert {
companion object {
private val RE_ACTUAL = ", actual: ".toRegex()
}
private val expectedActual by lazy {
val message = failure.text()
when {
message == null -> null
message.startsWith("expected: ") && RE_ACTUAL.findAll(message).count() == 1 -> {
val parts = message.substring(10).split(", actual: ")
parts[0] to parts[1]
}
else -> null
}
}
override val type: String by lazy { failure.attributes.find { it.localName == "type" }!!.value }
override val result: TestResult = TestResult.Failed
override val expected: String? = expectedActual?.first
override val actual: String? = expectedActual?.second
override val message: String? by lazy {
when (expectedActual) {
null -> failure.text()
else -> null
}
}
}
| apache-2.0 | 12f8c6cc4a0991957f436731331fa35e | 33.660377 | 100 | 0.665215 | 4.252315 | false | true | false | false |
hardikamal/AppIntro | appintro/src/main/java/com/github/appintro/internal/viewpager/ViewPagerTransformer.kt | 3 | 5290 | package com.github.appintro.internal.viewpager
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.viewpager.widget.ViewPager
import com.github.appintro.AppIntroPageTransformerType
import com.github.appintro.R
import com.github.appintro.internal.LogHelper
private const val MIN_SCALE_DEPTH = 0.75f
private const val MIN_SCALE_ZOOM = 0.85f
private const val MIN_ALPHA_ZOOM = 0.5f
private const val SCALE_FACTOR_SLIDE = 0.85f
private const val MIN_ALPHA_SLIDE = 0.35f
private const val FLOW_ROTATION_ANGLE = -30f
internal class ViewPagerTransformer(
private val transformType: AppIntroPageTransformerType
) : ViewPager.PageTransformer {
private var titlePF: Double = 0.0
private var imagePF: Double = 0.0
private var descriptionPF: Double = 0.0
override fun transformPage(page: View, position: Float) {
when (transformType) {
AppIntroPageTransformerType.Flow -> {
page.rotationY = position * FLOW_ROTATION_ANGLE
}
AppIntroPageTransformerType.SlideOver -> transformSlideOver(position, page)
AppIntroPageTransformerType.Depth -> transformDepth(position, page)
AppIntroPageTransformerType.Zoom -> transformZoom(position, page)
AppIntroPageTransformerType.Fade -> transformFade(position, page)
is AppIntroPageTransformerType.Parallax -> {
titlePF = transformType.titleParallaxFactor
imagePF = transformType.imageParallaxFactor
descriptionPF = transformType.descriptionParallaxFactor
transformParallax(position, page)
}
}
}
private fun transformParallax(position: Float, page: View) {
if (position > -1 && position < 1) {
try {
applyParallax(page, position)
} catch (e: IllegalStateException) {
LogHelper.e(TAG, "Failed to apply parallax effect", e)
}
}
}
private fun applyParallax(page: View, position: Float) {
page.findViewById<TextView>(R.id.title).translationX = computeParallax(page, position, titlePF)
page.findViewById<ImageView>(R.id.image).translationX = computeParallax(page, position, imagePF)
page.findViewById<TextView>(R.id.description).translationX = computeParallax(page, position, descriptionPF)
}
private fun computeParallax(page: View, position: Float, parallaxFactor: Double): Float {
return (-position * (page.width / parallaxFactor)).toFloat()
}
private fun transformFade(position: Float, page: View) {
if (position <= -1.0f || position >= 1.0f) {
page.translationX = page.width.toFloat()
page.alpha = 0.0f
page.isClickable = false
} else if (position == 0.0f) {
page.translationX = 0.0f
page.alpha = 1.0f
page.isClickable = true
} else {
// position is between -1.0F & 0.0F OR 0.0F & 1.0F
page.translationX = page.width * -position
page.alpha = 1.0f - Math.abs(position)
}
}
private fun transformZoom(position: Float, page: View) {
if (position >= -1 && position <= 1) {
page.scaleXY = Math.max(MIN_SCALE_ZOOM, 1 - Math.abs(position))
page.alpha = MIN_ALPHA_ZOOM + (page.scaleXY - MIN_SCALE_ZOOM) /
(1 - MIN_SCALE_ZOOM) * (1 - MIN_ALPHA_ZOOM)
val vMargin = page.height * (1 - page.scaleXY) / 2
val hMargin = page.width * (1 - page.scaleXY) / 2
if (position < 0) {
page.translationX = hMargin - vMargin / 2
} else {
page.translationX = -hMargin + vMargin / 2
}
} else {
page.transformDefaults()
}
}
private fun transformDepth(position: Float, page: View) {
if (position > 0 && position < 1) {
// moving to the right
page.alpha = 1 - position
page.scaleXY = MIN_SCALE_DEPTH + (1 - MIN_SCALE_DEPTH) * (1 - Math.abs(position))
page.translationX = page.width * -position
} else {
page.transformDefaults()
}
}
private fun transformSlideOver(position: Float, page: View) {
if (position < 0 && position > -1) {
// this is the page to the left
page.scaleXY = Math.abs(Math.abs(position) - 1) * (1.0f - SCALE_FACTOR_SLIDE) + SCALE_FACTOR_SLIDE
page.alpha = Math.max(MIN_ALPHA_SLIDE, 1 - Math.abs(position))
val pageWidth = page.width
val translateValue = position * -pageWidth
if (translateValue > -pageWidth) {
page.translationX = translateValue
} else {
page.translationX = 0f
}
} else {
page.transformDefaults()
}
}
companion object {
private val TAG = LogHelper.makeLogTag(ViewPagerTransformer::class)
}
}
private fun View.transformDefaults() {
this.alpha = 1f
this.scaleXY = 1f
this.translationX = 0f
}
private var View.scaleXY: Float
get() = this.scaleX
set(value) {
this.scaleX = value
this.scaleY = value
}
| apache-2.0 | c2484adf75d245f6f99e8a2f7facf168 | 36.253521 | 115 | 0.608696 | 4.145768 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_SQUARE_FAIL.kt | 1 | 2102 | package info.nightscout.androidaps.diaconn.pumplog
import okhttp3.internal.and
import java.nio.ByteBuffer
import java.nio.ByteOrder
/*
* 스퀘어주입 실패
*/
class LOG_INJECT_SQUARE_FAIL private constructor(
val data: String,
val dttm: String,
typeAndKind: Byte, // 47.5=4750
val injectAmount: Short, // 1분단위 주입시간(124=124분=2시간4분)
private val injectTime: Byte, // 1=주입막힘, 2=배터리잔량부족, 3=약물부족, 4=사용자중지, 5=시스템리셋, 6=기타, 7=긴급정지
val reason: Byte,
val batteryRemain: Byte
) {
val type: Byte = PumplogUtil.getType(typeAndKind)
val kind: Byte = PumplogUtil.getKind(typeAndKind)
fun getInjectTime(): Int {
return injectTime and 0xff
}
override fun toString(): String {
val sb = StringBuilder("LOG_INJECT_SQUARE_FAIL{")
sb.append("LOG_KIND=").append(LOG_KIND.toInt())
sb.append(", data='").append(data).append('\'')
sb.append(", dttm='").append(dttm).append('\'')
sb.append(", type=").append(type.toInt())
sb.append(", kind=").append(kind.toInt())
sb.append(", injectAmount=").append(injectAmount.toInt())
sb.append(", injectTime=").append(injectTime and 0xff)
sb.append(", reason=").append(reason.toInt())
sb.append(", batteryRemain=").append(batteryRemain.toInt())
sb.append('}')
return sb.toString()
}
companion object {
const val LOG_KIND: Byte = 0x0E
fun parse(data: String): LOG_INJECT_SQUARE_FAIL {
val bytes = PumplogUtil.hexStringToByteArray(data)
val buffer = ByteBuffer.wrap(bytes)
buffer.order(ByteOrder.LITTLE_ENDIAN)
return LOG_INJECT_SQUARE_FAIL(
data,
PumplogUtil.getDttm(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getShort(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getByte(buffer)
)
}
}
} | agpl-3.0 | de3fbdcc00dfa051d912e0c50afc4985 | 31.868852 | 97 | 0.603293 | 3.591398 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/autotune/AutotunePrep.kt | 1 | 31110 | package info.nightscout.androidaps.plugins.general.autotune
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.LocalInsulin
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.plugins.general.autotune.data.*
import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.database.entities.Carbs
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.MidnightTime
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.T
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class AutotunePrep @Inject constructor(
private val aapsLogger: AAPSLogger,
private val sp: SP,
private val dateUtil: DateUtil,
private val autotuneFS: AutotuneFS,
private val autotuneIob: AutotuneIob
) {
fun categorize(tunedprofile: ATProfile): PreppedGlucose? {
val preppedGlucose = categorizeBGDatums(tunedprofile, tunedprofile.localInsulin)
val tuneInsulin = sp.getBoolean(R.string.key_autotune_tune_insulin_curve, false)
if (tuneInsulin) {
var minDeviations = 1000000.0
val diaDeviations: MutableList<DiaDeviation> = ArrayList()
val peakDeviations: MutableList<PeakDeviation> = ArrayList()
val currentDIA = tunedprofile.localInsulin.dia
val currentPeak = tunedprofile.localInsulin.peak
var dia = currentDIA - 2
val endDIA = currentDIA + 2
while (dia <= endDIA)
{
var sqrtDeviations = 0.0
var deviations = 0.0
var deviationsSq = 0.0
val localInsulin = LocalInsulin("Ins_$currentPeak-$dia", currentPeak, dia)
val curve_output = categorizeBGDatums(tunedprofile, localInsulin, false)
val basalGlucose = curve_output?.basalGlucoseData
basalGlucose?.let {
for (hour in 0..23) {
for (i in 0..(basalGlucose.size-1)) {
val myHour = ((basalGlucose[i].date - MidnightTime.calc(basalGlucose[i].date)) / T.hours(1).msecs()).toInt()
if (hour == myHour) {
sqrtDeviations += Math.pow(Math.abs(basalGlucose[i].deviation), 0.5)
deviations += Math.abs(basalGlucose[i].deviation)
deviationsSq += Math.pow(basalGlucose[i].deviation, 2.0)
}
}
}
val meanDeviation = Round.roundTo(Math.abs(deviations / basalGlucose.size), 0.001)
val smrDeviation = Round.roundTo(Math.pow(sqrtDeviations / basalGlucose.size, 2.0), 0.001)
val rmsDeviation = Round.roundTo(Math.pow(deviationsSq / basalGlucose.size, 0.5), 0.001)
log("insulinEndTime $dia meanDeviation: $meanDeviation SMRDeviation: $smrDeviation RMSDeviation: $rmsDeviation (mg/dL)")
diaDeviations.add(
DiaDeviation(
dia = dia,
meanDeviation = meanDeviation,
smrDeviation = smrDeviation,
rmsDeviation = rmsDeviation
)
)
}
preppedGlucose?.diaDeviations = diaDeviations
deviations = Round.roundTo(deviations, 0.001)
if (deviations < minDeviations)
minDeviations = Round.roundTo(deviations, 0.001)
dia += 1.0
}
// consoleError('Optimum insulinEndTime', newDIA, 'mean deviation:', JSMath.Round(minDeviations/basalGlucose.length*1000)/1000, '(mg/dL)');
//consoleError(diaDeviations);
minDeviations = 1000000.0
var peak = currentPeak - 10
val endPeak = currentPeak + 10
while (peak <= endPeak)
{
var sqrtDeviations = 0.0
var deviations = 0.0
var deviationsSq = 0.0
val localInsulin = LocalInsulin("Ins_$peak-$currentDIA", peak, currentDIA)
val curve_output = categorizeBGDatums(tunedprofile, localInsulin, false)
val basalGlucose = curve_output?.basalGlucoseData
basalGlucose?.let {
for (hour in 0..23) {
for (i in 0..(basalGlucose.size - 1)) {
val myHour = ((basalGlucose[i].date - MidnightTime.calc(basalGlucose[i].date)) / T.hours(1).msecs()).toInt()
if (hour == myHour) {
//console.error(basalGlucose[i].deviation);
sqrtDeviations += Math.pow(Math.abs(basalGlucose[i].deviation), 0.5)
deviations += Math.abs(basalGlucose[i].deviation)
deviationsSq += Math.pow(basalGlucose[i].deviation, 2.0)
}
}
}
val meanDeviation = Round.roundTo(deviations / basalGlucose.size, 0.001)
val smrDeviation = Round.roundTo(Math.pow(sqrtDeviations / basalGlucose.size, 2.0), 0.001)
val rmsDeviation = Round.roundTo(Math.pow(deviationsSq / basalGlucose.size, 0.5), 0.001)
log("insulinPeakTime $peak meanDeviation: $meanDeviation SMRDeviation: $smrDeviation RMSDeviation: $rmsDeviation (mg/dL)")
peakDeviations.add(
PeakDeviation
(
peak = peak,
meanDeviation = meanDeviation,
smrDeviation = smrDeviation,
rmsDeviation = rmsDeviation,
)
)
}
deviations = Round.roundTo(deviations, 0.001);
if (deviations < minDeviations)
minDeviations = Round.roundTo(deviations, 0.001)
peak += 5
}
//consoleError($"Optimum insulinPeakTime {newPeak} mean deviation: {JSMath.Round(minDeviations/basalGlucose.Count, 3)} (mg/dL)");
//consoleError(peakDeviations);
preppedGlucose?.peakDeviations = peakDeviations
}
return preppedGlucose
}
// private static Logger log = LoggerFactory.getLogger(AutotunePlugin.class);
fun categorizeBGDatums(tunedprofile: ATProfile, localInsulin: LocalInsulin, verbose: Boolean = true): PreppedGlucose? {
//lib/meals is called before to get only meals data (in AAPS it's done in AutotuneIob)
val treatments: MutableList<Carbs> = autotuneIob.meals
val boluses: MutableList<Bolus> = autotuneIob.boluses
// Bloc between #21 and # 54 replaced by bloc below (just remove BG value below 39, Collections.sort probably not necessary because BG values already sorted...)
val glucose = autotuneIob.glucose
val glucoseData: MutableList<GlucoseValue> = ArrayList()
for (i in glucose.indices) {
if (glucose[i].value > 39) {
glucoseData.add(glucose[i])
}
}
if (glucose.size == 0 || glucoseData.size == 0 ) {
//aapsLogger.debug(LTag.AUTOTUNE, "No BG value received")
if (verbose)
log("No BG value received")
return null
}
glucoseData.sortWith(object: Comparator<GlucoseValue>{ override fun compare(o1: GlucoseValue, o2: GlucoseValue): Int = (o2.timestamp - o1.timestamp).toInt() })
// Bloc below replace bloc between #55 and #71
// boluses and maxCarbs not used here ?,
// IOBInputs are for iob calculation (done here in AutotuneIob Class)
//val boluses = 0
//val maxCarbs = 0
if (treatments.size == 0) {
//aapsLogger.debug(LTag.AUTOTUNE, "No Carbs entries")
if (verbose)
log("No Carbs entries")
//return null
}
if (autotuneIob.boluses.size == 0) {
//aapsLogger.debug(LTag.AUTOTUNE, "No treatment received")
if (verbose)
log("No treatment received")
return null
}
var csfGlucoseData: MutableList<BGDatum> = ArrayList()
var isfGlucoseData: MutableList<BGDatum> = ArrayList()
var basalGlucoseData: MutableList<BGDatum> = ArrayList()
val uamGlucoseData: MutableList<BGDatum> = ArrayList()
val crData: MutableList<CRDatum> = ArrayList()
//Bloc below replace bloc between #72 and #93
// I keep it because BG lines in log are consistent between AAPS and Oref0
val bucketedData: MutableList<BGDatum> = ArrayList()
bucketedData.add(BGDatum(glucoseData[0], dateUtil))
//int j=0;
var k = 0 // index of first value used by bucket
//for loop to validate and bucket the data
for (i in 1 until glucoseData.size) {
val BGTime = glucoseData[i].timestamp
val lastBGTime = glucoseData[k].timestamp
val elapsedMinutes = (BGTime - lastBGTime) / (60 * 1000)
if (Math.abs(elapsedMinutes) >= 2) {
//j++; // move to next bucket
k = i // store index of first value used by bucket
bucketedData.add(BGDatum(glucoseData[i], dateUtil))
} else {
// average all readings within time deadband
val average = glucoseData[k]
for (l in k + 1 until i + 1) {
average.value += glucoseData[l].value
}
average.value = average.value / (i - k + 1)
bucketedData.add(BGDatum(average, dateUtil))
}
}
// Here treatments contains only meals data
// bloc between #94 and #114 remove meals before first BG value
// Bloc below replace bloc between #115 and #122 (initialize data before main loop)
// crInitialxx are declaration to be able to use these data in whole loop
var calculatingCR = false
var absorbing = false
var uam = false // unannounced meal
var mealCOB = 0.0
var mealCarbs = 0.0
var crCarbs = 0.0
var type = ""
var crInitialIOB = 0.0
var crInitialBG = 0.0
var crInitialCarbTime = 0L
//categorize.js#123 (Note: don't need fullHistory because data are managed in AutotuneIob Class)
//Here is main loop between #125 and #366
// main for loop
for (i in bucketedData.size - 5 downTo 1) {
val glucoseDatum = bucketedData[i]
//log.debug(glucoseDatum);
val BGTime = glucoseDatum.date
// As we're processing each data point, go through the treatment.carbs and see if any of them are older than
// the current BG data point. If so, add those carbs to COB.
val treatment = if (treatments.size > 0) treatments[treatments.size - 1] else null
var myCarbs = 0.0
if (treatment != null) {
if (treatment.timestamp < BGTime) {
if (treatment.amount > 0.0) {
mealCOB += treatment.amount
mealCarbs += treatment.amount
myCarbs = treatment.amount
}
treatments.removeAt(treatments.size - 1)
}
}
var bg = 0.0
var avgDelta = 0.0
// TODO: re-implement interpolation to avoid issues here with gaps
// calculate avgDelta as last 4 datapoints to better catch more rises after COB hits zero
if (bucketedData[i].value != 0.0 && bucketedData[i + 4].value != 0.0) {
//log.debug(bucketedData[i]);
bg = bucketedData[i].value
if (bg < 40 || bucketedData[i + 4].value < 40) {
//process.stderr.write("!");
continue
}
avgDelta = (bg - bucketedData[i + 4].value) / 4
} else {
//aapsLogger.debug(LTag.AUTOTUNE, "Could not find glucose data")
if (verbose)
log("Could not find glucose data")
}
avgDelta = Round.roundTo(avgDelta, 0.01)
glucoseDatum.avgDelta = avgDelta
//sens = ISF
val sens = tunedprofile.isf
// for IOB calculations, use the average of the last 4 hours' basals to help convergence;
// this helps since the basal this hour could be different from previous, especially if with autotune they start to diverge.
// use the pumpbasalprofile to properly calculate IOB during periods where no temp basal is set
/* Note Philoul currentPumpBasal never used in oref0 Autotune code
var currentPumpBasal = pumpprofile.profile.getBasal(BGTime)
currentPumpBasal += pumpprofile.profile.getBasal(BGTime - 1 * 60 * 60 * 1000)
currentPumpBasal += pumpprofile.profile.getBasal(BGTime - 2 * 60 * 60 * 1000)
currentPumpBasal += pumpprofile.profile.getBasal(BGTime - 3 * 60 * 60 * 1000)
currentPumpBasal = Round.roundTo(currentPumpBasal / 4, 0.001) //CurrentPumpBasal for iob calculation is average of 4 last pumpProfile Basal rate
*/
// this is the current autotuned basal, used for everything else besides IOB calculations
val currentBasal = tunedprofile.getBasal(BGTime)
// basalBGI is BGI of basal insulin activity.
val basalBGI = Round.roundTo(currentBasal * sens / 60 * 5, 0.01) // U/hr * mg/dL/U * 1 hr / 60 minutes * 5 = mg/dL/5m
//console.log(JSON.stringify(IOBInputs.profile));
// call iob since calculated elsewhere
//var iob = getIOB(IOBInputs)[0];
// in autotune iob is calculated with 6 hours of history data, tunedProfile and average pumpProfile basal rate...
//log("currentBasal: " + currentBasal + " BGTime: " + BGTime + " / " + dateUtil!!.timeStringWithSeconds(BGTime) + "******************************************************************************************")
val iob = autotuneIob.getIOB(BGTime, localInsulin) // add localInsulin to be independent to InsulinPlugin
// activity times ISF times 5 minutes is BGI
val BGI = Round.roundTo(-iob.activity * sens * 5, 0.01)
// datum = one glucose data point (being prepped to store in output)
glucoseDatum.bgi = BGI
// calculating deviation
var deviation = avgDelta - BGI
// set positive deviations to zero if BG is below 80
if (bg < 80 && deviation > 0) {
deviation = 0.0
}
// rounding and storing deviation
deviation = Round.roundTo(deviation, 0.01)
glucoseDatum.deviation = deviation
// Then, calculate carb absorption for that 5m interval using the deviation.
if (mealCOB > 0) {
val ci = Math.max(deviation, sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, 3.0))
val absorbed = ci * tunedprofile.ic / sens
// Store the COB, and use it as the starting point for the next data point.
mealCOB = Math.max(0.0, mealCOB - absorbed)
}
// Calculate carb ratio (CR) independently of CSF and ISF
// Use the time period from meal bolus/carbs until COB is zero and IOB is < currentBasal/2
// For now, if another meal IOB/COB stacks on top of it, consider them together
// Compare beginning and ending BGs, and calculate how much more/less insulin is needed to neutralize
// Use entered carbs vs. starting IOB + delivered insulin + needed-at-end insulin to directly calculate CR.
if (mealCOB > 0 || calculatingCR) {
// set initial values when we first see COB
crCarbs += myCarbs
if (calculatingCR == false) {
crInitialIOB = iob.iob
crInitialBG = glucoseDatum.value
crInitialCarbTime = glucoseDatum.date
//aapsLogger.debug(LTag.AUTOTUNE, "CRInitialIOB: $crInitialIOB CRInitialBG: $crInitialBG CRInitialCarbTime: ${dateUtil.toISOString(crInitialCarbTime)}")
if (verbose)
log("CRInitialIOB: $crInitialIOB CRInitialBG: $crInitialBG CRInitialCarbTime: ${dateUtil.toISOString(crInitialCarbTime)}")
}
// keep calculatingCR as long as we have COB or enough IOB
if (mealCOB > 0 && i > 1) {
calculatingCR = true
} else if (iob.iob > currentBasal / 2 && i > 1) {
calculatingCR = true
// when COB=0 and IOB drops low enough, record end values and be done calculatingCR
} else {
val crEndIOB = iob.iob
val crEndBG = glucoseDatum.value
val crEndTime = glucoseDatum.date
//aapsLogger.debug(LTag.AUTOTUNE, "CREndIOB: $crEndIOB CREndBG: $crEndBG CREndTime: ${dateUtil.toISOString(crEndTime)}")
if (verbose)
log("CREndIOB: $crEndIOB CREndBG: $crEndBG CREndTime: ${dateUtil.toISOString(crEndTime)}")
val crDatum = CRDatum(dateUtil)
crDatum.crInitialBG = crInitialBG
crDatum.crInitialIOB = crInitialIOB
crDatum.crInitialCarbTime = crInitialCarbTime
crDatum.crEndBG = crEndBG
crDatum.crEndIOB = crEndIOB
crDatum.crEndTime = crEndTime
crDatum.crCarbs = crCarbs
//log.debug(CRDatum);
//String crDataString = "{\"CRInitialIOB\": " + CRInitialIOB + ", \"CRInitialBG\": " + CRInitialBG + ", \"CRInitialCarbTime\": " + CRInitialCarbTime + ", \"CREndIOB\": " + CREndIOB + ", \"CREndBG\": " + CREndBG + ", \"CREndTime\": " + CREndTime + ", \"CRCarbs\": " + CRCarbs + "}";
val CRElapsedMinutes = Math.round((crEndTime - crInitialCarbTime) / (1000 * 60).toFloat())
//log.debug(CREndTime - CRInitialCarbTime, CRElapsedMinutes);
if (CRElapsedMinutes < 60 || i == 1 && mealCOB > 0) {
//aapsLogger.debug(LTag.AUTOTUNE, "Ignoring $CRElapsedMinutes m CR period.")
if (verbose)
log("Ignoring $CRElapsedMinutes m CR period.")
} else {
crData.add(crDatum)
}
crCarbs = 0.0
calculatingCR = false
}
}
// If mealCOB is zero but all deviations since hitting COB=0 are positive, assign those data points to CSFGlucoseData
// Once deviations go negative for at least one data point after COB=0, we can use the rest of the data to tune ISF or basals
if (mealCOB > 0 || absorbing || mealCarbs > 0) {
// if meal IOB has decayed, then end absorption after this data point unless COB > 0
absorbing = if (iob.iob < currentBasal / 2) {
false
// otherwise, as long as deviations are positive, keep tracking carb deviations
} else if (deviation > 0) {
true
} else {
false
}
if (!absorbing && mealCOB == 0.0) {
mealCarbs = 0.0
}
// check previous "type" value, and if it wasn't csf, set a mealAbsorption start flag
//log.debug(type);
if (type != "csf") {
glucoseDatum.mealAbsorption = "start"
//aapsLogger.debug(LTag.AUTOTUNE, "${glucoseDatum.mealAbsorption} carb absorption")
if (verbose)
log("${glucoseDatum.mealAbsorption} carb absorption")
}
type = "csf"
glucoseDatum.mealCarbs = mealCarbs.toInt()
//if (i == 0) { glucoseDatum.mealAbsorption = "end"; }
csfGlucoseData.add(glucoseDatum)
} else {
// check previous "type" value, and if it was csf, set a mealAbsorption end flag
if (type == "csf") {
csfGlucoseData[csfGlucoseData.size - 1].mealAbsorption = "end"
//aapsLogger.debug(LTag.AUTOTUNE, "${csfGlucoseData[csfGlucoseData.size - 1].mealAbsorption} carb absorption")
if (verbose)
log("${csfGlucoseData[csfGlucoseData.size - 1].mealAbsorption} carb absorption")
}
if (iob.iob > 2 * currentBasal || deviation > 6 || uam) {
uam = if (deviation > 0) {
true
} else {
false
}
if (type != "uam") {
glucoseDatum.uamAbsorption = "start"
//aapsLogger.debug(LTag.AUTOTUNE, "${glucoseDatum.uamAbsorption} unannnounced meal absorption")
if (verbose)
log(glucoseDatum.uamAbsorption + " unannnounced meal absorption")
}
type = "uam"
uamGlucoseData.add(glucoseDatum)
} else {
if (type == "uam") {
//aapsLogger.debug(LTag.AUTOTUNE, "end unannounced meal absorption")
if (verbose)
log("end unannounced meal absorption")
}
// Go through the remaining time periods and divide them into periods where scheduled basal insulin activity dominates. This would be determined by calculating the BG impact of scheduled basal insulin
// (for example 1U/hr * 48 mg/dL/U ISF = 48 mg/dL/hr = 5 mg/dL/5m), and comparing that to BGI from bolus and net basal insulin activity.
// When BGI is positive (insulin activity is negative), we want to use that data to tune basals
// When BGI is smaller than about 1/4 of basalBGI, we want to use that data to tune basals
// When BGI is negative and more than about 1/4 of basalBGI, we can use that data to tune ISF,
// unless avgDelta is positive: then that's some sort of unexplained rise we don't want to use for ISF, so that means basals
if (basalBGI > -4 * BGI) {
type = "basal"
basalGlucoseData.add(glucoseDatum)
} else {
if (avgDelta > 0 && avgDelta > -2 * BGI) {
//type="unknown"
type = "basal"
basalGlucoseData.add(glucoseDatum)
} else {
type = "ISF"
isfGlucoseData.add(glucoseDatum)
}
}
}
}
// debug line to print out all the things
//aapsLogger.debug(LTag.AUTOTUNE, "${(if (absorbing) 1 else 0)} mealCOB: ${Round.roundTo(mealCOB, 0.1)} mealCarbs: ${Math.round(mealCarbs)} basalBGI: ${Round.roundTo(basalBGI, 0.1)} BGI: ${Round.roundTo(BGI, 0.1)} IOB: ${iob.iob} Activity: ${iob.activity} at ${dateUtil.timeStringWithSeconds(BGTime)} dev: $deviation avgDelta: $avgDelta $type")
if (verbose)
log("${(if (absorbing) 1 else 0)} mealCOB: ${Round.roundTo(mealCOB, 0.1)} mealCarbs: ${Math.round(mealCarbs)} basalBGI: ${Round.roundTo(basalBGI, 0.1)} BGI: ${Round
.roundTo(BGI, 0.1)} IOB: ${iob.iob} Activity: ${iob.activity} at ${dateUtil.timeStringWithSeconds(BGTime)} dev: $deviation avgDelta: $avgDelta $type")
}
//****************************************************************************************************************************************
// categorize.js Lines 372-383
for (crDatum in crData) {
crDatum.crInsulin = dosed(crDatum.crInitialCarbTime, crDatum.crEndTime, boluses)
}
// categorize.js Lines 384-436
val CSFLength = csfGlucoseData.size
var ISFLength = isfGlucoseData.size
val UAMLength = uamGlucoseData.size
var basalLength = basalGlucoseData.size
if (sp.getBoolean(R.string.key_autotune_categorize_uam_as_basal, false)) {
//aapsLogger.debug(LTag.AUTOTUNE, "Categorizing all UAM data as basal.")
if (verbose)
log("Categorizing all UAM data as basal.")
basalGlucoseData.addAll(uamGlucoseData)
} else if (CSFLength > 12) {
//aapsLogger.debug(LTag.AUTOTUNE, "Found at least 1h of carb: assuming meals were announced, and categorizing UAM data as basal.")
if (verbose)
log("Found at least 1h of carb: assuming meals were announced, and categorizing UAM data as basal.")
basalGlucoseData.addAll(uamGlucoseData)
} else {
if (2 * basalLength < UAMLength) {
//log.debug(basalGlucoseData, UAMGlucoseData);
//aapsLogger.debug(LTag.AUTOTUNE, "Warning: too many deviations categorized as UnAnnounced Meals")
//aapsLogger.debug(LTag.AUTOTUNE, "Adding $UAMLength UAM deviations to $basalLength basal ones")
if (verbose) {
log("Warning: too many deviations categorized as UnAnnounced Meals")
log("Adding $UAMLength UAM deviations to $basalLength basal ones")
}
basalGlucoseData.addAll(uamGlucoseData)
//log.debug(basalGlucoseData);
// if too much data is excluded as UAM, add in the UAM deviations, but then discard the highest 50%
basalGlucoseData.sortWith(object: Comparator<BGDatum>{ override fun compare(o1: BGDatum, o2: BGDatum): Int = (100 * o1.deviation - 100 * o2.deviation).toInt() }) //deviation rouded to 0.01, so *100 to avoid crash during sort
val newBasalGlucose: MutableList<BGDatum> = ArrayList()
for (i in 0 until basalGlucoseData.size / 2) {
newBasalGlucose.add(basalGlucoseData[i])
}
//log.debug(newBasalGlucose);
basalGlucoseData = newBasalGlucose
//aapsLogger.debug(LTag.AUTOTUNE, "and selecting the lowest 50%, leaving ${basalGlucoseData.size} basal+UAM ones")
if (verbose)
log("and selecting the lowest 50%, leaving ${basalGlucoseData.size} basal+UAM ones")
}
if (2 * ISFLength < UAMLength) {
//aapsLogger.debug(LTag.AUTOTUNE, "Adding $UAMLength UAM deviations to $ISFLength ISF ones")
if (verbose)
log("Adding $UAMLength UAM deviations to $ISFLength ISF ones")
isfGlucoseData.addAll(uamGlucoseData)
// if too much data is excluded as UAM, add in the UAM deviations to ISF, but then discard the highest 50%
isfGlucoseData.sortWith(object: Comparator<BGDatum>{ override fun compare(o1: BGDatum, o2: BGDatum): Int = (100 * o1.deviation - 100 * o2.deviation).toInt() }) //deviation rouded to 0.01, so *100 to avoid crash during sort
val newISFGlucose: MutableList<BGDatum> = ArrayList()
for (i in 0 until isfGlucoseData.size / 2) {
newISFGlucose.add(isfGlucoseData[i])
}
//console.error(newISFGlucose);
isfGlucoseData = newISFGlucose
//aapsLogger.debug(LTag.AUTOTUNE, "and selecting the lowest 50%, leaving ${isfGlucoseData.size} ISF+UAM ones")
if (verbose)
log("and selecting the lowest 50%, leaving ${isfGlucoseData.size} ISF+UAM ones")
//log.error(ISFGlucoseData.length, UAMLength);
}
}
basalLength = basalGlucoseData.size
ISFLength = isfGlucoseData.size
if (4 * basalLength + ISFLength < CSFLength && ISFLength < 10) {
//aapsLogger.debug(LTag.AUTOTUNE, "Warning: too many deviations categorized as meals")
//aapsLogger.debug(LTag.AUTOTUNE, "Adding $CSFLength CSF deviations to $ISFLength ISF ones")
if (verbose) {
log("Warning: too many deviations categorized as meals")
//log.debug("Adding",CSFLength,"CSF deviations to",basalLength,"basal ones");
//var basalGlucoseData = basalGlucoseData.concat(CSFGlucoseData);
log("Adding $CSFLength CSF deviations to $ISFLength ISF ones")
}
isfGlucoseData.addAll(csfGlucoseData)
csfGlucoseData = ArrayList()
}
// categorize.js Lines 437-444
//aapsLogger.debug(LTag.AUTOTUNE, "CRData: ${crData.size} CSFGlucoseData: ${csfGlucoseData.size} ISFGlucoseData: ${isfGlucoseData.size} BasalGlucoseData: ${basalGlucoseData.size}")
if (verbose)
log("CRData: ${crData.size} CSFGlucoseData: ${csfGlucoseData.size} ISFGlucoseData: ${isfGlucoseData.size} BasalGlucoseData: ${basalGlucoseData.size}")
return PreppedGlucose(autotuneIob.startBG, crData, csfGlucoseData, isfGlucoseData, basalGlucoseData, dateUtil)
}
//dosed.js full
private fun dosed(start: Long, end: Long, treatments: List<Bolus>): Double {
var insulinDosed = 0.0
//aapsLogger.debug(LTag.AUTOTUNE, "No treatments to process.")
if (treatments.size == 0) {
log("No treatments to process.")
return 0.0
}
for (treatment in treatments) {
if (treatment.amount != 0.0 && treatment.timestamp > start && treatment.timestamp <= end) {
insulinDosed += treatment.amount
//log("CRDATA;${dateUtil.toISOString(start)};${dateUtil.toISOString(end)};${treatment.timestamp};${treatment.amount};$insulinDosed")
}
}
//log("insulin dosed: " + insulinDosed);
return Round.roundTo(insulinDosed, 0.001)
}
private fun log(message: String) {
autotuneFS.atLog("[Prep] $message")
}
} | agpl-3.0 | 5761e8e9d18fb4a91dead00d71d67515 | 54.259325 | 356 | 0.562424 | 4.489177 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/fragment/impl/DefaultHorizontalTabBar.kt | 1 | 2041 | package org.hexworks.zircon.internal.fragment.impl
import org.hexworks.zircon.api.ComponentDecorations.margin
import org.hexworks.zircon.api.Components
import org.hexworks.zircon.api.component.AttachedComponent
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.component.HBox
import org.hexworks.zircon.api.component.Panel
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.dsl.component.buildVbox
import org.hexworks.zircon.api.dsl.component.hbox
import org.hexworks.zircon.api.dsl.component.panel
import org.hexworks.zircon.api.fragment.TabBar
import org.hexworks.zircon.internal.component.renderer.NoOpComponentRenderer
class DefaultHorizontalTabBar internal constructor(
size: Size,
defaultSelected: String,
tabs: List<TabData>
) : TabBar {
private lateinit var tabBar: HBox
private lateinit var content: Panel
private var currentContent: AttachedComponent? = null
private val group = Components.radioButtonGroup().build()
private val lookup = tabs.associate { (tab, content) ->
group.addComponent(tab.tabButton)
tab.key to TabData(tab, content)
}
override val root: Component = buildVbox {
preferredSize = size
componentRenderer = NoOpComponentRenderer()
tabBar = hbox {
preferredSize = Size.create(size.width, 3)
decoration = margin(0, 1)
componentRenderer = NoOpComponentRenderer()
childrenToAdd = lookup.map { it.value.tab.root }
}
content = panel {
preferredSize = size.withRelativeHeight(-3)
}
group.selectedButtonProperty.onChange { (_, newValue) ->
newValue?.let { button ->
currentContent?.detach()?.moveTo(Position.defaultPosition())
currentContent = content.addComponent(lookup.getValue(button.key).content)
}
}
lookup.getValue(defaultSelected).tab.isSelected = true
}
}
| apache-2.0 | 8370eac947229dee176644a7ff2799a0 | 34.807018 | 90 | 0.709456 | 4.417749 | false | false | false | false |
JetBrains/ideavim | src/test/java/org/jetbrains/plugins/ideavim/extension/exchange/VimExchangeWithClipboardTest.kt | 1 | 10609 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package org.jetbrains.plugins.ideavim.extension.exchange
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.extension.exchange.VimExchangeExtension
import com.maddyhome.idea.vim.helper.VimBehaviorDiffers
import com.maddyhome.idea.vim.options.OptionConstants
import org.jetbrains.plugins.ideavim.OptionValueType
import org.jetbrains.plugins.ideavim.VimOptionTestCase
import org.jetbrains.plugins.ideavim.VimOptionTestConfiguration
import org.jetbrains.plugins.ideavim.VimTestOption
class VimExchangeWithClipboardTest : VimOptionTestCase(OptionConstants.clipboardName) {
@Throws(Exception::class)
override fun setUp() {
super.setUp()
enableExtensions("exchange")
}
// |cx|
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test exchange words left to right`() {
doTest(
listOf("cxe", "w", "cxe"),
"The quick ${c}brown fox catch over the lazy dog",
"The quick fox ${c}brown catch over the lazy dog",
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
// |cx|
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test exchange words dot repeat`() {
doTest(
listOf("cxiw", "w", "."),
"The quick ${c}brown fox catch over the lazy dog",
"The quick fox ${c}brown catch over the lazy dog",
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
// |cx|
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test exchange words right to left`() {
doTest(
listOf("cxe", "b", "cxe"),
"The quick brown ${c}fox catch over the lazy dog",
"The quick ${c}fox brown catch over the lazy dog",
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
// |cx|
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test exchange words right to left with dot`() {
doTest(
listOf("cxe", "b", "."),
"The quick brown ${c}fox catch over the lazy dog",
"The quick ${c}fox brown catch over the lazy dog",
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
// |X|
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test visual exchange words left to right`() {
doTest(
listOf("veX", "w", "veX"),
"The quick ${c}brown fox catch over the lazy dog",
"The quick fox ${c}brown catch over the lazy dog",
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
// |X|
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
@VimBehaviorDiffers(
originalVimAfter = "The ${c}brown catch over the lazy dog",
shouldBeFixed = true
)
fun `test visual exchange words from inside`() {
doTest(
listOf("veX", "b", "v3e", "X"),
"The quick ${c}brown fox catch over the lazy dog",
"The brow${c}n catch over the lazy dog",
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
// |X|
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
@VimBehaviorDiffers(
originalVimAfter = "The brown ${c}catch over the lazy dog",
shouldBeFixed = true
)
fun `test visual exchange words from outside`() {
doTest(
listOf("v3e", "X", "w", "veX"),
"The ${c}quick brown fox catch over the lazy dog",
"The brow${c}n catch over the lazy dog",
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
// |cxx|
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
@VimBehaviorDiffers(
originalVimAfter =
"""The quick
catch over
${c}brown fox
the lazy dog
""",
shouldBeFixed = true
)
fun `test exchange lines top down`() {
doTest(
listOf("cxx", "j", "cxx"),
"""The quick
brown ${c}fox
catch over
the lazy dog
""".trimIndent(),
"""The quick
${c}catch over
brown fox
the lazy dog
""".trimIndent(),
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
// |cxx|
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
@VimBehaviorDiffers(
originalVimAfter =
"""The quick
catch over
${c}brown fox
the lazy dog
""",
shouldBeFixed = true
)
fun `test exchange lines top down with dot`() {
doTest(
listOf("cxx", "j", "."),
"""The quick
brown ${c}fox
catch over
the lazy dog
""".trimIndent(),
"""The quick
${c}catch over
brown fox
the lazy dog
""".trimIndent(),
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
@VimBehaviorDiffers(
originalVimAfter = """
The quick
brown thecatch over
fox
lazy dog
"""
)
fun `test exchange to the line end`() {
doTest(
listOf("v$", "X", "jj^ve", "X"),
"""The quick
brown ${c}fox
catch over
the lazy dog
""".trimIndent(),
"""The quick
brown the
catch over
fox lazy dog
""".trimIndent(),
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
@VimBehaviorDiffers(
originalVimAfter =
"""
catch over
the lazy dog
${c}The quick
brown fox
""",
shouldBeFixed = true
)
fun `test exchange visual lines`() {
doTest(
listOf("Vj", "X", "jj", "Vj", "X"),
"""
The ${c}quick
brown fox
catch over
the lazy dog
""".trimIndent(),
"""
${c}catch over
the lazy dog
The quick
brown fox
""".trimIndent(),
VimStateMachine.Mode.COMMAND,
VimStateMachine.SubMode.NONE
)
}
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test visual char highlighter`() {
val before = """
The ${c}quick
brown fox
catch over
the lazy dog
""".trimIndent()
configureByText(before)
typeText(injector.parser.parseKeys("vlll" + "X"))
assertHighlighter(4, 8, HighlighterTargetArea.EXACT_RANGE)
// Exit vim-exchange
exitExchange()
}
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test visual line highdhitligthhter`() {
val before = """
The ${c}quick
brown fox
catch over
the lazy dog
""".trimIndent()
configureByText(before)
typeText(injector.parser.parseKeys("Vj" + "X"))
assertHighlighter(4, 15, HighlighterTargetArea.LINES_IN_RANGE)
// Exit vim-exchange
exitExchange()
}
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test till the line end highlighter`() {
val before = """
The ${c}quick
brown fox
""".trimIndent()
configureByText(before)
typeText(injector.parser.parseKeys("v$" + "X"))
assertHighlighter(4, 10, HighlighterTargetArea.EXACT_RANGE)
// Exit vim-exchange
exitExchange()
}
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test pre line end highlighter`() {
val before = """
The ${c}quick
brown fox
""".trimIndent()
configureByText(before)
typeText(injector.parser.parseKeys("v\$h" + "X"))
assertHighlighter(4, 9, HighlighterTargetArea.EXACT_RANGE)
// Exit vim-exchange
exitExchange()
}
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test pre pre line end highlighter`() {
val before = """
The ${c}quick
brown fox
""".trimIndent()
configureByText(before)
typeText(injector.parser.parseKeys("v\$hh" + "X"))
assertHighlighter(4, 8, HighlighterTargetArea.EXACT_RANGE)
// Exit vim-exchange
exitExchange()
}
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test to file end highlighter`() {
val before = """
The quick
brown ${c}fox
""".trimIndent()
configureByText(before)
typeText(
injector.parser.parseKeys(
buildString {
append("v\$")
append("X")
}
)
)
assertHighlighter(16, 19, HighlighterTargetArea.EXACT_RANGE)
// Exit vim-exchange
exitExchange()
}
@VimOptionTestConfiguration(VimTestOption(OptionConstants.clipboardName, OptionValueType.STRING, "unnamed"))
fun `test to file end with new line highlighter`() {
val before = """
The quick
brown ${c}fox
""".trimIndent()
configureByText(before)
typeText(
injector.parser.parseKeys(
buildString {
append("v\$")
append("X")
}
)
)
assertHighlighter(16, 20, HighlighterTargetArea.EXACT_RANGE)
// Exit vim-exchange
exitExchange()
}
private fun exitExchange() {
typeText(injector.parser.parseKeys("cxc"))
}
private fun assertHighlighter(start: Int, end: Int, area: HighlighterTargetArea) {
val currentExchange = myFixture.editor.getUserData(VimExchangeExtension.EXCHANGE_KEY)!!
val highlighter = currentExchange.getHighlighter()!!
assertEquals(start, highlighter.startOffset)
assertEquals(end, highlighter.endOffset)
assertEquals(area, highlighter.targetArea)
}
}
| mit | f5e346cf5ae1325402d2f37163426e2c | 27.442359 | 110 | 0.648412 | 4.305601 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.