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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
spinnaker/orca | orca-core/src/main/java/com/netflix/spinnaker/orca/pipeline/model/ConcourseTrigger.kt | 4 | 3565 | /*
* Copyright 2019 Pivotal, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.pipeline.model
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import com.netflix.spinnaker.kork.artifacts.model.Artifact
import com.netflix.spinnaker.kork.artifacts.model.ExpectedArtifact
import com.netflix.spinnaker.orca.api.pipeline.models.Trigger
data class ConcourseTrigger
@JvmOverloads constructor(
private val type: String = "artifactory",
private val correlationId: String? = null,
private val user: String? = "[anonymous]",
private val parameters: MutableMap<String, Any> = mutableMapOf(),
private val artifacts: MutableList<Artifact> = mutableListOf(),
private val notifications: MutableList<MutableMap<String, Any>> = mutableListOf(),
private var isRebake: Boolean = false,
private var isDryRun: Boolean = false,
private var isStrategy: Boolean = false
) : Trigger {
private var other: MutableMap<String, Any> = mutableMapOf()
private var resolvedExpectedArtifacts: MutableList<ExpectedArtifact> = mutableListOf()
var buildInfo: ConcourseBuildInfo? = null
var properties: Map<String, Any> = mutableMapOf()
override fun getType(): String = type
override fun getCorrelationId(): String? = correlationId
override fun getUser(): String? = user
override fun getParameters(): MutableMap<String, Any> = parameters
override fun getArtifacts(): MutableList<Artifact> = artifacts
override fun isRebake(): Boolean = isRebake
override fun setRebake(rebake: Boolean) {
isRebake = rebake
}
override fun isDryRun(): Boolean = isDryRun
override fun setDryRun(dryRun: Boolean) {
isDryRun = dryRun
}
override fun isStrategy(): Boolean = isStrategy
override fun setStrategy(strategy: Boolean) {
isStrategy = strategy
}
override fun setResolvedExpectedArtifacts(resolvedExpectedArtifacts: MutableList<ExpectedArtifact>) {
this.resolvedExpectedArtifacts = resolvedExpectedArtifacts
}
override fun getNotifications(): MutableList<MutableMap<String, Any>> = notifications
override fun getOther(): MutableMap<String, Any> = other
override fun getResolvedExpectedArtifacts(): MutableList<ExpectedArtifact> = resolvedExpectedArtifacts
override fun setOther(key: String, value: Any) {
this.other[key] = value
}
override fun setOther(other: MutableMap<String, Any>) {
this.other = other
}
}
class ConcourseBuildInfo
@JsonCreator
constructor(
@param:JsonProperty("name") override val name: String?,
@param:JsonProperty("number") override val number: Int,
@param:JsonProperty("url") override val url: String?,
@param:JsonProperty("result") override val result: String?,
@param:JsonProperty("artifacts") override val artifacts: List<JenkinsArtifact>?,
@param:JsonProperty("scm") override val scm: List<SourceControl>?,
@param:JsonProperty("building") override var building: Boolean = false
) :
BuildInfo<Any>(name, number, url, result, artifacts, scm, building)
| apache-2.0 | 781baa3dbbc16ba27ca38853e73bb389 | 34.65 | 104 | 0.756522 | 4.467419 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/diskmap/impl/DiskSkipListMap.kt | 1 | 9905 | package com.onyx.diskmap.impl
import com.onyx.diskmap.SortedDiskMap
import com.onyx.diskmap.impl.base.skiplist.AbstractIterableSkipList
import com.onyx.diskmap.data.Header
import com.onyx.diskmap.data.PutResult
import com.onyx.diskmap.data.SkipNode
import com.onyx.diskmap.store.Store
import com.onyx.exception.AttributeTypeMismatchException
import com.onyx.persistence.query.QueryCriteriaOperator
import com.onyx.extension.common.forceCompare
import com.onyx.extension.common.getAny
import com.onyx.lang.concurrent.ClosureReadWriteLock
import com.onyx.lang.concurrent.impl.DefaultClosureReadWriteLock
import java.lang.reflect.Field
import java.util.*
/**
* Created by Tim Osborn on 1/7/17.
*
*
* This class was added to enhance the existing index within Onyx Database. The bitmap was very efficient but, it was a hog
* as far as how much space it took over. As far as in-memory data structures, this will be the go-to algorithm. The
* data structure is based on a SkipList.
*
* @param <K> Key Object Type
* @param <V> Value Object Type
* @since 1.2.0
*/
open class DiskSkipListMap<K, V>(fileStore:Store, header: Header, keyType:Class<*>) : AbstractIterableSkipList<K, V>(fileStore, header, keyType), SortedDiskMap<K,V> {
override val size: Int
get() = longSize().toInt()
private var mapReadWriteLock: ClosureReadWriteLock = DefaultClosureReadWriteLock()
/**
* Remove an item within the map
*
* @param key Key Identifier
* @return The value that was removed
*/
override fun remove(key: K): V? = mapReadWriteLock.writeLock { super.remove(key) }
/**
* Put a value into a map based on its key.
*
* @param key Key identifier of the value
* @param value Underlying value
* @return The value of the object that was just put into the map
*/
override fun put(key: K, value: V): V = mapReadWriteLock.writeLock { super.put(key, value) }
/**
* Put key value. This is the same as map.put(K,V) except
* rather than the value you just put into the map, it will
* return the record id. The purpose of this is so you
* do not have to fetch the record id and search the skip list
* again after inserting the record.
*
* @param key Primary Key
* @param value Value to insert or update
* @since 2.1.3
* @return Value for previous record ID and if the value is been updated or inserted
*/
override fun putAndGet(key: K, value: V, preUpdate:((Long) -> Unit)?): PutResult = mapReadWriteLock.writeLock { super.internalPutAndGet(key, value, preUpdate) }
/**
* Iterates through the entire skip list to see if it contains the value you are looking for.
*
*
* Note, this is not efficient. It will basically do a bubble search.
*
* @param value Value you are looking for
* @return Whether the value was found
*/
override fun containsValue(value: V): Boolean = mapReadWriteLock.readLock{
values.forEach { next ->
if (next == value)
return@readLock true
}
return@readLock false
}
/**
* Put all the elements from the map into the skip list map
*
* @param from Map to convert from
*/
override fun putAll(from: Map<out K, V>) = from.forEach { this[it.key] = it.value }
/**
* Clear all the elements of the array. If it is not detached we must handle
* the head of teh data structure
*
* @since 1.2.0
*/
override fun clear() = mapReadWriteLock.writeLock {
super.clear()
head = SkipNode.create(fileStore)
this.reference.firstNode = head!!.position
updateHeaderFirstNode(reference, this.reference.firstNode)
reference.recordCount.set(0L)
updateHeaderRecordCount(0L)
}
/**
* Get the record id of a corresponding data. Note, this points to the SkipListNode position. Not the actual
* record position.
*
* @param key Identifier
* @return The position of the record reference if it exists. Otherwise -1
* @since 1.2.0
*/
override fun getRecID(key: K): Long = mapReadWriteLock.readLock { find(key)?.position ?: -1 }
/**
* Hydrate a record with its record ID. If the record value exists it will be returned
*
* @param recordId Position to find the record reference
* @return The value within the map
* @since 1.2.0
*/
override fun getWithRecID(recordId: Long): V? {
if (recordId <= 0)
return null
val node:SkipNode = findNodeAtPosition(recordId) ?: return null
return node.getRecord<V>(fileStore)
}
/**
* Get Map representation of key object
*
* @param recordId Record reference within storage structure
* @return Map of key values
* @since 1.2.0
*/
override fun getMapWithRecID(recordId: Long): Map<String, Any?>? = mapReadWriteLock.readLock{
val node:SkipNode = findNodeAtPosition(recordId) ?: return@readLock null
return@readLock getRecordValueAsDictionary(node.record)
}
/**
* Get Map representation of key object. If it is in the cache, use reflection to get it from the cache. Otherwise,
* just hydrate the value within the store
*
* @param attribute Attribute name to fetch
* @param reference Record reference within storage structure
* @return Map of key values
* @since 1.2.0
* @since 1.3.0 Optimized to require the reflection field so it does not have to re-instantiate one.
*/
@Throws(AttributeTypeMismatchException::class)
override fun <T : Any?> getAttributeWithRecID(attribute: Field, reference: Long): T = mapReadWriteLock.readLock {
@Suppress("UNCHECKED_CAST")
val node:SkipNode = findNodeAtPosition(reference) ?: return@readLock null as T
return@readLock node.getRecord<Any>(fileStore).getAny(attribute)
}
@Throws(AttributeTypeMismatchException::class)
override fun <T : Any?> getAttributeWithRecID(field: Field, reference: SkipNode): T = reference.getRecord<Any>(fileStore).getAny(field)
/**
* Find all references above and perhaps equal to the key you are sending in. The underlying data structure
* is sorted so this should be very efficient
*
* @param index The index value to compare. This must be comparable. It does not work with hash codes.
* @param includeFirst Whether above and equals to
* @return A Set of references
* @since 1.2.0
*/
override fun above(index: K, includeFirst: Boolean): Set<Long> {
val results = HashSet<Long>()
var node:SkipNode? = nearest(index)
if(node != null && !node.isRecord && node.right> 0)
node = findNodeAtPosition(node.right)
while(node != null && node.isRecord) {
val nodeKey:K = node.getKey(fileStore, storeKeyWithinNode, keyType)
when {
index.forceCompare(nodeKey) && includeFirst -> results.add(node.position)
index.forceCompare(nodeKey, QueryCriteriaOperator.GREATER_THAN) -> results.add(node.position)
}
node = if (node.right > 0) findNodeAtPosition(node.right) else null
}
return results
}
/**
* Find all references below and perhaps equal to the key you are sending in. The underlying data structure
* is sorted so this should be very efficient
*
* @param index The index value to compare. This must be comparable. It does not work with hash codes.
* @param includeFirst Whether above and equals to
* @return A Set of references
* @since 1.2.0
*/
override fun below(index: K, includeFirst: Boolean): Set<Long> {
val results = HashSet<Long>()
var node:SkipNode? = nearest(index)
if(node != null && !node.isRecord && node.right> 0)
node = findNodeAtPosition(node.right)
while(node != null && node.isRecord) {
val nodeKey:K = node.getKey(fileStore, storeKeyWithinNode, keyType)
when {
index.forceCompare(nodeKey) && includeFirst -> results.add(node.position)
index.forceCompare(nodeKey, QueryCriteriaOperator.LESS_THAN) -> results.add(node.position)
}
node = if (node.left > 0) findNodeAtPosition(node.left) else null
}
return results
}
/**
* Find all references between from and to value. The underlying data structure
* is sorted so this should be very efficient
*
* @param fromValue The key to compare. This must be comparable. It is only sorted by comparable values
* @param includeFrom Whether to compare above and equal or not.
* @param toValue Key to end range to
* @param includeTo Whether to compare equal or not.
*
* @since 2.1.3
*/
override fun between(fromValue: K?, includeFrom: Boolean, toValue: K?, includeTo: Boolean): Set<Long> {
val results = HashSet<Long>()
var node:SkipNode? = nearest(fromValue!!)
if(node != null && !node.isRecord && node.right> 0)
node = findNodeAtPosition(node.right)
node@while(node != null && node.isRecord) {
val nodeKey:K = node.getKey(fileStore, storeKeyWithinNode, keyType)
when {
toValue.forceCompare(nodeKey) && includeTo -> results.add(node.position)
!toValue.forceCompare(nodeKey, QueryCriteriaOperator.LESS_THAN) -> break@node
fromValue.forceCompare(nodeKey) && includeFrom -> results.add(node.position)
fromValue.forceCompare(nodeKey, QueryCriteriaOperator.GREATER_THAN) -> results.add(node.position)
}
node = if (node.right > 0) findNodeAtPosition(node.right) else null
}
return results
}
}
| agpl-3.0 | 056e87db700e4f644e36421065937640 | 38.150198 | 166 | 0.654619 | 4.125364 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/PluginLayout.kt | 2 | 18073 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "BlockingMethodInNonBlockingContext", "ReplacePutWithAssignment", "ReplaceNegatedIsEmptyWithIsNotEmpty")
package org.jetbrains.intellij.build.impl
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.plus
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.intellij.build.BuildContext
import org.jetbrains.intellij.build.JvmArchitecture
import org.jetbrains.intellij.build.OsFamily
import org.jetbrains.intellij.build.PluginBundlingRestrictions
import org.jetbrains.intellij.build.io.copyDir
import org.jetbrains.intellij.build.io.copyFileToDir
import java.nio.file.FileSystemException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
import java.util.function.BiConsumer
import java.util.function.BiPredicate
import java.util.function.Consumer
import java.util.function.UnaryOperator
typealias ResourceGenerator = suspend (Path, BuildContext) -> Unit
/**
* Describes layout of a plugin in the product distribution
*/
class PluginLayout private constructor(
val mainModule: String,
mainJarNameWithoutExtension: String,
) : BaseLayout() {
constructor(mainModule: String) : this(
mainModule,
convertModuleNameToFileName(mainModule),
)
private var mainJarName = "$mainJarNameWithoutExtension.jar"
var directoryName: String = mainJarNameWithoutExtension
private set
var versionEvaluator: VersionEvaluator = object : VersionEvaluator {
override fun evaluate(pluginXml: Path, ideBuildVersion: String, context: BuildContext) = ideBuildVersion
}
var pluginXmlPatcher: (String, BuildContext) -> String = { s, _ -> s }
var directoryNameSetExplicitly: Boolean = false
var bundlingRestrictions: PluginBundlingRestrictions = PluginBundlingRestrictions.NONE
internal set
var pathsToScramble: PersistentList<String> = persistentListOf()
val scrambleClasspathPlugins: MutableList<Pair<String /*plugin name*/, String /*relative path*/>> = mutableListOf()
var scrambleClasspathFilter: BiPredicate<BuildContext, Path> = BiPredicate { _, _ -> true }
/**
* See {@link org.jetbrains.intellij.build.impl.PluginLayout.PluginLayoutSpec#zkmScriptStub}
*/
var zkmScriptStub: String? = null
var pluginCompatibilityExactVersion = false
var retainProductDescriptorForBundledPlugin = false
var enableSymlinksAndExecutableResources = false
internal var resourceGenerators: PersistentList<ResourceGenerator> = persistentListOf()
private set
internal var patchers: PersistentList<suspend (ModuleOutputPatcher, BuildContext) -> Unit> = persistentListOf()
fun getMainJarName() = mainJarName
companion object {
/**
* Creates the plugin layout description. The default plugin layout is composed of a jar with name {@code mainModuleName}.jar containing
* production output of {@code mainModuleName} module, and the module libraries of {@code mainModuleName} with scopes 'Compile' and 'Runtime'
* placed under 'lib' directory in a directory with name {@code mainModuleName}.
* If you need to include additional resources or modules into the plugin layout specify them in
* {@code body} parameter. If you don't need to change the default layout there is no need to call this method at all, it's enough to
* specify the plugin module in [org.jetbrains.intellij.build.ProductModulesLayout.bundledPluginModules],
* [org.jetbrains.intellij.build.ProductModulesLayout.bundledPluginModules],
* [org.jetbrains.intellij.build.ProductModulesLayout.pluginModulesToPublish] list.
*
* <p>Note that project-level libraries on which the plugin modules depend, are automatically put to 'IDE_HOME/lib' directory for all IDEs
* which are compatible with the plugin. If this isn't desired (e.g. a library is used in a single plugin only, or if plugins where
* a library is used aren't bundled with IDEs, so we don't want to increase size of the distribution, you may invoke {@link PluginLayoutSpec#withProjectLibrary}
* to include such a library to the plugin distribution.</p>
* @param mainModuleName name of the module containing META-INF/plugin.xml file of the plugin
*/
@JvmStatic
fun plugin(
mainModuleName: String,
body: Consumer<PluginLayoutSpec>,
): PluginLayout {
val layout = PluginLayout(mainModuleName)
val spec = PluginLayoutSpec(layout)
body.accept(spec)
layout.mainJarName = spec.mainJarName
layout.directoryName = spec.directoryName
layout.directoryNameSetExplicitly = spec.directoryNameSetExplicitly
layout.bundlingRestrictions = spec.bundlingRestrictions.build()
layout.withModule(mainModuleName)
return layout
}
@JvmStatic
@JvmOverloads
fun plugin(
moduleNames: List<String>,
body: Consumer<SimplePluginLayoutSpec>? = null,
): PluginLayout {
val layout = PluginLayout(mainModule = moduleNames.first())
moduleNames.forEach(layout::withModule)
body?.accept(SimplePluginLayoutSpec(layout))
return layout
}
@JvmStatic
fun simplePlugin(mainModule: String): PluginLayout = plugin(listOf(mainModule))
}
override fun toString() = "Plugin '$mainModule'" + if (bundlingRestrictions != PluginBundlingRestrictions.NONE) ", restrictions: $bundlingRestrictions" else ""
override fun withModule(moduleName: String) {
if (moduleName.endsWith(".jps") || moduleName.endsWith(".rt")) {
// must be in a separate JAR
super.withModule(moduleName)
}
else {
withModule(moduleName, mainJarName)
}
}
sealed class PluginLayoutBuilder(@JvmField protected val layout: PluginLayout) : BaseLayoutSpec(layout) {
/**
* @param resourcePath path to resource file or directory relative to the plugin's main module content root
* @param relativeOutputPath target path relative to the plugin root directory
*/
fun withResource(resourcePath: String, relativeOutputPath: String) {
layout.withResourceFromModule(layout.mainModule, resourcePath, relativeOutputPath)
}
fun withGeneratedResources(generator: BiConsumer<Path, BuildContext>) {
layout.resourceGenerators += { path, context ->
generator.accept(path, context)
}
}
fun withGeneratedResources(generator: ResourceGenerator) {
layout.resourceGenerators += generator
}
/**
* @param resourcePath path to resource file or directory relative to {@code moduleName} module content root
* @param relativeOutputPath target path relative to the plugin root directory
*/
fun withResourceFromModule(moduleName: String, resourcePath: String, relativeOutputPath: String) {
layout.withResourceFromModule(moduleName, resourcePath, relativeOutputPath)
}
fun withPatch(patcher: BiConsumer<ModuleOutputPatcher, BuildContext>) {
layout.patchers = layout.patchers.add(patcher::accept)
}
}
@ApiStatus.Experimental
class SimplePluginLayoutSpec(layout: PluginLayout) : PluginLayoutBuilder(layout)
// as a builder for PluginLayout, that ideally should be immutable
class PluginLayoutSpec(layout: PluginLayout) : PluginLayoutBuilder(layout) {
var directoryName: String = convertModuleNameToFileName(layout.mainModule)
/**
* Custom name of the directory (under 'plugins' directory) where the plugin should be placed. By default, the main module name is used
* (with stripped {@code intellij} prefix and dots replaced by dashes).
* <strong>Don't set this property for new plugins</strong>; it is temporary added to keep layout of old plugins unchanged.
*/
set(value) {
field = value
directoryNameSetExplicitly = true
}
var directoryNameSetExplicitly: Boolean = false
private set
val mainModule
get() = layout.mainModule
/**
* Returns {@link PluginBundlingRestrictions} instance which can be used to exclude the plugin from some distributions.
*/
val bundlingRestrictions: PluginBundlingRestrictionBuilder = PluginBundlingRestrictionBuilder()
class PluginBundlingRestrictionBuilder {
/**
* Change this value if the plugin works in some OS only and therefore don't need to be bundled with distributions for other OS.
*/
var supportedOs: PersistentList<OsFamily> = OsFamily.ALL
/**
* Change this value if the plugin works on some architectures only and
* therefore don't need to be bundled with distributions for other architectures.
*/
var supportedArch: List<JvmArchitecture> = JvmArchitecture.ALL
/**
* Set to {@code true} if the plugin should be included in distribution for EAP builds only.
*/
var includeInEapOnly: Boolean = false
var ephemeral: Boolean = false
internal fun build(): PluginBundlingRestrictions {
if (ephemeral) {
check(supportedOs == OsFamily.ALL)
check(supportedArch == JvmArchitecture.ALL)
check(!includeInEapOnly)
return PluginBundlingRestrictions.EPHEMERAL
}
return PluginBundlingRestrictions(supportedOs, supportedArch, includeInEapOnly)
}
}
var mainJarName: String
get() = layout.mainJarName
/**
* Custom name of the main plugin JAR file. By default, the main module name with 'jar' extension is used (with stripped {@code intellij}
* prefix and dots replaced by dashes).
* <strong>Don't set this property for new plugins</strong>; it is temporary added to keep layout of old plugins unchanged.
*/
set(value) {
layout.mainJarName = value
}
/**
* @param binPathRelativeToCommunity path to resource file or directory relative to the intellij-community repo root
* @param outputPath target path relative to the plugin root directory
*/
@JvmOverloads
fun withBin(binPathRelativeToCommunity: String, outputPath: String, skipIfDoesntExist: Boolean = false) {
withGeneratedResources { targetDir, context ->
val source = context.paths.communityHomeDir.resolve(binPathRelativeToCommunity).normalize()
val attributes = try {
Files.readAttributes(source, BasicFileAttributes::class.java)
}
catch (ignored: FileSystemException) {
if (skipIfDoesntExist) {
return@withGeneratedResources
}
error("$source doesn't exist")
}
if (attributes.isRegularFile) {
copyFileToDir(source, targetDir.resolve(outputPath))
}
else {
copyDir(source, targetDir.resolve(outputPath))
}
}
}
/**
* @param resourcePath path to resource file or directory relative to the plugin's main module content root
* @param relativeOutputFile target path relative to the plugin root directory
*/
fun withResourceArchive(resourcePath: String, relativeOutputFile: String) {
withResourceArchiveFromModule(layout.mainModule, resourcePath, relativeOutputFile)
}
/**
* @param resourcePath path to resource file or directory relative to {@code moduleName} module content root
* @param relativeOutputFile target path relative to the plugin root directory
*/
fun withResourceArchiveFromModule(moduleName: String, resourcePath: String, relativeOutputFile: String) {
layout.resourcePaths = layout.resourcePaths.add(ModuleResourceData(moduleName = moduleName,
resourcePath = resourcePath,
relativeOutputPath = relativeOutputFile,
packToZip = true))
}
/**
* By default, version of a plugin is equal to the build number of the IDE it's built with. This method allows to specify custom version evaluator.
*/
fun withCustomVersion(versionEvaluator: VersionEvaluator) {
layout.versionEvaluator = versionEvaluator
}
fun withPluginXmlPatcher(pluginXmlPatcher: UnaryOperator<String>) {
layout.pluginXmlPatcher = { text, _ -> pluginXmlPatcher.apply(text) }
}
@Deprecated(message = "localizable resources are always put to the module JAR, so there is no need to call this method anymore")
fun doNotCreateSeparateJarForLocalizableResources() {
}
/**
* This plugin will be compatible only with exactly the same IDE version.
* See {@link org.jetbrains.intellij.build.CompatibleBuildRange#EXACT}
*/
fun pluginCompatibilityExactVersion() {
layout.pluginCompatibilityExactVersion = true
}
/**
* <product-description> is usually removed for bundled plugins.
* Call this method to retain it in plugin.xml
*/
fun retainProductDescriptorForBundledPlugin() {
layout.retainProductDescriptorForBundledPlugin = true
}
/**
* Do not automatically include module libraries from {@code moduleNames}
* <strong>Do not use this for new plugins, this method is temporary added to keep layout of old plugins</strong>.
*/
fun doNotCopyModuleLibrariesAutomatically(moduleNames: List<String>) {
layout.modulesWithExcludedModuleLibraries.addAll(moduleNames)
}
/**
* Specifies a relative path to a plugin jar that should be scrambled.
* Scrambling is performed by the {@link org.jetbrains.intellij.build.ProprietaryBuildTools#scrambleTool}
* If scramble tool is not defined, scrambling will not be performed
* Multiple invocations of this method will add corresponding paths to a list of paths to be scrambled
*
* @param relativePath - a path to a jar file relative to plugin root directory
*/
fun scramble(relativePath: String) {
layout.pathsToScramble = layout.pathsToScramble.add(relativePath)
}
/**
* Specifies a relative to {@link org.jetbrains.intellij.build.BuildPaths#communityHome} path to a zkm script stub file.
* If scramble tool is not defined, scramble toot will expect to find the script stub file at "{@link org.jetbrains.intellij.build.BuildPaths#projectHome}/plugins/{@code pluginName}/build/script.zkm.stub".
* Project home cannot be used since it is not constant (for example for Rider).
*
* @param communityRelativePath - a path to a jar file relative to community project home directory
*/
fun zkmScriptStub(communityRelativePath: String) {
layout.zkmScriptStub = communityRelativePath
}
/**
* Specifies a dependent plugin name to be added to scrambled classpath
* Scrambling is performed by the {@link org.jetbrains.intellij.build.ProprietaryBuildTools#scrambleTool}
* If scramble tool is not defined, scrambling will not be performed
* Multiple invocations of this method will add corresponding plugin names to a list of name to be added to scramble classpath
*
* @param pluginName - a name of dependent plugin, whose jars should be added to scramble classpath
* @param relativePath - a directory where jars should be searched (relative to plugin home directory, "lib" by default)
*/
@JvmOverloads
fun scrambleClasspathPlugin(pluginName: String, relativePath: String = "lib") {
layout.scrambleClasspathPlugins.add(Pair(pluginName, relativePath))
}
/**
* Allows control over classpath entries that will be used by the scrambler to resolve references from jars being scrambled.
* By default, all platform jars are added to the 'scramble classpath'
*/
fun filterScrambleClasspath(filter: BiPredicate<BuildContext, Path>) {
layout.scrambleClasspathFilter = filter
}
/**
* Concatenates `META-INF/services` files with the same name from different modules together.
* By default, the first service file silently wins.
*/
fun mergeServiceFiles() {
withPatch { patcher, context ->
val discoveredServiceFiles = LinkedHashMap<String, LinkedHashSet<Pair<String, Path>>>()
for (moduleName in layout.jarToModules.get(layout.mainJarName)!!) {
val path = context.findFileInModuleSources(moduleName, "META-INF/services") ?: continue
Files.list(path).use { stream ->
stream
.filter { Files.isRegularFile(it) }
.forEach { serviceFile ->
discoveredServiceFiles.computeIfAbsent(serviceFile.fileName.toString()) { LinkedHashSet() }
.add(Pair(moduleName, serviceFile))
}
}
}
for ((serviceFileName, serviceFiles) in discoveredServiceFiles) {
if (serviceFiles.size <= 1) {
continue
}
val content = serviceFiles.joinToString(separator = "\n") { Files.readString(it.second) }
Span.current().addEvent("merge service file)", Attributes.of(
AttributeKey.stringKey("serviceFile"), serviceFileName,
AttributeKey.stringArrayKey("serviceFiles"), serviceFiles.map { it.first },
))
patcher.patchModuleOutput(moduleName = serviceFiles.first().first, // first one wins
path = "META-INF/services/$serviceFileName",
content = content)
}
}
}
/**
* Enables support for symlinks and files with posix executable bit set, such as required by macOS.
*/
fun enableSymlinksAndExecutableResources() {
layout.enableSymlinksAndExecutableResources = true
}
}
interface VersionEvaluator {
fun evaluate(pluginXml: Path, ideBuildVersion: String, context: BuildContext): String
}
} | apache-2.0 | dd9802bdc4fb98c68059cbcdd2effee6 | 42.136038 | 209 | 0.70846 | 5.162239 | false | false | false | false |
santaevpavel/ClipboardTranslator | domain/src/main/java/com/example/santaev/domain/factory/UseCaseFactory.kt | 1 | 1376 | package com.example.santaev.domain.factory
import com.example.santaev.domain.dto.LanguageDto
import com.example.santaev.domain.usecase.*
class UseCaseFactory(
private val repositoryFactory: RepositoryFactory,
private val gatewayFactory: IGatewayFactory
) {
fun getTranslateFactory(
sourceLanguage: LanguageDto,
targetLanguage: LanguageDto,
text: String
): TranslateUseCase {
return TranslateUseCase(
sourceLanguage = sourceLanguage,
targetLanguage = targetLanguage,
text = text,
apiService = gatewayFactory.getApiService(),
translationRepository = repositoryFactory.getTranslationRepository()
)
}
fun getGetHistoryUseCase() = GetHistoryUseCase(repositoryFactory.getTranslationRepository())
fun getGetLanguagesUseCase() = GetLanguagesUseCase(repositoryFactory.getLanguageRepository())
fun getDeleteHistoryUseCase() = DeleteHistoryUseCase(repositoryFactory.getTranslationRepository())
fun getRequestLanguagesUseCase() = RequestLanguagesUseCase(repositoryFactory.getLanguageRepository())
companion object {
val instance by lazy {
UseCaseFactory(
RepositoryFactory.instance,
IGatewayFactory.instance
)
}
}
} | apache-2.0 | 51dd0201e646755044f433c879b661f8 | 31.785714 | 105 | 0.679506 | 5.616327 | false | false | false | false |
rlac/tealeaf | library/src/androidTest/kotlin/au/id/rlac/tealeaf/properties/BundleVarDelegateTests.kt | 1 | 1856 | package au.id.rlac.tealeaf.properties
import android.os.Bundle
import android.support.test.runner.AndroidJUnit4
import org.junit.runner.RunWith
import org.junit.Test
import org.assertj.core.api.Assertions.assertThat
import org.assertj.android.api.Assertions.assertThat
import org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown
RunWith(javaClass<AndroidJUnit4>())
public class BundleVarDelegateTests {
/**
* Test that bundle values can be set using bundleVar and are keyed by variable name.
*/
Test
public fun testVariableWritable() {
class Test(b: Bundle) {
var short: Short by BundleDelegates.bundleVar(b)
var int: Int by BundleDelegates.bundleVar(b)
var long: Long by BundleDelegates.bundleVar(b)
var float: Float by BundleDelegates.bundleVar(b)
var string: String by BundleDelegates.bundleVar(b)
var bool: Boolean by BundleDelegates.bundleVar(b)
var byte: Byte by BundleDelegates.bundleVar(b)
var char: Char by BundleDelegates.bundleVar(b)
}
val b = Bundle()
val v = Test(b)
v.int = 5
v.short = 1
v.long = 1000L
v.float = 5.5F
v.string = "String"
v.bool = true
v.byte = 1
v.char = 'c'
assertThat(b)
.hasSize(8)
.hasKey("short")
.hasKey("int")
.hasKey("long")
.hasKey("float")
.hasKey("string")
.hasKey("bool")
.hasKey("byte")
.hasKey("char")
assertThat(b.getShort("short")).isEqualTo(1)
assertThat(b.getInt("int")).isEqualTo(5)
assertThat(b.getLong("long")).isEqualTo(1000L)
assertThat(b.getFloat("float")).isEqualTo(5.5F)
assertThat(b.getString("string")).isEqualTo("String")
assertThat(b.getBoolean("bool")).isTrue()
assertThat(b.getByte("byte")).isEqualTo(1.toByte())
assertThat(b.getChar("char")).isEqualTo('c')
}
} | apache-2.0 | f7588a3fb2e900ba059f389b9f427fb6 | 28.47619 | 87 | 0.670259 | 3.689861 | false | true | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/Generic/TVec2.kt | 1 | 12362 | package glm
data class TVec2<T>(val x: T, val y: T) {
// Initializes each element by evaluating init from 0 until 1
constructor(init: (Int) -> T) : this(init(0), init(1))
operator fun get(idx: Int): T = when (idx) {
0 -> x
1 -> y
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
inline fun map(func: (T) -> T): TVec2<T> = TVec2(func(x), func(y))
fun toList(): List<T> = listOf(x, y)
// Predefined vector constants
companion object Constants {
}
// Conversions to Float
inline fun toVec(conv: (T) -> Float): Vec2 = Vec2(conv(x), conv(y))
inline fun toVec2(conv: (T) -> Float): Vec2 = Vec2(conv(x), conv(y))
inline fun toVec3(z: Float = 0f, conv: (T) -> Float): Vec3 = Vec3(conv(x), conv(y), z)
inline fun toVec4(z: Float = 0f, w: Float = 0f, conv: (T) -> Float): Vec4 = Vec4(conv(x), conv(y), z, w)
// Conversions to Float
inline fun toMutableVec(conv: (T) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
inline fun toMutableVec2(conv: (T) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
inline fun toMutableVec3(z: Float = 0f, conv: (T) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), z)
inline fun toMutableVec4(z: Float = 0f, w: Float = 0f, conv: (T) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), z, w)
// Conversions to Double
inline fun toDoubleVec(conv: (T) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
inline fun toDoubleVec2(conv: (T) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
inline fun toDoubleVec3(z: Double = 0.0, conv: (T) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), z)
inline fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (T) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), z, w)
// Conversions to Double
inline fun toMutableDoubleVec(conv: (T) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
inline fun toMutableDoubleVec2(conv: (T) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
inline fun toMutableDoubleVec3(z: Double = 0.0, conv: (T) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), z)
inline fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (T) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), z, w)
// Conversions to Int
inline fun toIntVec(conv: (T) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
inline fun toIntVec2(conv: (T) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
inline fun toIntVec3(z: Int = 0, conv: (T) -> Int): IntVec3 = IntVec3(conv(x), conv(y), z)
inline fun toIntVec4(z: Int = 0, w: Int = 0, conv: (T) -> Int): IntVec4 = IntVec4(conv(x), conv(y), z, w)
// Conversions to Int
inline fun toMutableIntVec(conv: (T) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
inline fun toMutableIntVec2(conv: (T) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
inline fun toMutableIntVec3(z: Int = 0, conv: (T) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), z)
inline fun toMutableIntVec4(z: Int = 0, w: Int = 0, conv: (T) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), z, w)
// Conversions to Long
inline fun toLongVec(conv: (T) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
inline fun toLongVec2(conv: (T) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
inline fun toLongVec3(z: Long = 0L, conv: (T) -> Long): LongVec3 = LongVec3(conv(x), conv(y), z)
inline fun toLongVec4(z: Long = 0L, w: Long = 0L, conv: (T) -> Long): LongVec4 = LongVec4(conv(x), conv(y), z, w)
// Conversions to Long
inline fun toMutableLongVec(conv: (T) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
inline fun toMutableLongVec2(conv: (T) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
inline fun toMutableLongVec3(z: Long = 0L, conv: (T) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), z)
inline fun toMutableLongVec4(z: Long = 0L, w: Long = 0L, conv: (T) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), z, w)
// Conversions to Short
inline fun toShortVec(conv: (T) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
inline fun toShortVec2(conv: (T) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
inline fun toShortVec3(z: Short = 0.toShort(), conv: (T) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), z)
inline fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (T) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), z, w)
// Conversions to Short
inline fun toMutableShortVec(conv: (T) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
inline fun toMutableShortVec2(conv: (T) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
inline fun toMutableShortVec3(z: Short = 0.toShort(), conv: (T) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), z)
inline fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (T) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), z, w)
// Conversions to Byte
inline fun toByteVec(conv: (T) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
inline fun toByteVec2(conv: (T) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
inline fun toByteVec3(z: Byte = 0.toByte(), conv: (T) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), z)
inline fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (T) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), z, w)
// Conversions to Byte
inline fun toMutableByteVec(conv: (T) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
inline fun toMutableByteVec2(conv: (T) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
inline fun toMutableByteVec3(z: Byte = 0.toByte(), conv: (T) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), z)
inline fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (T) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), z, w)
// Conversions to Char
inline fun toCharVec(conv: (T) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
inline fun toCharVec2(conv: (T) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
inline fun toCharVec3(z: Char, conv: (T) -> Char): CharVec3 = CharVec3(conv(x), conv(y), z)
inline fun toCharVec4(z: Char, w: Char, conv: (T) -> Char): CharVec4 = CharVec4(conv(x), conv(y), z, w)
// Conversions to Char
inline fun toMutableCharVec(conv: (T) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
inline fun toMutableCharVec2(conv: (T) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
inline fun toMutableCharVec3(z: Char, conv: (T) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), z)
inline fun toMutableCharVec4(z: Char, w: Char, conv: (T) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), z, w)
// Conversions to Boolean
inline fun toBoolVec(conv: (T) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
inline fun toBoolVec2(conv: (T) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
inline fun toBoolVec3(z: Boolean = false, conv: (T) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), z)
inline fun toBoolVec4(z: Boolean = false, w: Boolean = false, conv: (T) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), z, w)
// Conversions to Boolean
inline fun toMutableBoolVec(conv: (T) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
inline fun toMutableBoolVec2(conv: (T) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
inline fun toMutableBoolVec3(z: Boolean = false, conv: (T) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), z)
inline fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false, conv: (T) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), z, w)
// Conversions to String
fun toStringVec(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec(conv: (T) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (T) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(z: String = ""): StringVec3 = StringVec3(x.toString(), y.toString(), z)
inline fun toStringVec3(z: String = "", conv: (T) -> String): StringVec3 = StringVec3(conv(x), conv(y), z)
fun toStringVec4(z: String = "", w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z, w)
inline fun toStringVec4(z: String = "", w: String = "", conv: (T) -> String): StringVec4 = StringVec4(conv(x), conv(y), z, w)
// Conversions to String
fun toMutableStringVec(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec(conv: (T) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (T) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(z: String = ""): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z)
inline fun toMutableStringVec3(z: String = "", conv: (T) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), z)
fun toMutableStringVec4(z: String = "", w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z, w)
inline fun toMutableStringVec4(z: String = "", w: String = "", conv: (T) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), z, w)
// Conversions to T2
inline fun <T2> toTVec(conv: (T) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec2(conv: (T) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(z: T2, conv: (T) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), z)
inline fun <T2> toTVec4(z: T2, w: T2, conv: (T) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), z, w)
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (T) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec2(conv: (T) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(z: T2, conv: (T) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), z)
inline fun <T2> toMutableTVec4(z: T2, w: T2, conv: (T) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), z, w)
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: TVec2<T> get() = TVec2(x, x)
val xy: TVec2<T> get() = TVec2(x, y)
val yx: TVec2<T> get() = TVec2(y, x)
val yy: TVec2<T> get() = TVec2(y, y)
val xxx: TVec3<T> get() = TVec3(x, x, x)
val xxy: TVec3<T> get() = TVec3(x, x, y)
val xyx: TVec3<T> get() = TVec3(x, y, x)
val xyy: TVec3<T> get() = TVec3(x, y, y)
val yxx: TVec3<T> get() = TVec3(y, x, x)
val yxy: TVec3<T> get() = TVec3(y, x, y)
val yyx: TVec3<T> get() = TVec3(y, y, x)
val yyy: TVec3<T> get() = TVec3(y, y, y)
val xxxx: TVec4<T> get() = TVec4(x, x, x, x)
val xxxy: TVec4<T> get() = TVec4(x, x, x, y)
val xxyx: TVec4<T> get() = TVec4(x, x, y, x)
val xxyy: TVec4<T> get() = TVec4(x, x, y, y)
val xyxx: TVec4<T> get() = TVec4(x, y, x, x)
val xyxy: TVec4<T> get() = TVec4(x, y, x, y)
val xyyx: TVec4<T> get() = TVec4(x, y, y, x)
val xyyy: TVec4<T> get() = TVec4(x, y, y, y)
val yxxx: TVec4<T> get() = TVec4(y, x, x, x)
val yxxy: TVec4<T> get() = TVec4(y, x, x, y)
val yxyx: TVec4<T> get() = TVec4(y, x, y, x)
val yxyy: TVec4<T> get() = TVec4(y, x, y, y)
val yyxx: TVec4<T> get() = TVec4(y, y, x, x)
val yyxy: TVec4<T> get() = TVec4(y, y, x, y)
val yyyx: TVec4<T> get() = TVec4(y, y, y, x)
val yyyy: TVec4<T> get() = TVec4(y, y, y, y)
}
val swizzle: Swizzle get() = Swizzle()
}
fun <T> vecOf(x: T, y: T): TVec2<T> = TVec2(x, y)
| mit | b68f438cae48a2a99389d297da72c9d9 | 65.462366 | 162 | 0.624494 | 3.131999 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/i18n/lang/structure/I18nStructureViewElement.kt | 1 | 1572 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.i18n.lang.structure
import com.demonwav.mcdev.i18n.lang.I18nFile
import com.demonwav.mcdev.i18n.lang.gen.psi.I18nEntry
import com.demonwav.mcdev.util.mapToArray
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.util.treeView.smartTree.SortableTreeElement
import com.intellij.navigation.NavigationItem
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.util.PsiTreeUtil
class I18nStructureViewElement(private val element: PsiElement) : StructureViewTreeElement, SortableTreeElement {
override fun getValue() = element
override fun navigate(requestFocus: Boolean) {
if (element is NavigationItem) {
element.navigate(requestFocus)
}
}
override fun canNavigate() = element is NavigationItem && element.canNavigate()
override fun canNavigateToSource() = element is NavigationItem && element.canNavigateToSource()
override fun getAlphaSortKey() = (element as PsiNamedElement).name!!
override fun getPresentation() = (element as NavigationItem).presentation!!
override fun getChildren() =
when (element) {
is I18nFile -> {
val entries = PsiTreeUtil.getChildrenOfType(element, I18nEntry::class.java) ?: emptyArray()
entries.mapToArray(::I18nStructureViewElement)
}
else -> emptyArray()
}
}
| mit | a0c1e68c47aeceab18728fb2e1cb0aa2 | 31.75 | 113 | 0.724555 | 4.530259 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/glfw/src/templates/kotlin/glfw/GLFWTypes.kt | 2 | 29156 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package glfw
import org.lwjgl.generator.*
val GLFW_BINDING = simpleBinding(
Module.GLFW,
libraryExpression = """Configuration.GLFW_LIBRARY_NAME.get(Platform.mapLibraryNameBundled("glfw"))""",
bundledWithLWJGL = true
)
val GLFW_BINDING_DELEGATE = GLFW_BINDING.delegate("GLFW.getLibrary()")
val GLFWmonitor = "GLFWmonitor".opaque
val GLFWwindow = "GLFWwindow".opaque
val GLFWvidmode = struct(Module.GLFW, "GLFWVidMode", nativeName = "GLFWvidmode", mutable = false) {
documentation = "Describes a single video mode."
int("width", "the width, in screen coordinates, of the video mode")
int("height", "the height, in screen coordinates, of the video mode")
int("redBits", "the bit depth of the red channel of the video mode")
int("greenBits", "the bit depth of the green channel of the video mode")
int("blueBits", "the bit depth of the blue channel of the video mode")
int("refreshRate", "the refresh rate, in Hz, of the video mode")
}
val GLFWgammaramp = struct(Module.GLFW, "GLFWGammaRamp", nativeName = "GLFWgammaramp") {
documentation = "Describes the gamma ramp for a monitor."
since = "version 3.0"
unsigned_short.p("red", "an array of values describing the response of the red channel")
unsigned_short.p("green", "an array of values describing the response of the green channel")
unsigned_short.p("blue", "an array of values describing the response of the blue channel")
AutoSize("red", "green", "blue")..unsigned_int("size", "the number of elements in each array")
}
val GLFWcursor = "GLFWcursor".opaque
val GLFWimage = struct(Module.GLFW, "GLFWImage", nativeName = "GLFWimage") {
documentation =
"""
Image data.
This describes a single 2D image. See the documentation for each related function to see what the expected pixel format is.
"""
since = "version 2.1"
int("width", "the width, in pixels, of this image")
int("height", "the height, in pixels, of this image")
unsigned_char.p("pixels", "the pixel data of this image, arranged left-to-right, top-to-bottom")
}
val GLFWgamepadstate = struct(Module.GLFW, "GLFWGamepadState", nativeName = "GLFWgamepadstate") {
documentation = "Describes the input state of a gamepad."
since = "version 3.3"
unsigned_char("buttons", "the states of each gamepad button, #PRESS or #RELEASE")[15]
float("axes", "the states of each gamepad axis, in the range -1.0 to 1.0 inclusive")[6]
}
// callback functions
val GLFWallocatefun = Module.GLFW.callback {
void.p(
"GLFWAllocateCallback",
"Will be called for memory allocation requests.",
size_t("size", "the minimum size, in bytes, of the memory block"),
opaque_p("user", "the user-defined pointer from the allocator"),
returnDoc = "the address of the newly allocated memory block, or #NULL if an error occurred",
nativeType = "GLFWallocatefun"
) {
documentation =
"""
The function pointer type for memory allocation callbacks.
This is the function pointer type for memory allocation callbacks. A memory allocation callback function has the following signature:
${codeBlock("""
void* function_name(size_t size, void* user)""")}
This function must return either a memory block at least {@code size} bytes long, or #NULL if allocation failed. Note that not all parts of GLFW
handle allocation failures gracefully yet.
This function may be called during #Init() but before the library is flagged as initialized, as well as during #Terminate() after the library is no
longer flagged as initialized.
Any memory allocated by this function will be deallocated during library termination or earlier.
The size will always be greater than zero. Allocations of size zero are filtered out before reaching the custom allocator.
${note(ul(
"The returned memory block must be valid at least until it is deallocated.",
"This function should not call any GLFW function.",
"This function may be called from any thread that calls GLFW functions."
))}
"""
since = "version 3.4"
}
}
val GLFWreallocatefun = Module.GLFW.callback {
void.p(
"GLFWReallocateCallback",
"Will be called for memory reallocation requests.",
Unsafe..void.p("block", "the address of the memory block to reallocate"),
size_t("size", "the new minimum size, in bytes, of the memory block"),
opaque_p("user", "the user-defined pointer from the allocator"),
returnDoc = "the address of the newly allocated or resized memory block, or #NULL if an error occurred",
nativeType = "GLFWreallocatefun"
) {
documentation =
"""
The function pointer type for memory reallocation callbacks.
This is the function pointer type for memory reallocation callbacks. A memory reallocation callback function has the following signature:
${codeBlock("""
void* function_name(void* block, size_t size, void* user) """)}
This function must return a memory block at least {@code size} bytes long, or #NULL if allocation failed. Note that not all parts of GLFW handle
allocation failures gracefully yet.
This function may be called during #Init() but before the library is flagged as initialized, as well as during #Terminate() after the library is no
longer flagged as initialized.
Any memory allocated by this function will be deallocated during library termination or earlier.
The block address will never be #NULL and the size will always be greater than zero. Reallocations of a block to size zero are converted into
deallocations. Reallocations of #NULL to a non-zero size are converted into regular allocations.
${note(ul(
"The returned memory block must be valid at least until it is deallocated.",
"This function should not call any GLFW function.",
"This function may be called from any thread that calls GLFW functions."
))}
"""
since = "version 3.4"
}
}
val GLFWdeallocatefun = Module.GLFW.callback {
void(
"GLFWDeallocateCallback",
"Will be called for memory deallocation requests.",
Unsafe..void.p("block", "the address of the memory block to deallocate"),
opaque_p("user", "the user-defined pointer from the allocator"),
nativeType = "GLFWdeallocatefun"
) {
documentation =
"""
The function pointer type for memory deallocation callbacks.
This is the function pointer type for memory deallocation callbacks. A memory deallocation callback function has the following signature:
${codeBlock("""
void function_name(void* block, void* user)""")}
This function may deallocate the specified memory block. This memory block will have been allocated with the same allocator.
This function may be called during #Init() but before the library is flagged as initialized, as well as during #Terminate() after the library is no
longer flagged as initialized.
The block address will never be #NULL. Deallocations of #NULL are filtered out before reaching the custom allocator.
${note(ul(
"The specified memory block will not be accessed by GLFW after this function is called.",
"This function should not call any GLFW function.",
"This function may be called from any thread that calls GLFW functions."
))}
"""
since = "version 3.4"
}
}
val GLFWerrorfun = Module.GLFW.callback {
void(
"GLFWErrorCallback",
"Will be called with an error code and a human-readable description when a GLFW error occurs.",
int("error", "the error code"),
NullTerminated..charUTF8.p("description", "a pointer to a UTF-8 encoded string describing the error"),
nativeType = "GLFWerrorfun"
) {
documentation = "Instances of this interface may be passed to the #SetErrorCallback() method."
since = "version 3.0"
javaImport(
"java.io.PrintStream",
"java.util.Map",
"static org.lwjgl.glfw.GLFW.*"
)
additionalCode = """
/**
* Converts the specified {@code GLFWErrorCallback} argument to a String.
*
* <p>This method may only be used inside a GLFWErrorCallback invocation.</p>
*
* @param description pointer to the UTF-8 encoded description string
*
* @return the description as a String
*/
public static String getDescription(long description) {
return memUTF8(description);
}
/**
* Returns a {@code GLFWErrorCallback} instance that prints the error to the {@link APIUtil#DEBUG_STREAM}.
*
* @return the GLFWerrorCallback
*/
public static GLFWErrorCallback createPrint() {
return createPrint(APIUtil.DEBUG_STREAM);
}
/**
* Returns a {@code GLFWErrorCallback} instance that prints the error in the specified {@link PrintStream}.
*
* @param stream the PrintStream to use
*
* @return the GLFWerrorCallback
*/
public static GLFWErrorCallback createPrint(PrintStream stream) {
return new GLFWErrorCallback() {
private Map<Integer, String> ERROR_CODES = APIUtil.apiClassTokens((field, value) -> 0x10000 < value && value < 0x20000, null, GLFW.class);
@Override
public void invoke(int error, long description) {
String msg = getDescription(description);
stream.printf("[LWJGL] %s error\n", ERROR_CODES.get(error));
stream.println("\tDescription : " + msg);
stream.println("\tStacktrace :");
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
for ( int i = 4; i < stack.length; i++ ) {
stream.print("\t\t");
stream.println(stack[i].toString());
}
}
};
}
/**
* Returns a {@code GLFWErrorCallback} instance that throws an {@link IllegalStateException} when an error occurs.
*
* @return the GLFWerrorCallback
*/
public static GLFWErrorCallback createThrow() {
return new GLFWErrorCallback() {
@Override
public void invoke(int error, long description) {
throw new IllegalStateException(String.format("GLFW error [0x%X]: %s", error, getDescription(description)));
}
};
}
/** See {@link GLFW#glfwSetErrorCallback SetErrorCallback}. */
public GLFWErrorCallback set() {
glfwSetErrorCallback(this);
return this;
}
"""
}
}
val GLFWallocator = struct(Module.GLFW, "GLFWAllocator", nativeName = "GLFWallocator") {
documentation = "A custom memory allocator that can be set with #InitAllocator()."
since = "version 3.4"
GLFWallocatefun("allocate", "the memory allocation callback")
GLFWreallocatefun("reallocate", "the memory reallocation callback")
GLFWdeallocatefun("deallocate", "the memory deallocation callback")
nullable..opaque_p("user", "a user-defined pointer that will be passed to the callbacks")
}
val GLFWmonitorfun = Module.GLFW.callback {
void(
"GLFWMonitorCallback",
"Will be called when a monitor is connected to or disconnected from the system.",
GLFWmonitor.p("monitor", "the monitor that was connected or disconnected"),
int("event", "one of #CONNECTED or #DISCONNECTED. Remaining values reserved for future use."),
nativeType = "GLFWmonitorfun"
) {
documentation = "Instances of this interface may be passed to the #SetMonitorCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetMonitorCallback SetMonitorCallback}. */
public GLFWMonitorCallback set() {
glfwSetMonitorCallback(this);
return this;
}
"""
}
}
val GLFWjoystickfun = Module.GLFW.callback {
void(
"GLFWJoystickCallback",
"Will be called when a joystick is connected to or disconnected from the system.",
int("jid", "the joystick that was connected or disconnected"),
int("event", "one of #CONNECTED or #DISCONNECTED. Remaining values reserved for future use."),
nativeType = "GLFWjoystickfun"
) {
documentation = "Instances of this interface may be passed to the #SetJoystickCallback() method."
since = "version 3.2"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetJoystickCallback SetJoystickCallback}. */
public GLFWJoystickCallback set() {
glfwSetJoystickCallback(this);
return this;
}
"""
}
}
val GLFWwindowposfun = Module.GLFW.callback {
void(
"GLFWWindowPosCallback",
"Will be called when the specified window moves.",
GLFWwindow.p("window", "the window that was moved"),
int("xpos", "the new x-coordinate, in screen coordinates, of the upper-left corner of the content area of the window"),
int("ypos", "the new y-coordinate, in screen coordinates, of the upper-left corner of the content area of the window"),
nativeType = "GLFWwindowposfun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowPosCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowPosCallback SetWindowPosCallback}. */
public GLFWWindowPosCallback set(long window) {
glfwSetWindowPosCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowsizefun = Module.GLFW.callback {
void(
"GLFWWindowSizeCallback",
"Will be called when the specified window is resized.",
GLFWwindow.p("window", "the window that was resized"),
int("width", "the new width, in screen coordinates, of the window"),
int("height", "the new height, in screen coordinates, of the window"),
nativeType = "GLFWwindowsizefun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowSizeCallback() method."
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowSizeCallback SetWindowSizeCallback}. */
public GLFWWindowSizeCallback set(long window) {
glfwSetWindowSizeCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowclosefun = Module.GLFW.callback {
void(
"GLFWWindowCloseCallback",
"Will be called when the user attempts to close the specified window, for example by clicking the close widget in the title bar.",
GLFWwindow.p("window", "the window that the user attempted to close"),
nativeType = "GLFWwindowclosefun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowCloseCallback() method."
since = "version 2.5"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowCloseCallback SetWindowCloseCallback}. */
public GLFWWindowCloseCallback set(long window) {
glfwSetWindowCloseCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowrefreshfun = Module.GLFW.callback {
void(
"GLFWWindowRefreshCallback",
"""
Will be called when the client area of the specified window needs to be redrawn, for example if the window has been exposed after having been covered by
another window.
""",
GLFWwindow.p("window", "the window whose content needs to be refreshed"),
nativeType = "GLFWwindowrefreshfun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowRefreshCallback() method."
since = "version 2.5"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowRefreshCallback SetWindowRefreshCallback}. */
public GLFWWindowRefreshCallback set(long window) {
glfwSetWindowRefreshCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowfocusfun = Module.GLFW.callback {
void(
"GLFWWindowFocusCallback",
"Will be called when the specified window gains or loses focus.",
GLFWwindow.p("window", "the window that was focused or defocused"),
intb("focused", "#TRUE if the window was focused, or #FALSE if it was defocused"),
nativeType = "GLFWwindowfocusfun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowFocusCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowFocusCallback SetWindowFocusCallback}. */
public GLFWWindowFocusCallback set(long window) {
glfwSetWindowFocusCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowiconifyfun = Module.GLFW.callback {
void(
"GLFWWindowIconifyCallback",
"Will be called when the specified window is iconified or restored.",
GLFWwindow.p("window", "the window that was iconified or restored."),
intb("iconified", "#TRUE if the window was iconified, or #FALSE if it was restored"),
nativeType = "GLFWwindowiconifyfun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowIconifyCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowIconifyCallback SetWindowIconifyCallback}. */
public GLFWWindowIconifyCallback set(long window) {
glfwSetWindowIconifyCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowmaximizefun = Module.GLFW.callback {
void(
"GLFWWindowMaximizeCallback",
"Will be called when the specified window is maximized or restored.",
GLFWwindow.p("window", "the window that was maximized or restored."),
intb("maximized", "#TRUE if the window was maximized, or #FALSE if it was restored"),
nativeType = "GLFWwindowmaximizefun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowMaximizeCallback() method."
since = "version 3.3"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowMaximizeCallback SetWindowMaximizeCallback}. */
public GLFWWindowMaximizeCallback set(long window) {
glfwSetWindowMaximizeCallback(window, this);
return this;
}
"""
}
}
val GLFWframebuffersizefun = Module.GLFW.callback {
void(
"GLFWFramebufferSizeCallback",
"Will be called when the framebuffer of the specified window is resized.",
GLFWwindow.p("window", "the window whose framebuffer was resized"),
int("width", "the new width, in pixels, of the framebuffer"),
int("height", "the new height, in pixels, of the framebuffer"),
nativeType = "GLFWframebuffersizefun"
) {
documentation = "Instances of this interface may be passed to the #SetFramebufferSizeCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetFramebufferSizeCallback SetFramebufferSizeCallback}. */
public GLFWFramebufferSizeCallback set(long window) {
glfwSetFramebufferSizeCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowcontentscalefun = Module.GLFW.callback {
void(
"GLFWWindowContentScaleCallback",
"Will be called when the window content scale changes.",
GLFWwindow.p("window", "the window whose content scale changed"),
float("xscale", "the new x-axis content scale of the window"),
float("yscale", "the new y-axis content scale of the window"),
nativeType = "GLFWwindowcontentscalefun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowContentScaleCallback() method."
since = "version 3.3"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowContentScaleCallback SetWindowContentScaleCallback}. */
public GLFWWindowContentScaleCallback set(long window) {
glfwSetWindowContentScaleCallback(window, this);
return this;
}
"""
}
}
val GLFWkeyfun = Module.GLFW.callback {
void(
"GLFWKeyCallback",
"Will be called when a key is pressed, repeated or released.",
GLFWwindow.p("window", "the window that received the event"),
int("key", "the keyboard key that was pressed or released"),
int("scancode", "the platform-specific scancode of the key"),
int("action", "the key action", "#PRESS #RELEASE #REPEAT"),
int("mods", "bitfield describing which modifiers keys were held down"),
nativeType = "GLFWkeyfun"
) {
documentation = "Instances of this interface may be passed to the #SetKeyCallback() method."
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetKeyCallback SetKeyCallback}. */
public GLFWKeyCallback set(long window) {
glfwSetKeyCallback(window, this);
return this;
}
"""
}
}
val GLFWcharfun = Module.GLFW.callback {
void(
"GLFWCharCallback",
"Will be called when a Unicode character is input.",
GLFWwindow.p("window", "the window that received the event"),
unsigned_int("codepoint", "the Unicode code point of the character"),
nativeType = "GLFWcharfun"
) {
documentation = "Instances of this interface may be passed to the #SetCharCallback() method."
since = "version 2.4"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetCharCallback SetCharCallback}. */
public GLFWCharCallback set(long window) {
glfwSetCharCallback(window, this);
return this;
}
"""
}
}
val GLFWcharmodsfun = Module.GLFW.callback {
void(
"GLFWCharModsCallback",
"Will be called when a Unicode character is input regardless of what modifier keys are used.",
GLFWwindow.p("window", "the window that received the event"),
unsigned_int("codepoint", "the Unicode code point of the character"),
int("mods", "bitfield describing which modifier keys were held down"),
nativeType = "GLFWcharmodsfun"
) {
documentation =
"""
Instances of this interface may be passed to the #SetCharModsCallback() method.
Deprecared: scheduled for removal in version 4.0.
"""
since = "version 3.1"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetCharModsCallback SetCharModsCallback}. */
public GLFWCharModsCallback set(long window) {
glfwSetCharModsCallback(window, this);
return this;
}
"""
}
}
val GLFWmousebuttonfun = Module.GLFW.callback {
void(
"GLFWMouseButtonCallback",
"Will be called when a mouse button is pressed or released.",
GLFWwindow.p("window", "the window that received the event"),
int("button", "the mouse button that was pressed or released"),
int("action", "the button action", "#PRESS #RELEASE"),
int("mods", "bitfield describing which modifiers keys were held down"),
nativeType = "GLFWmousebuttonfun"
) {
documentation = "Instances of this interface may be passed to the #SetMouseButtonCallback() method."
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetMouseButtonCallback SetMouseButtonCallback}. */
public GLFWMouseButtonCallback set(long window) {
glfwSetMouseButtonCallback(window, this);
return this;
}
"""
}
}
val GLFWcursorposfun = Module.GLFW.callback {
void(
"GLFWCursorPosCallback",
"""
Will be called when the cursor is moved.
The callback function receives the cursor position, measured in screen coordinates but relative to the top-left corner of the window client area. On
platforms that provide it, the full sub-pixel cursor position is passed on.
""",
GLFWwindow.p("window", "the window that received the event"),
double("xpos", "the new cursor x-coordinate, relative to the left edge of the content area"),
double("ypos", "the new cursor y-coordinate, relative to the top edge of the content area"),
nativeType = "GLFWcursorposfun"
) {
documentation = "Instances of this interface may be passed to the #SetCursorPosCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetCursorPosCallback SetCursorPosCallback}. */
public GLFWCursorPosCallback set(long window) {
glfwSetCursorPosCallback(window, this);
return this;
}
"""
}
}
val GLFWcursorenterfun = Module.GLFW.callback {
void(
"GLFWCursorEnterCallback",
"Will be called when the cursor enters or leaves the client area of the window.",
GLFWwindow.p("window", "the window that received the event"),
intb("entered", "#TRUE if the cursor entered the window's content area, or #FALSE if it left it"),
nativeType = "GLFWcursorenterfun"
) {
documentation = "Instances of this interface may be passed to the #SetCursorEnterCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetCursorEnterCallback SetCursorEnterCallback}. */
public GLFWCursorEnterCallback set(long window) {
glfwSetCursorEnterCallback(window, this);
return this;
}
"""
}
}
val GLFWscrollfun = Module.GLFW.callback {
void(
"GLFWScrollCallback",
"Will be called when a scrolling device is used, such as a mouse wheel or scrolling area of a touchpad.",
GLFWwindow.p("window", "the window that received the event"),
double("xoffset", "the scroll offset along the x-axis"),
double("yoffset", "the scroll offset along the y-axis"),
nativeType = "GLFWscrollfun"
) {
documentation = "Instances of this interface may be passed to the #SetScrollCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetScrollCallback SetScrollCallback}. */
public GLFWScrollCallback set(long window) {
glfwSetScrollCallback(window, this);
return this;
}
"""
}
}
val GLFWdropfun = Module.GLFW.callback {
void(
"GLFWDropCallback",
"Will be called when one or more dragged files are dropped on the window.",
GLFWwindow.p("window", "the window that received the event"),
AutoSize("names")..int("count", "the number of dropped files"),
char.const.p.p("names", "pointer to the array of UTF-8 encoded path names of the dropped files"),
nativeType = "GLFWdropfun"
) {
documentation = "Instances of this interface may be passed to the #SetDropCallback() method."
since = "version 3.1"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/**
* Decodes the specified {@link GLFWDropCallback} arguments to a String.
*
* <p>This method may only be used inside a {@code GLFWDropCallback} invocation.</p>
*
* @param names pointer to the array of UTF-8 encoded path names of the dropped files
* @param index the index to decode
*
* @return the name at the specified index as a String
*/
public static String getName(long names, int index) {
return memUTF8(memGetAddress(names + Pointer.POINTER_SIZE * index));
}
/** See {@link GLFW#glfwSetDropCallback SetDropCallback}. */
public GLFWDropCallback set(long window) {
glfwSetDropCallback(window, this);
return this;
}
"""
}
}
// OpenGL
val GLFWglproc = "GLFWglproc".handle
// Vulkan
val GLFWvkproc = "GLFWvkproc".handle | bsd-3-clause | c088a3caf1085fbc21876923f017b3f7 | 37.516513 | 160 | 0.650432 | 4.610373 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/trackedentity/search/TrackedEntityInstanceQueryRepositoryScopeHelperShould.kt | 1 | 8751 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity.search
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.mock
import org.hisp.dhis.android.core.arch.repositories.scope.internal.FilterItemOperator
import org.hisp.dhis.android.core.common.*
import org.hisp.dhis.android.core.enrollment.EnrollmentStatus
import org.hisp.dhis.android.core.event.EventStatus
import org.hisp.dhis.android.core.trackedentity.AttributeValueFilter
import org.hisp.dhis.android.core.trackedentity.EntityQueryCriteria
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceEventFilter
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceFilter
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class TrackedEntityInstanceQueryRepositoryScopeHelperShould {
private val filterUid = "filterUid"
private val programId = "programId"
private val programStage1 = "programStage1"
private val programStage2 = "programStage2"
private val enrollmentStatus = EnrollmentStatus.COMPLETED
private val followUp = true
private val dateFilterPeriodHelper: DateFilterPeriodHelper = mock()
private lateinit var scopeHelper: TrackedEntityInstanceQueryRepositoryScopeHelper
@Before
fun setUp() {
scopeHelper = TrackedEntityInstanceQueryRepositoryScopeHelper(dateFilterPeriodHelper)
}
@Test
fun `Should parse first level properties`() {
val scope = TrackedEntityInstanceQueryRepositoryScope.empty()
val filter = TrackedEntityInstanceFilter.builder()
.uid(filterUid)
.program(ObjectWithUid.create(programId))
.entityQueryCriteria(
EntityQueryCriteria.builder()
.enrollmentStatus(enrollmentStatus)
.followUp(followUp)
.enrollmentCreatedDate(
DateFilterPeriod.builder()
.startBuffer(-2)
.endBuffer(5)
.build()
)
.build()
)
.build()
val updatedScope = scopeHelper.addTrackedEntityInstanceFilter(scope, filter)
assertThat(updatedScope.program()).isEqualTo(programId)
assertThat(updatedScope.enrollmentStatus()).isEqualTo(listOf(enrollmentStatus))
assertThat(updatedScope.followUp()).isEqualTo(followUp)
assertThat(updatedScope.programDate()).isNotNull()
val daysBetween = updatedScope.programDate()!!.endBuffer()!! - updatedScope.programDate()!!.startBuffer()!!
assertThat(daysBetween).isEqualTo(7)
}
@Test
fun `Should parse event filters`() {
val scope = TrackedEntityInstanceQueryRepositoryScope.empty()
val filter = TrackedEntityInstanceFilter.builder()
.uid(filterUid)
.eventFilters(
listOf(
TrackedEntityInstanceEventFilter.builder()
.programStage(programStage1).eventStatus(EventStatus.ACTIVE).build(),
TrackedEntityInstanceEventFilter.builder()
.programStage(programStage2).assignedUserMode(AssignedUserMode.CURRENT)
.eventCreatedPeriod(FilterPeriod.create(-5, 2)).build()
)
)
.entityQueryCriteria(EntityQueryCriteria.builder().build())
.build()
val updatedScope = scopeHelper.addTrackedEntityInstanceFilter(scope, filter)
assertThat(updatedScope.eventFilters().size).isEqualTo(2)
updatedScope.eventFilters().forEach {
when (it.programStage()) {
programStage1 ->
assertThat(it.eventStatus()).isEqualTo(listOf(EventStatus.ACTIVE))
programStage2 -> {
assertThat(it.assignedUserMode()).isEqualTo(AssignedUserMode.CURRENT)
assertThat(it.eventDate()).isNotNull()
val daysBetween = it.eventDate()!!.endBuffer()!! - it.eventDate()!!.startBuffer()!!
assertThat(daysBetween).isEqualTo(7)
}
else -> fail("Unknown programStageId")
}
}
}
@Test
fun `Should overwrite existing properties`() {
val scope = TrackedEntityInstanceQueryRepositoryScope.builder()
.program("existingProgramUid")
.enrollmentStatus(listOf(EnrollmentStatus.ACTIVE))
.eventFilters(
listOf(
TrackedEntityInstanceQueryEventFilter.builder().assignedUserMode(AssignedUserMode.CURRENT).build()
)
)
.build()
val filter = TrackedEntityInstanceFilter.builder()
.uid(filterUid)
.program(ObjectWithUid.create(programId))
.eventFilters(
listOf(
TrackedEntityInstanceEventFilter.builder().assignedUserMode(AssignedUserMode.ANY).build()
)
)
.entityQueryCriteria(EntityQueryCriteria.builder().build())
.build()
val updatedScope = scopeHelper.addTrackedEntityInstanceFilter(scope, filter)
assertThat(updatedScope.program()).isEqualTo(programId)
assertThat(updatedScope.enrollmentStatus()).isEqualTo(listOf(EnrollmentStatus.ACTIVE))
assertThat(updatedScope.eventFilters().size).isEqualTo(1)
assertThat(updatedScope.eventFilters()[0].assignedUserMode()).isEqualTo(AssignedUserMode.ANY)
}
@Test
fun `Should parse attribute filter values`() {
val scope = TrackedEntityInstanceQueryRepositoryScope.empty()
val filter = TrackedEntityInstanceFilter.builder()
.uid(filterUid)
.program(ObjectWithUid.create(programId))
.entityQueryCriteria(
EntityQueryCriteria.builder()
.attributeValueFilters(
listOf(
AttributeValueFilter.builder()
.attribute("attribute1")
.like("like_str")
.build(),
AttributeValueFilter.builder()
.attribute("attribute2")
.eq("eq_str")
.build(),
)
)
.build()
)
.build()
val updatedScope = scopeHelper.addTrackedEntityInstanceFilter(scope, filter)
val filters = updatedScope.filter()
assertThat(filters.size).isEqualTo(2)
assertThat(
filters.any {
it.operator() == FilterItemOperator.LIKE && it.key() == "attribute1" && it.value() == "like_str"
}
).isTrue()
assertThat(
filters.any {
it.operator() == FilterItemOperator.EQ && it.key() == "attribute2" && it.value() == "eq_str"
}
).isTrue()
}
}
| bsd-3-clause | 394f9542f4c81eee58d607eb5d94a559 | 41.897059 | 118 | 0.638441 | 5.259014 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/editor/quickDoc/EscapeHtmlInsideCodeBlocks.kt | 9 | 960 | /**
* Code block:
* ``` kotlin
* A<T>
* ```
* Code span:
* `<T>` is type parameter
*/
class <caret>A<T>
//INFO: <div class='definition'><pre><span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">final</span> <span style="color:#000080;font-weight:bold;">class</span> <span style="color:#000000;">A</span><span style=""><</span><span style="color:#20999d;">T</span><span style="">></span></pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Code block:</p>
//INFO: <pre><code style='font-size:96%;'>
//INFO: <span style=""><span style="">A<T></span></span>
//INFO: </code></pre><p>Code span: <code style='font-size:96%;'><span style=""><span style=""><T></span></span></code> is type parameter</p></div><table class='sections'></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"/> EscapeHtmlInsideCodeBlocks.kt<br/></div>
| apache-2.0 | 7db960b874174234c627272a16027083 | 67.571429 | 428 | 0.647917 | 3.028391 | false | false | false | false |
QuarkWorks/RealmTypeSafeQuery-Android | query/src/main/kotlin/com/quarkworks/android/realmtypesafequery/fields/RealmShortField.kt | 1 | 2681 | package com.quarkworks.android.realmtypesafequery.fields
import io.realm.RealmModel
import io.realm.RealmQuery
open class RealmShortField<Model : RealmModel>(override val modelClass: Class<Model>, override val name: String) :
RealmField<Model>,
RealmEquatableField<Model, Short>,
RealmComparableField<Model, Short>,
RealmSortableField<Model>,
RealmInableField<Model, Short>,
RealmMinMaxField<Model, Short>,
RealmAggregatableField<Model, Long> {
override fun equalTo(query: RealmQuery<Model>, value: Short?) {
if (value == null) {
isNull(query)
return
}
query.equalTo(name, value)
}
override fun notEqualTo(query: RealmQuery<Model>, value: Short?) {
if (value == null) {
isNotNull(query)
return
}
query.notEqualTo(name, value)
}
override fun never(query: RealmQuery<Model>) {
query.beginGroup().equalTo(name, 0.toShort()).equalTo(name, 1.toShort()).endGroup()
}
override fun greaterThan(query: RealmQuery<Model>, value: Short?) {
if (value == null) {
notEqualTo(query, null)
return
}
query.greaterThan(name, value.toInt())
}
override fun greaterThanOrEqualTo(query: RealmQuery<Model>, value: Short?) {
if (value == null) {
equalTo(query, null)
return
}
query.greaterThanOrEqualTo(name, value.toInt())
}
override fun lessThan(query: RealmQuery<Model>, value: Short?) {
if (value == null) {
notEqualTo(query, null)
return
}
query.lessThan(name, value.toInt())
}
override fun lessThanOrEqualTo(query: RealmQuery<Model>, value: Short?) {
if (value == null) {
equalTo(query, null)
return
}
query.lessThanOrEqualTo(name, value.toInt())
}
override fun between(query: RealmQuery<Model>, start: Short?, end: Short?) {
if (start == null || end == null) {
equalTo(query, null)
}
query.between(name, start!!.toInt(), end!!.toInt())
}
override fun `in`(query: RealmQuery<Model>, values: Array<Short>) {
query.`in`(name, values)
}
override fun `in`(query: RealmQuery<Model>, values: List<Short>) {
query.`in`(name, values.toTypedArray())
}
override fun min(query: RealmQuery<Model>): Short? = query.min(name)?.toShort()
override fun max(query: RealmQuery<Model>): Short? = query.max(name)?.toShort()
override fun sum(query: RealmQuery<Model>): Long = query.sum(name).toLong()
}
| mit | 5fa875a133bd269e2970aec01cb4273a | 27.521277 | 114 | 0.595673 | 4.282748 | false | false | false | false |
martijn-heil/wac-core | src/main/kotlin/tk/martijn_heil/wac_core/craft/util/craftutil.kt | 1 | 4528 | /*
* wac-core
* Copyright (C) 2016 Martijn Heil
*
* 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 tk.martijn_heil.wac_core.craft.util
import at.pavlov.cannons.cannon.Cannon
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.Material.AIR
import org.bukkit.World
import org.bukkit.block.Block
import org.bukkit.entity.Entity
import org.bukkit.event.player.PlayerTeleportEvent
import tk.martijn_heil.wac_core.craft.Rotation
import tk.martijn_heil.wac_core.craft.Rotation.CLOCKWISE
import tk.martijn_heil.wac_core.craft.SailingModule
import java.util.*
fun detect(startLocation: Location, allowedBlocks: Collection<Material>, maxSize: Int): Collection<Block> {
val blocks = ArrayList<Block>()
val s = Stack<Location>()
s.push(startLocation)
while(s.count() > 0) {
if(blocks.size >= maxSize) throw Exception("Maximum detection size ($maxSize) exceeded.")
val loc = s.pop()
if(blocks.contains(loc.block) || !allowedBlocks.contains(loc.block.type)) continue
blocks.add(loc.block)
for (modX in -1..1) {
for(modY in -1..1) {
for(modZ in -1..1) {
s.push(Location(loc.world, loc.x + modX, loc.y + modY, loc.z + modZ))
}
}
}
}
if(blocks.isEmpty()) throw Exception("Could not detect any allowed blocks.")
return blocks
}
fun getRotatedLocation(rotationPoint: Location, rotation: Rotation, loc: Location): Location {
val newRelativeX = if (rotation == CLOCKWISE) rotationPoint.z - loc.z else -(rotationPoint.z - loc.z)
val newRelativeZ = if(rotation == CLOCKWISE) -(rotationPoint.x - loc.x) else rotationPoint.x - loc.x
return Location(loc.world, rotationPoint.x + newRelativeX, loc.y, rotationPoint.z + newRelativeZ)
}
fun getRotatedLocation(output: Location, rotationPoint: Location, rotation: Rotation, loc: Location) {
val newRelativeX = if (rotation == CLOCKWISE) rotationPoint.z - loc.z else -(rotationPoint.z - loc.z)
val newRelativeZ = if(rotation == CLOCKWISE) -(rotationPoint.x - loc.x) else rotationPoint.x - loc.x
output.x += newRelativeX
output.y += loc.y
output.z += newRelativeZ
}
fun detectAirBlocksBelowSeaLevel(world: World, box: BoundingBox): Collection<BlockPos> {
val minX = box.minX.toInt()
val maxX = box.maxX.toInt()
val minY = box.minY.toInt()
val minZ = box.minZ.toInt()
val maxZ = box.maxZ.toInt()
if(minY > world.seaLevel) return emptyList()
val list = ArrayList<BlockPos>()
for(x in minX..maxX) {
for(y in minY..world.seaLevel) {
for(z in minZ..maxZ) {
if(world.getBlockAt(x, y, z).type == AIR) list.add(BlockPos(x, y, z))
}
}
}
return list
}
fun detectCannons(locations: List<Location>): Collection<Cannon> {
val cannons = ArrayList<Cannon>()
Bukkit.getOnlinePlayers().forEach { p -> cannons.addAll(SailingModule.cannonsAPI.getCannons(locations, p.uniqueId)) }
return cannons
}
fun rotateEntities(entities: Collection<Entity>, rotationPoint: Location, rotation: Rotation) {
entities.forEach {
val loc = it.location
val newLoc = getRotatedLocation(rotationPoint, rotation, loc)
newLoc.yaw = if (rotation == Rotation.CLOCKWISE) loc.yaw + 90 else loc.yaw - 90
if (newLoc.yaw < -179) newLoc.yaw += 360
if (newLoc.yaw > 180) newLoc.yaw -= 360
newLoc.pitch = loc.pitch
// Correction for teleport behaviour
when (rotation) {
Rotation.CLOCKWISE -> newLoc.x += 1
Rotation.ANTICLOCKWISE -> newLoc.z += 1
}
it.teleport(newLoc, PlayerTeleportEvent.TeleportCause.PLUGIN)
}
} | gpl-3.0 | ed98a59e7ab8d0637714bb3db959cc63 | 35.438017 | 121 | 0.650177 | 3.77648 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/hprof/visitors/CreateClassStoreVisitor.kt | 12 | 3990 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diagnostic.hprof.visitors
import com.intellij.diagnostic.hprof.classstore.ClassDefinition
import com.intellij.diagnostic.hprof.classstore.ClassStore
import com.intellij.diagnostic.hprof.classstore.InstanceField
import com.intellij.diagnostic.hprof.classstore.StaticField
import com.intellij.diagnostic.hprof.parser.*
import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap
import it.unimi.dsi.fastutil.longs.Long2ObjectMap
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap
import it.unimi.dsi.fastutil.longs.LongArrayList
internal class CreateClassStoreVisitor(private val stringIdMap: Long2ObjectMap<String>) : HProfVisitor() {
private val classIDToNameStringID = Long2LongOpenHashMap()
private val result = Long2ObjectOpenHashMap<ClassDefinition>()
private var completed = false
override fun preVisit() {
disableAll()
enable(RecordType.LoadClass)
enable(HeapDumpRecordType.ClassDump)
classIDToNameStringID.clear()
}
override fun postVisit() {
completed = true
}
override fun visitLoadClass(classSerialNumber: Long, classObjectId: Long, stackSerialNumber: Long, classNameStringId: Long) {
classIDToNameStringID.put(classObjectId, classNameStringId)
}
override fun visitClassDump(
classId: Long,
stackTraceSerialNumber: Long,
superClassId: Long,
classloaderClassId: Long,
instanceSize: Long,
constants: Array<ConstantPoolEntry>,
staticFields: Array<StaticFieldEntry>,
instanceFields: Array<InstanceFieldEntry>) {
val refInstanceFields = mutableListOf<InstanceField>()
val primitiveInstanceFields = mutableListOf<InstanceField>()
var currentOffset = 0
instanceFields.forEach {
val fieldName = stringIdMap[it.fieldNameStringId]
val field = InstanceField(fieldName, currentOffset, it.type)
if (it.type != Type.OBJECT) {
primitiveInstanceFields.add(field)
currentOffset += it.type.size
}
else {
refInstanceFields.add(field)
currentOffset += visitorContext.idSize
}
}
val constantsArray = LongArrayList(constants.size)
constants.asSequence()
.filter { it.type == Type.OBJECT }
.forEach { constantsArray.add(it.value) }
val objectStaticFieldList = staticFields.asSequence()
.filter { it.type == Type.OBJECT }
.map { StaticField(stringIdMap[it.fieldNameStringId], it.value) }
val primitiveStaticFieldList = staticFields.asSequence()
.filter { it.type != Type.OBJECT }
.map { StaticField(stringIdMap[it.fieldNameStringId], it.value) }
val classDefinition = ClassDefinition(
name = stringIdMap.get(classIDToNameStringID.get(classId)).replace('/', '.'),
id = classId,
superClassId = superClassId,
classLoaderId = classloaderClassId,
instanceSize = instanceSize.toInt(),
superClassOffset = currentOffset,
refInstanceFields = refInstanceFields.toTypedArray(),
primitiveInstanceFields = primitiveInstanceFields.toTypedArray(),
constantFields = constantsArray.toLongArray(),
objectStaticFields = objectStaticFieldList.toList().toTypedArray(),
primitiveStaticFields = primitiveStaticFieldList.toList().toTypedArray()
)
result.put(classId, classDefinition)
}
fun getClassStore(): ClassStore {
assert(completed)
return ClassStore(result)
}
} | apache-2.0 | eb28567e93141756d0de8a4dbeb66510 | 37.375 | 127 | 0.742356 | 4.534091 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/appsync/src/main/kotlin/com/example/appsync/CreateApiKey.kt | 1 | 1740 | // snippet-sourcedescription:[CreateApiKey.kt demonstrates how to create a unique key.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[AWS AppSync]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.appsync
// snippet-start:[appsync.kotlin.create_key.import]
import aws.sdk.kotlin.services.appsync.AppSyncClient
import aws.sdk.kotlin.services.appsync.model.CreateApiKeyRequest
import kotlin.system.exitProcess
// snippet-end:[appsync.kotlin.create_key.import]
/**
* Before running this Kotlin code example, set up your development environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<apiId>
Where:
apiId - The Id of the API. (You can get this value from the AWS Management Console.)
"""
if (args.size != 1) {
println(usage)
exitProcess(1)
}
val apiId = args[0]
val key = createKey(apiId)
println("The Id of the new Key is $key")
}
// snippet-start:[appsync.kotlin.create_key.main]
suspend fun createKey(apiIdVal: String): String? {
val apiKeyRequest = CreateApiKeyRequest {
apiId = apiIdVal
description = "Created using the AWS SDK for Kotlin"
}
AppSyncClient { region = "us-east-1" }.use { appClient ->
val response = appClient.createApiKey(apiKeyRequest)
return response.apiKey?.id
}
}
// snippet-end:[appsync.kotlin.create_key.main]
| apache-2.0 | 1238c6c005dfdd21b12492a177cbb878 | 28.526316 | 108 | 0.666667 | 3.866667 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/utils/multiselector/SelectorBase.kt | 1 | 2474 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.utils.multiselector
import android.os.Bundle
import androidx.annotation.CallSuper
abstract class SelectorBase {
protected var tracker = WeakHolderTracker()
var selectable: Boolean = false
set(value) {
field = value
refreshAllHolders()
}
protected fun refreshAllHolders() {
for (holder in tracker.trackedHolders) {
refreshHolder(holder)
}
}
protected fun refreshHolder(holder: SelectableHolder?) {
if (holder != null) {
if (holder is ItemBindingHolder<*> && holder.item != null) {
holder.bindItem()
}
holder.isSelectable = selectable
holder.isActivated = isSelected(holder.itemIdentifier)
}
}
fun setSelected(holder: SelectableHolder, isSelected: Boolean) {
setSelected(holder.itemIdentifier, isSelected)
}
abstract fun setSelected(id: Long, isSelected: Boolean)
protected abstract fun isSelected(id: Long): Boolean
fun tapSelection(holder: SelectableHolder): Boolean {
val itemId = holder.itemIdentifier
return if (selectable) {
val isSelected = isSelected(itemId)
setSelected(itemId, !isSelected)
true
} else {
false
}
}
fun saveSelectionStates(): Bundle {
val bundle = Bundle()
bundle.putBoolean(SELECTIONS_STATE, selectable)
saveSelectionStates(bundle)
return bundle
}
fun bindHolder(holder: SelectableHolder, id: Long) {
tracker.bindHolder(holder, id)
refreshHolder(holder)
}
protected abstract fun saveSelectionStates(bundle: Bundle)
@CallSuper
open fun restoreSelectionStates(savedStates: Bundle) {
selectable = savedStates.getBoolean(SELECTIONS_STATE)
}
companion object {
private const val SELECTIONS_STATE = "state"
}
}
| gpl-2.0 | 1ae1f06f719ab7cf819b630baab505f5 | 27.767442 | 72 | 0.65481 | 4.74856 | false | false | false | false |
paplorinc/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/completion/providers/EditorConfigSimpleOptionKeyCompletionProvider.kt | 4 | 2876 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.codeinsight.completion.providers
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.patterns.PsiElementPattern
import com.intellij.psi.PsiElement
import com.intellij.util.ProcessingContext
import org.editorconfig.language.codeinsight.completion.providers.EditorConfigCompletionProviderUtil.createLookupAndCheckDeprecation
import org.editorconfig.language.codeinsight.completion.withSeparatorIn
import org.editorconfig.language.psi.EditorConfigElementTypes
import org.editorconfig.language.psi.EditorConfigOption
import org.editorconfig.language.psi.EditorConfigSection
import org.editorconfig.language.services.EditorConfigOptionDescriptorManager
import org.editorconfig.language.util.EditorConfigPsiTreeUtil.getParentOfType
object EditorConfigSimpleOptionKeyCompletionProvider : EditorConfigCompletionProviderBase() {
override val destination: PsiElementPattern.Capture<PsiElement> =
psiElement()
.afterLeaf(psiElement().andOr(
psiElement(EditorConfigElementTypes.IDENTIFIER),
psiElement(EditorConfigElementTypes.R_BRACKET)
))
.withSuperParent(3, EditorConfigSection::class.java)
.andNot(psiElement().withParent(psiElement(EditorConfigElementTypes.PATTERN)))
.andNot(psiElement().beforeLeaf(psiElement(EditorConfigElementTypes.COLON)))
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val position = parameters.position
val option = position.parent.parent as EditorConfigOption
val text = position.text
val firstChar = text.first().takeUnless { text.startsWith(DUMMY_IDENTIFIER_TRIMMED) }
val section = position.getParentOfType<EditorConfigSection>() ?: return
val optionKeys = section.optionList.mapNotNull(EditorConfigOption::getFlatOptionKey)
val rawCompletionItems = EditorConfigOptionDescriptorManager
.instance
.getSimpleKeyDescriptors(false)
.asSequence()
.filter { optionKeys.none(it::matches) }
.flatMap { EditorConfigCompletionProviderUtil.selectSimpleParts(it, firstChar).asSequence() }
.map(::createLookupAndCheckDeprecation)
val completionItems = if (needSeparatorAfter(option.nextSibling)) {
rawCompletionItems.map { it.withSeparatorIn(section.containingFile) }
}
else rawCompletionItems
completionItems.forEach(result::addElement)
}
private fun needSeparatorAfter(space: PsiElement?) =
space?.textMatches(" ") != true
}
| apache-2.0 | 1550ffba27c44ea90630c3601612812a | 52.259259 | 140 | 0.809805 | 5.090265 | false | true | false | false |
nibarius/opera-park-android | app/src/testMock/java/se/barsk/park/CarCollectionTest.kt | 1 | 5268 | package se.barsk.park
import android.util.SparseBooleanArray
import org.junit.Assert.assertEquals
import org.junit.Test
import se.barsk.park.datatypes.Garage
import se.barsk.park.datatypes.MockCarCollection
import se.barsk.park.datatypes.OwnCar
import se.barsk.park.datatypes.ParkedCar
class CarCollectionTest : RobolectricTest() {
private val fullGarage = Garage(listOf(
ParkedCar("zzz999", "owner", "1 hour ago"),
ParkedCar("yyy888", "owner2", "1 hour ago"),
ParkedCar("xxx777", "owner3", "1 hour ago"),
ParkedCar("www666", "owner4", "1 hour ago"),
ParkedCar("vvv555", "owner5", "1 hour ago"),
ParkedCar("uuu444", "owner6", "1 hour ago")))
private val carCollection = MockCarCollection()
@Test
fun testEmptyCarCollection() {
carCollection.replaceContent(mutableListOf())
assertEquals(true, carCollection.getCars().isEmpty())
}
@Test
fun testUpdateStatusEmptyCollection() {
carCollection.replaceContent(mutableListOf())
assertEquals(false, carCollection.updateParkStatus(fullGarage))
}
@Test
fun testUpdateStatusNoParkedCar() {
carCollection.replaceContent(mutableListOf(OwnCar("abc123", "me")))
assertEquals(false, carCollection.updateParkStatus(fullGarage))
}
@Test
fun testUpdateStatusCarIsParked() {
carCollection.replaceContent(mutableListOf(OwnCar("uuu444", "me")))
assertEquals(true, carCollection.updateParkStatus(fullGarage))
assertEquals(true, carCollection.getCars()[0].parked)
}
@Test
fun testUpdateStatusCarIsStillParked() {
carCollection.replaceContent(mutableListOf(OwnCar("uuu444", "me")))
carCollection.updateParkStatus(fullGarage)
assertEquals(false, carCollection.updateParkStatus(fullGarage))
assertEquals(true, carCollection.getCars()[0].parked)
}
@Test
fun testUpdateStatusCarIsNoLongerParked() {
carCollection.replaceContent(mutableListOf(OwnCar("uuu444", "me")))
carCollection.updateParkStatus(fullGarage)
assertEquals(true, carCollection.updateParkStatus(Garage()))
assertEquals(false, carCollection.getCars()[0].parked)
}
@Test
fun testPositionOfOneCar() {
val car = OwnCar("uuu444", "me", id = "my_uuid")
carCollection.replaceContent(mutableListOf(car))
assertEquals(0, carCollection.positionOf(car))
}
@Test
fun testPositionOfFirstCar() {
val car1 = OwnCar("uuu444", "me", id = "my_uuid")
val car2 = OwnCar("uuu444", "me")
carCollection.replaceContent(mutableListOf(car1, car2))
assertEquals(0, carCollection.positionOf(car1))
}
@Test
fun testPositionOfLastCar() {
val car1 = OwnCar("uuu444", "me")
val car2 = OwnCar("uuu444", "me", id = "my_uuid")
carCollection.replaceContent(mutableListOf(car1, car2))
assertEquals(1, carCollection.positionOf(car2))
}
@Test(expected = RuntimeException::class)
fun testPositionOfDoesNotExist() {
carCollection.replaceContent(mutableListOf())
carCollection.positionOf(OwnCar("uuu444", "me"))
}
@Test
fun testRemoveFirstCar() {
val car1 = OwnCar("uuu444", "me")
val car2 = OwnCar("vvv555", "me")
val car3 = OwnCar("www666", "me")
carCollection.replaceContent(mutableListOf(car1, car2, car3))
val toDelete = SparseBooleanArray()
toDelete.put(0, true)
carCollection.removeCars(toDelete)
assertEquals(2, carCollection.getCars().size)
assertEquals(car2, carCollection.getCarAtPosition(0))
assertEquals(car3, carCollection.getCarAtPosition(1))
}
@Test
fun testRemoveLastCar() {
val car1 = OwnCar("uuu444", "me")
val car2 = OwnCar("vvv555", "me")
val car3 = OwnCar("www666", "me")
carCollection.replaceContent(mutableListOf(car1, car2, car3))
val toDelete = SparseBooleanArray()
toDelete.put(2, true)
carCollection.removeCars(toDelete)
assertEquals(2, carCollection.getCars().size)
assertEquals(car1, carCollection.getCarAtPosition(0))
assertEquals(car2, carCollection.getCarAtPosition(1))
}
@Test
fun testRemoveTwoCars() {
val car1 = OwnCar("uuu444", "me")
val car2 = OwnCar("vvv555", "me")
val car3 = OwnCar("www666", "me")
carCollection.replaceContent(mutableListOf(car1, car2, car3))
val toDelete = SparseBooleanArray()
toDelete.put(0, true)
toDelete.put(2, true)
carCollection.removeCars(toDelete)
assertEquals(1, carCollection.getCars().size)
assertEquals(car2, carCollection.getCarAtPosition(0))
}
@Test
fun testRemoveAllCars() {
val car1 = OwnCar("uuu444", "me")
val car2 = OwnCar("vvv555", "me")
val car3 = OwnCar("www666", "me")
carCollection.replaceContent(mutableListOf(car1, car2, car3))
val toDelete = SparseBooleanArray()
toDelete.put(0, true)
toDelete.put(1, true)
toDelete.put(2, true)
carCollection.removeCars(toDelete)
assertEquals(0, carCollection.getCars().size)
}
} | mit | 057fb36855ffb14dab70375d5ecab157 | 35.089041 | 75 | 0.656796 | 3.825708 | false | true | false | false |
arnab/adventofcode | src/main/kotlin/aoc2020/day8/InfiniteLoop.kt | 1 | 4442 | package aoc2020.day8
import java.lang.IllegalArgumentException
object InfiniteLoop {
data class Program(
val instructions: List<Pair<String, Int>>,
val currentState: State
) {
companion object {
fun parse(rawInstructions: String): Program =
rawInstructions.split("\n")
.map { it.parseInstruction() }
.let { instructions -> Program(instructions, State.init()) }
}
data class State(
val currentInstruction: Int,
val currentAccumulatedValue: Int,
val seenInstructions: Set<Int>
) {
companion object {
fun init() = State(0,0, emptySet())
}
}
fun eval(): State = evalSafely(currentState)
private fun evalSafely(state: State): State {
val allInstructionsProcessed = state.currentInstruction >= this.instructions.size
val instructionAlreadyEvaluated = state.seenInstructions.contains(state.currentInstruction)
if (allInstructionsProcessed || instructionAlreadyEvaluated) return state
val nextState = evalInstruction(this.instructions[state.currentInstruction], state)
return evalSafely(nextState)
}
fun detectAndRepair(): State? {
generateAllPossibleInstructions(this.instructions).forEach { instructions ->
val program = Program(instructions, State.init())
try {
// If we successfully execute the program, we are done!
return program.evalAndAbortOnLoops(program.currentState)
} catch (e: IllegalArgumentException) {
println("Dang... Still failing... Let's try the next set of tweaked instruction")
}
}
return null
}
private fun generateAllPossibleInstructions(
instructions: List<Pair<String, Int>>
): Sequence<List<Pair<String, Int>>> {
val allInstructionSets = mutableListOf<List<Pair<String, Int>>>()
for (i in instructions.indices) {
val (operator, value) = instructions[i]
if (operator in listOf("nop", "jmp")) {
val newOperator = if (operator == "nop") "jmp" else "nop"
instructions.toMutableList()
.apply { this[i] = Pair(newOperator, value) }
.also { allInstructionSets.add(it) }
}
}
return allInstructionSets.asSequence()
}
private fun evalAndAbortOnLoops(state: State): State {
val instructionAlreadyEvaluated = state.seenInstructions.contains(state.currentInstruction)
if (instructionAlreadyEvaluated) {
throw IllegalArgumentException("Instr #${state.currentInstruction} already evaluated: ${state.seenInstructions}")
}
val allInstructionsProcessed = state.currentInstruction >= this.instructions.size
if (allInstructionsProcessed) return state
val nextState = evalInstruction(this.instructions[state.currentInstruction], state)
return evalAndAbortOnLoops(nextState)
}
private fun evalInstruction(instruction: Pair<String, Int>, state: State): State = instruction.let {
(operator, value) ->
when(operator) {
"nop" -> state.copy(
seenInstructions = state.seenInstructions + state.currentInstruction,
currentInstruction = state.currentInstruction + 1
)
"acc" -> state.copy(
seenInstructions = state.seenInstructions + state.currentInstruction,
currentInstruction = state.currentInstruction + 1,
currentAccumulatedValue = state.currentAccumulatedValue + value
)
"jmp" -> state.copy(
seenInstructions = state.seenInstructions + state.currentInstruction,
currentInstruction = state.currentInstruction + value
)
else -> throw IllegalArgumentException("Unknown operator: $operator")
}
}
}
}
private fun String.parseInstruction() = this.split(" ").let {
(operation, value) -> Pair(operation, value.toInt())
}
| mit | 0c30faab686a7b2fa9ebe7b4ecfb90ce | 39.018018 | 129 | 0.583296 | 5.332533 | false | false | false | false |
google/intellij-community | plugins/kotlin/code-insight/utils/src/org/jetbrains/kotlin/idea/codeinsight/utils/ExpressionSimplificationUtils.kt | 1 | 2494 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeinsight.utils
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
object NegatedBinaryExpressionSimplificationUtils {
fun simplifyNegatedBinaryExpressionIfNeeded(expression: KtPrefixExpression) {
if (expression.canBeSimplified()) expression.simplify()
}
fun KtPrefixExpression.canBeSimplified(): Boolean {
if (operationToken != KtTokens.EXCL) return false
val expression = KtPsiUtil.deparenthesize(baseExpression) as? KtOperationExpression ?: return false
when (expression) {
is KtIsExpression -> if (expression.typeReference == null) return false
is KtBinaryExpression -> if (expression.left == null || expression.right == null) return false
else -> return false
}
return (expression.operationReference.getReferencedNameElementType() as? KtSingleValueToken)?.negate() != null
}
fun KtPrefixExpression.simplify() {
val expression = KtPsiUtil.deparenthesize(baseExpression) ?: return
val operation =
(expression as KtOperationExpression).operationReference.getReferencedNameElementType().negate()?.value ?: return
val psiFactory = KtPsiFactory(expression)
val newExpression = when (expression) {
is KtIsExpression ->
psiFactory.createExpressionByPattern("$0 $1 $2", expression.leftHandSide, operation, expression.typeReference!!)
is KtBinaryExpression ->
psiFactory.createExpressionByPattern("$0 $1 $2", expression.left ?: return, operation, expression.right ?: return)
else ->
throw IllegalArgumentException()
}
replace(newExpression)
}
fun IElementType.negate(): KtSingleValueToken? = when (this) {
KtTokens.IN_KEYWORD -> KtTokens.NOT_IN
KtTokens.NOT_IN -> KtTokens.IN_KEYWORD
KtTokens.IS_KEYWORD -> KtTokens.NOT_IS
KtTokens.NOT_IS -> KtTokens.IS_KEYWORD
KtTokens.EQEQ -> KtTokens.EXCLEQ
KtTokens.EXCLEQ -> KtTokens.EQEQ
KtTokens.LT -> KtTokens.GTEQ
KtTokens.GTEQ -> KtTokens.LT
KtTokens.GT -> KtTokens.LTEQ
KtTokens.LTEQ -> KtTokens.GT
else -> null
}
} | apache-2.0 | 814e0e6e0fa0b8fccf13141fe5a31967 | 39.241935 | 130 | 0.682839 | 5.375 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/Formatting.kt | 1 | 696 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.objectweb.asm.Opcodes
class Formatting : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.instanceFields.isEmpty() && it.instanceMethods.isEmpty() }
.and { it.classInitializer != null && it.classInitializer!!.instructions.any { it.opcode == Opcodes.LDC && it.ldcCst == "->" } }
} | mit | ea2e6db8a71bb4a7e85133842e6d5690 | 45.466667 | 140 | 0.748563 | 3.824176 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentEntityImpl.kt | 1 | 8048 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ParentEntityImpl(val dataSource: ParentEntityData) : ParentEntity, WorkspaceEntityBase() {
companion object {
internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentEntity::class.java, ChildEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
CHILD_CONNECTION_ID,
)
}
override val parentData: String
get() = dataSource.parentData
override val child: ChildEntity?
get() = snapshot.extractOneToOneChild(CHILD_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ParentEntityData?) : ModifiableWorkspaceEntityBase<ParentEntity>(), ParentEntity.Builder {
constructor() : this(ParentEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ParentEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isParentDataInitialized()) {
error("Field ParentEntity#parentData should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ParentEntity
this.entitySource = dataSource.entitySource
this.parentData = dataSource.parentData
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentData: String
get() = getEntityData().parentData
set(value) {
checkModificationAllowed()
getEntityData().parentData = value
changedProperty.add("parentData")
}
override var child: ChildEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? ChildEntity
}
else {
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? ChildEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CHILD_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value
}
changedProperty.add("child")
}
override fun getEntityData(): ParentEntityData = result ?: super.getEntityData() as ParentEntityData
override fun getEntityClass(): Class<ParentEntity> = ParentEntity::class.java
}
}
class ParentEntityData : WorkspaceEntityData<ParentEntity>() {
lateinit var parentData: String
fun isParentDataInitialized(): Boolean = ::parentData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ParentEntity> {
val modifiable = ParentEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ParentEntity {
return getCached(snapshot) {
val entity = ParentEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ParentEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ParentEntity(parentData, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ParentEntityData
if (this.entitySource != other.entitySource) return false
if (this.parentData != other.parentData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ParentEntityData
if (this.parentData != other.parentData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + parentData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + parentData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | f1070cb725c6f94859a87aebeaec811f | 33.246809 | 138 | 0.706635 | 5.319233 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeObjectToClassFix.kt | 1 | 1772 | // 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.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtConstructor
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
class ChangeObjectToClassFix(element: KtObjectDeclaration) : KotlinQuickFixAction<KtObjectDeclaration>(element) {
override fun getText(): String = KotlinBundle.message("fix.change.object.to.class")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val objectDeclaration = element ?: return
val psiFactory = KtPsiFactory(project)
objectDeclaration.getObjectKeyword()?.replace(psiFactory.createClassKeyword())
objectDeclaration.replace(psiFactory.createClass(objectDeclaration.text))
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtObjectDeclaration>? {
val element = diagnostic.psiElement as? KtConstructor<*> ?: return null
val containingObject = element.containingClassOrObject as? KtObjectDeclaration ?: return null
return ChangeObjectToClassFix(containingObject)
}
}
}
| apache-2.0 | dc353b2ea2ec57e046e55dd8b89eb912 | 49.628571 | 158 | 0.782167 | 5.048433 | false | false | false | false |
StephaneBg/ScoreIt | cache/src/main/kotlin/com/sbgapps/scoreit/cache/repository/ScoreItPreferencesRepo.kt | 1 | 3954 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.cache.repository
import android.content.SharedPreferences
import androidx.core.content.edit
import com.sbgapps.scoreit.core.utils.THEME_MODE_AUTO
import com.sbgapps.scoreit.data.model.GameType
import com.sbgapps.scoreit.data.repository.PreferencesRepo
import kotlin.math.max
class ScoreItPreferencesRepo(private val preferences: SharedPreferences) : PreferencesRepo {
override fun getGameType(): GameType =
GameType.values()[preferences.getInt(USER_PREF_CURRENT_GAME, GameType.UNIVERSAL.ordinal)]
override fun setGameType(gameType: GameType) {
preferences.edit {
putInt(USER_PREF_CURRENT_GAME, gameType.ordinal)
}
}
override fun getPlayerCount(): Int = when (getGameType()) {
GameType.UNIVERSAL -> preferences.getInt(USER_PREF_UNIVERSAL_PLAYER_CNT, 5)
GameType.TAROT -> preferences.getInt(USER_PREF_TAROT_PLAYER_CNT, 5)
else -> 2
}
override fun setPlayerCount(count: Int) {
preferences.edit {
when (getGameType()) {
GameType.UNIVERSAL -> putInt(USER_PREF_UNIVERSAL_PLAYER_CNT, max(2, count))
GameType.TAROT -> putInt(USER_PREF_TAROT_PLAYER_CNT, max(3, count))
else -> error("Cannot set player count for this game")
}
}
}
override fun isRounded(gameType: GameType): Boolean = when (gameType) {
GameType.BELOTE -> preferences.getBoolean(USER_PREF_BELOTE_ROUND, true)
GameType.COINCHE -> preferences.getBoolean(USER_PREF_COINCHE_ROUND, true)
else -> error("This game can't have rounded points")
}
override fun setRounded(gameType: GameType, rounded: Boolean) {
return when (gameType) {
GameType.BELOTE -> preferences.edit { putBoolean(USER_PREF_BELOTE_ROUND, rounded) }
GameType.COINCHE -> preferences.edit { putBoolean(USER_PREF_COINCHE_ROUND, rounded) }
else -> error("This game can't have rounded points")
}
}
override fun isTotalDisplayed(gameType: GameType): Boolean = when (gameType) {
GameType.UNIVERSAL -> preferences.getBoolean(USER_PREF_UNIVERSAL_TOTAL, false)
else -> error("Cannot display total for this game")
}
override fun setTotalDisplayed(gameType: GameType, displayed: Boolean) {
preferences.edit {
when (gameType) {
GameType.UNIVERSAL -> putBoolean(USER_PREF_UNIVERSAL_TOTAL, displayed)
else -> error("Cannot display total for this game")
}
}
}
override fun getThemeMode(): String = preferences.getString(USER_PREF_THEME, null) ?: THEME_MODE_AUTO
override fun setThemeMode(mode: String) {
preferences.edit {
putString(USER_PREF_THEME, mode)
}
}
companion object {
private const val USER_PREF_CURRENT_GAME = "selected_game"
private const val USER_PREF_UNIVERSAL_PLAYER_CNT = "universal_player_count"
private const val USER_PREF_TAROT_PLAYER_CNT = "tarot_player_count"
private const val USER_PREF_UNIVERSAL_TOTAL = "universal_show_total"
private const val USER_PREF_BELOTE_ROUND = "belote_round_score"
private const val USER_PREF_COINCHE_ROUND = "coinche_round_score"
private const val USER_PREF_THEME = "preferred_theme"
}
}
| apache-2.0 | 0fe8321df8bbfb04e784820604b69440 | 39.336735 | 105 | 0.677713 | 4.029562 | false | false | false | false |
StephaneBg/ScoreIt | app/src/main/kotlin/com/sbgapps/scoreit/app/ui/edition/coinche/CoincheEditionBonusFragment.kt | 1 | 3196 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.app.ui.edition.coinche
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sbgapps.scoreit.app.R
import com.sbgapps.scoreit.app.databinding.FragmentEditionCoincheBonusBinding
import com.sbgapps.scoreit.data.model.BeloteBonusValue
import com.sbgapps.scoreit.data.model.PlayerPosition
import io.uniflow.androidx.flow.onStates
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
class CoincheEditionBonusFragment : BottomSheetDialogFragment() {
private val viewModel by sharedViewModel<CoincheEditionViewModel>()
private var beloteBonus: BeloteBonusValue = BeloteBonusValue.BELOTE
private lateinit var binding: FragmentEditionCoincheBonusBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentEditionCoincheBonusBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
onStates(viewModel) { state ->
if (state is CoincheEditionState.Content) {
binding.teamOne.text = state.players[PlayerPosition.ONE.index].name
binding.teamTwo.text = state.players[PlayerPosition.TWO.index].name
beloteBonus = state.availableBonuses.first()
binding.bonus.text = getString(beloteBonus.resId)
binding.bonus.setOnClickListener {
MaterialAlertDialogBuilder(requireContext())
.setSingleChoiceItems(
state.availableBonuses.map { getString(it.resId) }.toTypedArray(),
state.availableBonuses.indexOf(beloteBonus)
) { dialog, which ->
beloteBonus = state.availableBonuses[which]
binding.bonus.text = getString(beloteBonus.resId)
dialog.dismiss()
}
.show()
}
binding.addBonus.setOnClickListener {
viewModel.addBonus(getTeam() to beloteBonus)
dismiss()
}
}
}
}
private fun getTeam(): PlayerPosition =
if (R.id.teamOne == binding.teamGroup.checkedButtonId) PlayerPosition.ONE else PlayerPosition.TWO
}
| apache-2.0 | 05a21bac842f61c376591beeb554adff | 42.175676 | 116 | 0.679812 | 4.819005 | false | false | false | false |
exercism/xkotlin | exercises/practice/robot-simulator/src/test/kotlin/RobotTest.kt | 1 | 5244 | import org.junit.Ignore
import org.junit.Test
import kotlin.test.assertEquals
class RobotTest {
@Test
fun `brand new - at origin facing north`() =
Robot()
.should {
face(Orientation.NORTH)
beAt(x = 0, y = 0)
}
@Ignore
@Test
fun `brand new - at negative position facing south`() =
Robot(GridPosition(x = -1, y = -1), Orientation.SOUTH)
.should {
face(Orientation.SOUTH)
beAt(x = -1, y = -1)
}
@Ignore
@Test
fun `rotating clockwise - changes north to east`() =
Robot(GridPosition(x = 0, y = 0), Orientation.NORTH)
.instructed("R")
.should {
face(Orientation.EAST)
}
@Ignore
@Test
fun `rotating clockwise - changes east to south`() =
Robot(GridPosition(x = 0, y = 0), Orientation.EAST)
.instructed("R")
.should {
face(Orientation.SOUTH)
}
@Ignore
@Test
fun `rotating clockwise - changes south to west`() =
Robot(GridPosition(x = 0, y = 0), Orientation.SOUTH)
.instructed("R")
.should {
face(Orientation.WEST)
}
@Ignore
@Test
fun `rotating clockwise - changes west to north`() =
Robot(GridPosition(x = 0, y = 0), Orientation.WEST)
.instructed("R")
.should {
face(Orientation.NORTH)
}
@Ignore
@Test
fun `rotating counter-clockwise - changes north to west`() =
Robot(GridPosition(x = 0, y = 0), Orientation.NORTH)
.instructed("L")
.should {
face(Orientation.WEST)
}
@Ignore
@Test
fun `rotating counter-clockwise - changes west to south`() =
Robot(GridPosition(x = 0, y = 0), Orientation.WEST)
.instructed("L")
.should {
face(Orientation.SOUTH)
}
@Ignore
@Test
fun `rotating counter-clockwise - changes south to east`() =
Robot(GridPosition(x = 0, y = 0), Orientation.SOUTH)
.instructed("L")
.should {
face(Orientation.EAST)
}
@Ignore
@Test
fun `rotating counter-clockwise - changes east to north`() =
Robot(GridPosition(x = 0, y = 0), Orientation.EAST)
.instructed("L")
.should {
face(Orientation.NORTH)
}
@Ignore
@Test
fun `moving forward - facing north increments Y`() =
Robot(GridPosition(x = 0, y = 0), Orientation.NORTH)
.instructed("A")
.should {
face(Orientation.NORTH)
beAt(x = 0, y = 1)
}
@Ignore
@Test
fun `moving forward - facing south decrements Y`() =
Robot(GridPosition(x = 0, y = 0), Orientation.SOUTH)
.instructed("A")
.should {
face (Orientation.SOUTH)
beAt(x = 0, y = -1)
}
@Ignore
@Test
fun `moving forward - facing east increments X`() =
Robot(GridPosition(x = 0, y = 0), Orientation.EAST)
.instructed("A")
.should {
face (Orientation.EAST)
beAt(x = 1, y = 0)
}
@Ignore
@Test
fun `moving forward - facing west decrements X`() =
Robot(GridPosition(x = 0, y = 0), Orientation.WEST)
.instructed("A")
.should {
face (Orientation.WEST)
beAt(x = -1, y = 0)
}
@Ignore
@Test
fun `series of instructions - moving east and north example`() =
Robot(GridPosition(x = 7, y = 3), Orientation.NORTH)
.instructed("RAALAL")
.should {
face(Orientation.WEST)
beAt(x = 9, y = 4)
}
@Ignore
@Test
fun `series of instructions - moving west and north`() =
Robot(GridPosition(x = 0, y = 0), Orientation.NORTH)
.instructed("LAAARALA")
.should {
face(Orientation.WEST)
beAt(x = -4, y = 1)
}
@Ignore
@Test
fun `series of instructions - moving west and south`() =
Robot(GridPosition(x = 2, y = -7), Orientation.EAST)
.instructed("RRAAAAALA")
.should {
face(Orientation.SOUTH)
beAt(x = -3, y = -8)
}
@Ignore
@Test
fun `series of instructions - moving east and north`() =
Robot(GridPosition(x = 8, y = 4), Orientation.SOUTH)
.instructed("LAAARRRALLLL")
.should {
face(Orientation.NORTH)
beAt(x = 11, y = 5)
}
}
private fun Robot.instructed(moves: String): Robot {
simulate(moves)
return this
}
private fun Robot.should(what: RobotShould.() -> Unit) = what(RobotShould(this))
private class RobotShould(private val robot: Robot) {
fun face(expected: Orientation) = assertEquals(expected, robot.orientation)
fun beAt(x: Int, y: Int) = assertEquals(GridPosition(x = x, y = y), robot.gridPosition)
}
| mit | 56bcb590a4be513364c71a635535395c | 27.042781 | 91 | 0.503432 | 4.071429 | false | true | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/JdkUpdater.kt | 1 | 8308 | // 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.projectRoots.impl.jdkDownloader
import com.intellij.ProjectTopics
import com.intellij.execution.wsl.WslDistributionManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.*
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.ui.configuration.UnknownSdk
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.text.VersionComparatorUtil
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* This extension point is used to collect
* additional [Sdk] instances to check for a possible
* JDK update
*/
private val EP_NAME = ExtensionPointName.create<JdkUpdateCheckContributor>("com.intellij.jdkUpdateCheckContributor")
interface JdkUpdateCheckContributor {
/**
* Executed from any thread (possibly without read-lock) to
* collect SDKs, which should be considered for
* JDK Update check
*/
fun contributeJdks(project: Project): List<Sdk>
}
private fun isEnabled(project: Project) = !project.isDefault &&
Registry.`is`("jdk.updater") &&
!ApplicationManager.getApplication().isUnitTestMode &&
!ApplicationManager.getApplication().isHeadlessEnvironment
internal class JdkUpdaterStartup : StartupActivity.Background {
override fun runActivity(project: Project) {
if (!isEnabled(project)) return
project.service<JdkUpdatesCollector>().updateNotifications()
}
}
private val LOG = logger<JdkUpdatesCollector>()
@Service // project
private class JdkUpdatesCollectorQueue : UnknownSdkCollectorQueue(7_000)
@Service
internal class JdkUpdatesCollector(
private val project: Project
) : Disposable {
override fun dispose() = Unit
init {
schedule()
}
private fun isEnabled() = isEnabled(project)
private fun schedule() {
if (!isEnabled()) return
val future = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay(
Runnable {
if (project.isDisposed) return@Runnable
try {
updateNotifications()
}
catch (t: Throwable) {
if (t is ControlFlowException) return@Runnable
LOG.warn("Failed to complete JDK Update check. ${t.message}", t)
}
},
12,
12,
TimeUnit.HOURS
)
Disposer.register(this, Disposable { future.cancel(false) })
val myLastKnownModificationId = AtomicLong(-100_500)
project.messageBus
.connect(this)
.subscribe(
ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
if (event.isCausedByFileTypesChange) return
//an optimization - we do not scan for JDKs if there we no ProjectRootManager modifications change
//this avoids VirtualFilePointers invalidation
val newCounterValue = ProjectRootManager.getInstance(project).modificationCount
if (myLastKnownModificationId.getAndSet(newCounterValue) == newCounterValue) return
updateNotifications()
}
})
}
fun updateNotifications() {
if (!isEnabled()) return
project.service<JdkUpdatesCollectorQueue>().queue(object: UnknownSdkTrackerTask {
override fun createCollector(): UnknownSdkCollector? {
if (!isEnabled()) return null
return object : UnknownSdkCollector(project) {
override fun getContributors(): List<UnknownSdkContributor> {
return super.getContributors() + EP_NAME.extensionList.map {
object : UnknownSdkContributor {
override fun contributeUnknownSdks(project: Project) = listOf<UnknownSdk>()
override fun contributeKnownSdks(project: Project): List<Sdk> = it.contributeJdks(project)
}
}
}
}
}
override fun onLookupCompleted(snapshot: UnknownSdkSnapshot) {
if (!isEnabled()) return
//this callback happens in the GUI thread!
val knownSdks = snapshot
.knownSdks
.filter { it.sdkType is JavaSdkType && it.sdkType !is DependentSdkType }
if (knownSdks.isEmpty()) return
ProgressManager.getInstance().run(
object : Task.Backgroundable(project, ProjectBundle.message("progress.title.checking.for.jdk.updates"), true, ALWAYS_BACKGROUND) {
override fun run(indicator: ProgressIndicator) {
updateWithSnapshot(knownSdks.distinct().sortedBy { it.name }, indicator)
}
}
)
}
})
}
private fun updateWithSnapshot(knownSdks: List<Sdk>, indicator: ProgressIndicator) {
val jdkFeed by lazy {
val listDownloader = JdkListDownloader.getInstance()
var items = listDownloader.downloadModelForJdkInstaller(predicate = JdkPredicate.default(), progress = indicator)
if (SystemInfo.isWindows && WslDistributionManager.getInstance().installedDistributions.isNotEmpty()) {
@Suppress("SuspiciousCollectionReassignment")
items += listDownloader.downloadModelForJdkInstaller(predicate = JdkPredicate.forWSL(), progress = indicator)
}
items.toList()
}
val notifications = service<JdkUpdaterNotifications>()
val noUpdatesFor = HashSet<Sdk>(knownSdks)
for (jdk in knownSdks) {
val actualItem = JdkInstaller.getInstance().findJdkItemForInstalledJdk(jdk.homePath) ?: continue
val feedItem = jdkFeed.firstOrNull {
it.suggestedSdkName == actualItem.suggestedSdkName && it.arch == actualItem.arch && it.os == actualItem.os
} ?: continue
if (!service<JdkUpdaterState>().isAllowed(jdk, feedItem)) continue
//internal versions are not considered here (JBRs?)
if (VersionComparatorUtil.compare(feedItem.jdkVersion, actualItem.jdkVersion) <= 0) continue
notifications.showNotification(jdk, actualItem, feedItem)
noUpdatesFor -= jdk
}
//handle the case, when a JDK is no longer requires an update
for (jdk in noUpdatesFor) {
notifications.hideNotification(jdk)
}
}
}
@Service //Application service
class JdkUpdaterNotifications : Disposable {
private val lock = ReentrantLock()
private val pendingNotifications = HashMap<Sdk, JdkUpdateNotification>()
override fun dispose() : Unit = lock.withLock {
pendingNotifications.clear()
}
fun showNotification(jdk: Sdk, actualItem: JdkItem, newItem: JdkItem) : Unit = lock.withLock {
val newNotification = JdkUpdateNotification(
jdk = jdk,
oldItem = actualItem,
newItem = newItem,
whenComplete = {
lock.withLock {
pendingNotifications.remove(jdk, it)
}
}
)
val currentNotification = pendingNotifications[jdk]
if (currentNotification != null && !currentNotification.tryReplaceWithNewerNotification(newNotification)) return
pendingNotifications[jdk] = newNotification
newNotification
}.showNotificationIfAbsent()
fun hideNotification(jdk: Sdk) = lock.withLock {
pendingNotifications[jdk]?.tryReplaceWithNewerNotification()
}
}
| apache-2.0 | aaa600c490757bd7c08c67a0fdfbd2d9 | 35.279476 | 140 | 0.715455 | 4.87845 | false | false | false | false |
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/ui/view/app/tabs/admincards/ExportCard.kt | 1 | 3148 | /*
* (C) Copyright 2019 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.view.app.tabs.admincards
import com.faendir.acra.i18n.Messages
import com.faendir.acra.model.App
import com.faendir.acra.model.QReport
import com.faendir.acra.navigation.ParseAppParameter
import com.faendir.acra.navigation.View
import com.faendir.acra.service.DataService
import com.faendir.acra.ui.component.AdminCard
import com.faendir.acra.ui.component.Translatable
import com.faendir.acra.ui.ext.comboBox
import com.faendir.acra.ui.ext.content
import com.faendir.acra.ui.ext.downloadButton
import com.querydsl.core.types.dsl.BooleanExpression
import com.querydsl.core.types.dsl.StringPath
import com.vaadin.flow.server.InputStreamFactory
import com.vaadin.flow.server.StreamResource
import org.springframework.security.core.context.SecurityContextHolder
import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets
@View
class ExportCard(dataService: DataService, @ParseAppParameter app: App) : AdminCard(dataService) {
init {
content {
setHeader(Translatable.createLabel(Messages.EXPORT))
val mailBox = comboBox(dataService.getFromReports(app, QReport.report.userEmail), Messages.BY_MAIL) {
setWidthFull()
}
val idBox = comboBox(dataService.getFromReports(app, QReport.report.installationId), Messages.BY_ID) {
setWidthFull()
}
val authentication = SecurityContextHolder.getContext().authentication
downloadButton(StreamResource("reports.json", InputStreamFactory {
SecurityContextHolder.getContext().authentication = authentication
try {
val where = null.eqIfNotBlank(QReport.report.userEmail, mailBox.value).eqIfNotBlank(QReport.report.installationId, idBox.value)
ByteArrayInputStream(
if (where == null) ByteArray(0) else dataService.getFromReports(app, QReport.report.content, where, sorted = false)
.joinToString(", ", "[", "]").toByteArray(StandardCharsets.UTF_8)
)
} finally {
SecurityContextHolder.getContext().authentication = null
}
}), Messages.DOWNLOAD) {
setSizeFull()
}
}
}
private fun BooleanExpression?.eqIfNotBlank(path: StringPath, value: String?): BooleanExpression? {
return value?.takeIf { it.isNotBlank() }?.let { path.eq(it).and(this) } ?: this
}
} | apache-2.0 | 0160ae9298973111e6ba5da4ca65a174 | 44.637681 | 147 | 0.695997 | 4.372222 | false | false | false | false |
anthonycr/Lightning-Browser | app/src/main/java/acr/browser/lightning/list/RecyclerViewDialogItemAdapter.kt | 1 | 1655 | package acr.browser.lightning.list
import acr.browser.lightning.R
import acr.browser.lightning.dialog.DialogItem
import acr.browser.lightning.extensions.inflater
import android.graphics.PorterDuff
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
/**
* A [RecyclerView.Adapter] that displays [DialogItem] with icons.
*/
class RecyclerViewDialogItemAdapter(
private val listItems: List<DialogItem>
) : RecyclerView.Adapter<DialogItemViewHolder>() {
var onItemClickListener: ((DialogItem) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DialogItemViewHolder =
DialogItemViewHolder(
parent.context.inflater.inflate(R.layout.dialog_list_item, parent, false)
)
override fun getItemCount(): Int = listItems.size
override fun onBindViewHolder(holder: DialogItemViewHolder, position: Int) {
val item = listItems[position]
holder.icon.setImageDrawable(item.icon)
item.colorTint?.let { holder.icon.setColorFilter(it, PorterDuff.Mode.SRC_IN) }
holder.title.setText(item.title)
holder.itemView.setOnClickListener { onItemClickListener?.invoke(item) }
}
}
/**
* A [RecyclerView.ViewHolder] that displays an icon and a title.
*/
class DialogItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
/**
* The icon to display.
*/
val icon: ImageView = view.findViewById(R.id.icon)
/**
* The title to display.
*/
val title: TextView = view.findViewById(R.id.title_text)
}
| mpl-2.0 | 92ba9f256ae1b545b5418226f1d8d932 | 29.648148 | 93 | 0.727492 | 4.298701 | false | false | false | false |
leafclick/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/completion/JavaLangInvokeHandleCompletionTest.kt | 1 | 6118 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInsight.completion
import com.intellij.JavaTestUtil
import com.intellij.codeInsight.completion.LightFixtureCompletionTestCase
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
/**
* @author Pavel Dolgov
*/
class JavaLangInvokeHandleCompletionTest : LightFixtureCompletionTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor = LightJavaCodeInsightFixtureTestCase.JAVA_9
override fun getBasePath() = JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/completion/invokeHandle/"
fun testVirtual() = doTestFirst(1, "m1(int)", "pm1(int)", "m2(float, double)")
fun testVirtualPrefixed() = doTest(1, "m1(int)", "m2(float, double)", "pm1(int)")
fun testStatic() = doTest(0, "psm1(char)", "sm1(char)", "sm2(short)")
fun testGetter() = doTest(0, "f1", "pf1", "f2")
fun testSetter() = doTest(2, "f1", "pf1", "f2")
fun testStaticGetter() = doTest(0, "psf1", "sf1", "sf2")
fun testStaticSetter() = doTest(2, "psf1", "sf1", "sf2")
fun testVarHandle() = doTest(0, "f1", "pf1", "f2")
fun testStaticVarHandle() = doTest(0, "psf1", "sf1", "sf2")
fun testOverloaded() = doTestTypes(1, "strMethod()", "strMethod(int, int)")
fun testVirtualType() = doTestTypes(0, "MethodType.methodType(String.class)", "MethodType.methodType(String.class, int.class, int.class)")
fun testStaticType() = doTestTypes(1,
"MethodType.methodType(Object.class, int.class, int.class)",
"MethodType.methodType(Object.class, Object.class)")
fun testGetterType() = doTestTypes(0, "int.class")
fun testSetterType() = doTestTypes(0, "float.class")
fun testVarHandleType() = doTestTypes(0, "String.class")
fun testStaticVarHandleType() = doTestTypes(0, "Object.class")
fun testVirtualTypeGeneric() = doTestTypes(0, "MethodType.methodType(Object.class, Object.class, String.class)")
fun testStaticTypeGeneric() = doTestTypes(0, "MethodType.methodType(Object.class, List.class, Object[].class)")
fun testConstructorType1() = doTestTypes(0, "MethodType.methodType(void.class)")
fun testConstructorType2() = doTestTypes(0,
"MethodType.methodType(void.class)",
"MethodType.methodType(void.class, int.class)",
"MethodType.methodType(void.class, List.class)",
"MethodType.methodType(void.class, Object[].class)")
fun testConstructorType3() = doTestTypes(3,
"MethodType.methodType(void.class)",
"MethodType.methodType(void.class, int.class)",
"MethodType.methodType(void.class, List.class)",
"MethodType.methodType(void.class, Object[].class)")
private fun doTest(index: Int, vararg expected: String) {
doTest(index, { assertLookupTexts(false, *expected) })
}
private fun doTestFirst(index: Int, vararg expected: String) {
doTest(index, { assertLookupTexts(true, *expected, "clone()") })
}
private fun doTestTypes(index: Int, vararg expected: String) {
myFixture.addClass("""
import java.util.List;
public class Types extends Parent {
String str;
static Object sObj;
String strMethod() {return "";}
String strMethod(int n, int m) {return "";}
static String strMethod(int n) {return "";}
static Object objMethod(Object o) {return o;}
static Object objMethod(int n, int m) {return n;}
Object objMethod(int n) {return n;}
<T> T genericMethod(T t, String s) {return t;}
static <T> T sGenericMethod(List<T> lst, T... ts) {return ts[0];}
}""")
myFixture.addClass("""
import java.util.List;
public class Constructed<T> {
Constructed() {}
Constructed(int n) {}
Constructed(List<T> a) {}
Constructed(T... a) {}
}""")
doTest(index, { assertLookupTexts(true, *expected) })
}
private fun assertLookupTexts(compareFirst: Boolean, vararg expected: String) {
val elements = myFixture.lookupElements
assertNotNull(elements)
val lookupTexts = elements!!.map {
val presentation = LookupElementPresentation.renderElement(it)
(presentation.itemText ?: "") + (presentation.tailText ?: "")
}
val actual = if (compareFirst) lookupTexts.subList(0, Math.min(expected.size, lookupTexts.size)) else lookupTexts
assertOrderedEquals(actual, *expected)
}
private fun doTest(index: Int, assertion: () -> Unit) {
myFixture.addClass("""
public class Parent {
public int pf1;
private float pf2;
public static char psf1;
private static short psf2;
public void pm1(int n) {}
private void pm2(float n, double m) {}
public static void psm1(char n) {}
private static void psm2(short n) {}
}""")
myFixture.addClass("""
public class Test extends Parent {
public int f1;
private float f2;
public static char sf1;
private static short sf2;
public void m1(int n) {}
private void m2(float n, double m) {}
public static void sm1(char n) {}
private static void sm2(short n) {}
}""")
configureByFile(getTestName(false) + ".java")
assertion()
if (index >= 0) selectItem(lookup.items[index])
myFixture.checkResultByFile(getTestName(false) + "_after.java")
}
}
| apache-2.0 | 5a813209c6223ff03197d0a5b2ab8efa | 37.477987 | 140 | 0.667375 | 3.990868 | false | true | false | false |
alibaba/transmittable-thread-local | ttl2-compatible/src/test/java/com/alibaba/demo/distributed_tracer/weakref/DistributedTracerUseDemo_WeakReferenceInsteadOfRefCounter.kt | 2 | 4173 | package com.alibaba.demo.distributed_tracer.weakref
import com.alibaba.expandThreadPool
import com.alibaba.ttl.TransmittableThreadLocal
import com.alibaba.ttl.threadpool.TtlExecutors
import java.lang.Thread.sleep
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import kotlin.concurrent.thread
private val executorService: ExecutorService = Executors.newFixedThreadPool(1) { r: Runnable ->
Thread(r, "Executors").apply { isDaemon = true }
}.let {
// ensure threads in pool is pre-created.
expandThreadPool(it)
TtlExecutors.getTtlExecutorService(it)
}!!
/**
* DistributedTracer(DT) use demo.
*
* @author Jerry Lee (oldratlee at gmail dot com)
*/
fun main() {
for (i in 0..42) {
rpcInvokeIn()
}
println("WARN: finished rpc invocation")
// help to check GC status
sleep(200)
println("WARN: Call System.gc")
System.gc()
println("WARN: Called System.gc")
sleep(100)
println("Exit Main.")
}
///////////////////////////////////////////////////////////////////////
private fun rpcInvokeIn() {
////////////////////////////////////////////////
// DistributedTracer Framework Code
////////////////////////////////////////////////
// Get Trace Id and Span Id from RPC Context
val traceId = "traceId_XXXYYY" + traceIdCounter.getAndIncrement()
val baseSpanId = "1.1"
val leafSpanIdInfo = LeafSpanIdInfo()
transferInfo.set(DtTransferInfo(traceId, baseSpanId, leafSpanIdInfo))
////////////////////////////////////////////////
// Biz Code
////////////////////////////////////////////////
syncMethod()
////////////////////////////////////////////////
// DistributedTracer Framework Code
////////////////////////////////////////////////
System.out.printf("Finished Rpc call %s with span %s.%n", traceId, leafSpanIdInfo)
// release context in ThreadLocal, avoid to be hold by thread, GC friendly.
transferInfo.remove()
}
private fun syncMethod() {
// async call by TTL Executor, Test OK!
executorService.submit { asyncMethod() }
// async call by new Thread
thread(name = "Thread-by-new") { syncMethod_ByNewThread() }
invokeServerWithRpc("server 1")
}
private fun asyncMethod() {
sleep(3)
invokeServerWithRpc("server 2")
}
private fun syncMethod_ByNewThread() {
sleep(2)
invokeServerWithRpc("server 3")
}
// RPC invoke
private fun invokeServerWithRpc(server: String) {
////////////////////////////////////////////////
// DistributedTracer Framework Code
////////////////////////////////////////////////
val leafSpanCurrent = increaseLeafSpanCurrentAndReturn()
// Set RpcContext
// Mocked, should use RPC util to get Rpc Context instead
val rpcContext = ConcurrentHashMap<String, String>()
rpcContext["traceId"] = transferInfo.get()!!.traceId
rpcContext["spanId"] = transferInfo.get()!!.baseSpanId + "." + leafSpanCurrent
// Do Rpc
// ...
System.out.printf("Do Rpc invocation to server %s with %s%n", server, rpcContext)
}
///////////////////////////////////////////////////////////////////////
// Span id management
///////////////////////////////////////////////////////////////////////
private val traceIdCounter = AtomicLong()
internal data class LeafSpanIdInfo(val current: AtomicInteger = AtomicInteger(1))
internal data class DtTransferInfo(val traceId: String, val baseSpanId: String, val leafSpanIdInfo: LeafSpanIdInfo) {
// Output GC operation
// How to implement finalize() in kotlin? - https://stackoverflow.com/questions/43784161
@Suppress("unused", "ProtectedInFinal")
protected fun finalize() {
System.out.printf("DEBUG: gc DtTransferInfo traceId %s in thread %s: %s%n",
traceId, Thread.currentThread().name, this)
}
}
private val transferInfo = TransmittableThreadLocal<DtTransferInfo>()
private fun increaseLeafSpanCurrentAndReturn(): Int = transferInfo.get()!!.leafSpanIdInfo.current.getAndIncrement()
| apache-2.0 | 6f21a21fc983927330e8f19532de5c7a | 29.683824 | 117 | 0.606278 | 4.439362 | false | false | false | false |
JuliusKunze/kotlin-native | samples/libcurl/src/main/kotlin/org/konan/libcurl/Event.kt | 2 | 761 | package org.konan.libcurl
typealias EventHandler<T> = (T) -> Unit
class Event<T : Any> {
private var handlers = emptyList<EventHandler<T>>()
fun subscribe(handler: EventHandler<T>) {
handlers += handler
}
fun unsubscribe(handler: EventHandler<T>) {
handlers -= handler
}
operator fun plusAssign(handler: EventHandler<T>) = subscribe(handler)
operator fun minusAssign(handler: EventHandler<T>) = unsubscribe(handler)
operator fun invoke(value: T) {
var exception: Throwable? = null
for (handler in handlers) {
try {
handler(value)
} catch (e: Throwable) {
exception = e
}
}
exception?.let { throw it }
}
} | apache-2.0 | ad7e9bb0e490d4f69eac28840df1953d | 25.275862 | 77 | 0.582129 | 4.502959 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/defaultValues/lambdaInlining/callableReferences/boundPropertyReferenceOnInt.kt | 1 | 354 | // FILE: 1.kt
// LANGUAGE_VERSION: 1.2
// SKIP_INLINE_CHECK_IN: inlineFun$default
package test
val Int.myInc
get() = this + 1
inline fun inlineFun(lambda: () -> Int = 1::myInc): Int {
return lambda()
}
// FILE: 2.kt
import test.*
fun box(): String {
val result = inlineFun()
return if (result == 2) return "OK" else "fail $result"
} | apache-2.0 | 2311a77282f7bbc106e256a01443f800 | 15.904762 | 59 | 0.618644 | 3.051724 | false | true | false | false |
GlobalTechnology/android-gto-support | gto-support-okta/src/main/kotlin/org/ccci/gto/android/common/okta/oidc/storage/security/NoopEncryptionManager.kt | 2 | 750 | package org.ccci.gto.android.common.okta.oidc.storage.security
import android.content.Context
import com.okta.oidc.storage.security.EncryptionManager
import javax.crypto.Cipher
object NoopEncryptionManager : EncryptionManager {
override fun isHardwareBackedKeyStore() = false
override fun isUserAuthenticatedOnDevice() = true
override fun encrypt(value: String?) = value
override fun decrypt(value: String?) = value
override fun getHashed(value: String?) = value
override fun isValidKeys() = false
override fun recreateKeys(context: Context?) = Unit
override fun removeKeys() = Unit
override fun setCipher(cipher: Cipher?) = Unit
override fun getCipher() = null
override fun recreateCipher() = Unit
}
| mit | 0d89d439487928e7e6fe9dbb1318f15e | 33.090909 | 62 | 0.752 | 4.43787 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/UselessCallOnCollectionInspection.kt | 2 | 5236 | // 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.collections
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.quickfix.ReplaceSelectorOfQualifiedExpressionFix
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.calls.inference.model.TypeVariableTypeConstructor
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isFlexible
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
class UselessCallOnCollectionInspection : AbstractUselessCallInspection() {
override val uselessFqNames = mapOf(
"kotlin.collections.filterNotNull" to deleteConversion,
"kotlin.sequences.filterNotNull" to deleteConversion,
"kotlin.collections.filterIsInstance" to deleteConversion,
"kotlin.sequences.filterIsInstance" to deleteConversion,
"kotlin.collections.mapNotNull" to Conversion("map"),
"kotlin.sequences.mapNotNull" to Conversion("map"),
"kotlin.collections.mapNotNullTo" to Conversion("mapTo"),
"kotlin.sequences.mapNotNullTo" to Conversion("mapTo"),
"kotlin.collections.mapIndexedNotNull" to Conversion("mapIndexed"),
"kotlin.sequences.mapIndexedNotNull" to Conversion("mapIndexed"),
"kotlin.collections.mapIndexedNotNullTo" to Conversion("mapIndexedTo"),
"kotlin.sequences.mapIndexedNotNullTo" to Conversion("mapIndexedTo")
)
override val uselessNames = uselessFqNames.keys.toShortNames()
override fun QualifiedExpressionVisitor.suggestConversionIfNeeded(
expression: KtQualifiedExpression,
calleeExpression: KtExpression,
context: BindingContext,
conversion: Conversion
) {
val receiverType = expression.receiverExpression.getType(context) ?: return
val receiverTypeArgument = receiverType.arguments.singleOrNull()?.type ?: return
val resolvedCall = expression.getResolvedCall(context) ?: return
if (calleeExpression.text == "filterIsInstance") {
val typeParameterDescriptor = resolvedCall.candidateDescriptor.typeParameters.singleOrNull() ?: return
val argumentType = resolvedCall.typeArguments[typeParameterDescriptor] ?: return
if (receiverTypeArgument.isFlexible() || !receiverTypeArgument.isSubtypeOf(argumentType)) return
} else {
// xxxNotNull
if (TypeUtils.isNullableType(receiverTypeArgument)) return
if (calleeExpression.text != "filterNotNull") {
// Also check last argument functional type to have not-null result
val lastParameterMatches = resolvedCall.hasLastFunctionalParameterWithResult(context) {
!TypeUtils.isNullableType(it) && it.constructor !is TypeVariableTypeConstructor
}
if (!lastParameterMatches) return
}
}
val newName = conversion.replacementName
if (newName != null) {
val descriptor = holder.manager.createProblemDescriptor(
expression,
TextRange(
expression.operationTokenNode.startOffset - expression.startOffset,
calleeExpression.endOffset - expression.startOffset
),
KotlinBundle.message("call.on.collection.type.may.be.reduced"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
RenameUselessCallFix(newName)
)
holder.registerProblem(descriptor)
} else {
val fix = if (resolvedCall.resultingDescriptor.returnType.isList() && !receiverType.isList()) {
ReplaceSelectorOfQualifiedExpressionFix("toList()")
} else {
RemoveUselessCallFix()
}
val descriptor = holder.manager.createProblemDescriptor(
expression,
TextRange(
expression.operationTokenNode.startOffset - expression.startOffset,
calleeExpression.endOffset - expression.startOffset
),
KotlinBundle.message("useless.call.on.collection.type"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
isOnTheFly,
fix
)
holder.registerProblem(descriptor)
}
}
private fun KotlinType?.isList() = this?.constructor?.declarationDescriptor?.fqNameSafe == StandardNames.FqNames.list
}
| apache-2.0 | 294d7a40b8d342d1a7952da006ea281a | 49.834951 | 158 | 0.699771 | 5.58209 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/shops/PurchaseDialogQuestContent.kt | 1 | 5615 | package com.habitrpg.android.habitica.ui.views.shops
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView
import com.facebook.drawee.view.SimpleDraweeView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.models.inventory.QuestContent
import com.habitrpg.android.habitica.models.inventory.QuestDropItem
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
class PurchaseDialogQuestContent : PurchaseDialogContent {
private val questDetailView: View by bindView(R.id.questDetailView)
private val questTypeTextView: TextView by bindView(R.id.questTypeTextView)
private val bossHealthView: View by bindView(R.id.boss_health_view)
private val bossHealthTextView: TextView by bindView(R.id.boss_health_text)
private val questCollectView: View by bindView(R.id.quest_collect_view)
private val questCollectTextView: TextView by bindView(R.id.quest_collect_text)
private val questDifficultyView: RatingBar by bindView(R.id.quest_difficulty_view)
private val rageMeterView: View by bindView(R.id.rage_meter_view)
private val rewardsList: ViewGroup by bindView(R.id.rewardsList)
private val ownerRewardsTitle: View by bindView(R.id.ownerRewardsTitle)
private val ownerRewardsList: ViewGroup by bindView(R.id.ownerRewardsList)
override val viewId: Int
get() = R.layout.dialog_purchase_content_quest
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
fun setQuestContent(questContent: QuestContent) {
rageMeterView.visibility = View.GONE
if (questContent.isBossQuest) {
questTypeTextView.setText(R.string.boss_quest)
questCollectView.visibility = View.GONE
bossHealthTextView.text = questContent.boss?.hp.toString()
if (questContent.boss?.hasRage() == true) {
rageMeterView.visibility = View.VISIBLE
}
questDifficultyView.rating = questContent.boss?.str ?: 1f
} else {
questTypeTextView.setText(R.string.collection_quest)
val collectionList = questContent.collect?.map { it.count.toString() + " " + it.text }
questCollectTextView.text = TextUtils.join(", ", collectionList ?: listOf<String>())
bossHealthView.visibility = View.GONE
questDifficultyView.rating = 1f
}
questDetailView.visibility = View.VISIBLE
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as? LayoutInflater
if (questContent.drop != null && questContent.drop?.items != null) {
questContent.drop?.items
?.filterNot { it.isOnlyOwner }
?.forEach { addRewardsRow(inflater, it, rewardsList) }
var hasOwnerRewards = false
for (item in questContent.drop?.items ?: emptyList<QuestDropItem>()) {
if (item.isOnlyOwner) {
addRewardsRow(inflater, item, ownerRewardsList)
hasOwnerRewards = true
}
}
if (!hasOwnerRewards) {
ownerRewardsTitle.visibility = View.GONE
ownerRewardsList.visibility = View.GONE
}
if (questContent.drop?.exp ?: 0 > 0) {
val view = inflater?.inflate(R.layout.row_quest_reward_imageview, rewardsList, false) as? ViewGroup
val imageView = view?.findViewById<ImageView>(R.id.imageView)
imageView?.scaleType = ImageView.ScaleType.CENTER
imageView?.setImageBitmap(HabiticaIconsHelper.imageOfExperienceReward())
val titleTextView = view?.findViewById<TextView>(R.id.titleTextView)
titleTextView?.text = context.getString(R.string.experience_reward, questContent.drop?.exp)
rewardsList.addView(view)
}
if (questContent.drop?.gp ?: 0 > 0) {
val view = inflater?.inflate(R.layout.row_quest_reward_imageview, rewardsList, false) as? ViewGroup
val imageView = view?.findViewById<ImageView>(R.id.imageView)
imageView?.scaleType = ImageView.ScaleType.CENTER
imageView?.setImageBitmap(HabiticaIconsHelper.imageOfGoldReward())
val titleTextView = view?.findViewById<TextView>(R.id.titleTextView)
titleTextView?.text = context.getString(R.string.gold_reward, questContent.drop?.gp)
rewardsList.addView(view)
}
}
}
private fun addRewardsRow(inflater: LayoutInflater?, item: QuestDropItem, containerView: ViewGroup?) {
val view = inflater?.inflate(R.layout.row_quest_reward, containerView, false) as? ViewGroup
val imageView = view?.findViewById(R.id.imageView) as? SimpleDraweeView
val titleTextView = view?.findViewById(R.id.titleTextView) as? TextView
DataBindingUtils.loadImage(imageView, item.imageName)
if (item.count > 1) {
titleTextView?.text = context.getString(R.string.quest_reward_count, item.text, item.count)
} else {
titleTextView?.text = item.text
}
containerView?.addView(view)
}
}
| gpl-3.0 | d586db8882e6cec57ac43f32b1fdb7fc | 47.405172 | 115 | 0.681745 | 4.517297 | false | false | false | false |
MER-GROUP/intellij-community | platform/built-in-server/src/org/jetbrains/io/fastCgi/FastCgiService.kt | 4 | 6426 | /*
* Copyright 2000-2014 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.io.fastCgi
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.util.Consumer
import com.intellij.util.containers.ConcurrentIntObjectMap
import com.intellij.util.containers.ContainerUtil
import io.netty.bootstrap.Bootstrap
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import io.netty.handler.codec.http.*
import org.jetbrains.builtInWebServer.SingleConnectionNetService
import org.jetbrains.concurrency.Promise
import org.jetbrains.io.*
import java.util.concurrent.atomic.AtomicInteger
val LOG: Logger = Logger.getInstance(FastCgiService::class.java)
// todo send FCGI_ABORT_REQUEST if client channel disconnected
abstract class FastCgiService(project: Project) : SingleConnectionNetService(project) {
private val requestIdCounter = AtomicInteger()
protected val requests: ConcurrentIntObjectMap<Channel> = ContainerUtil.createConcurrentIntObjectMap<Channel>()
override fun configureBootstrap(bootstrap: Bootstrap, errorOutputConsumer: Consumer<String>) {
bootstrap.handler {
it.pipeline().addLast("fastCgiDecoder", FastCgiDecoder(errorOutputConsumer, this@FastCgiService))
it.pipeline().addLast("exceptionHandler", ChannelExceptionHandler.getInstance())
it.closeFuture().addListener {
requestIdCounter.set(0)
if (!requests.isEmpty()) {
val waitingClients = requests.elements().toList()
requests.clear()
for (channel in waitingClients) {
sendBadGateway(channel)
}
}
}
}
}
fun send(fastCgiRequest: FastCgiRequest, content: ByteBuf) {
val notEmptyContent: ByteBuf?
if (content.isReadable()) {
content.retain()
notEmptyContent = content
notEmptyContent.touch()
}
else {
notEmptyContent = null
}
try {
val promise: Promise<*>
if (processHandler.has()) {
val channel = processChannel.get()
if (channel == null || !channel.isOpen) {
// channel disconnected for some reason
promise = connectAgain()
}
else {
fastCgiRequest.writeToServerChannel(notEmptyContent, channel)
return
}
}
else {
promise = processHandler.get()
}
promise
.done { fastCgiRequest.writeToServerChannel(notEmptyContent, processChannel.get()!!) }
.rejected {
Promise.logError(LOG, it)
handleError(fastCgiRequest, notEmptyContent)
}
}
catch (e: Throwable) {
LOG.error(e)
handleError(fastCgiRequest, notEmptyContent)
}
}
private fun handleError(fastCgiRequest: FastCgiRequest, content: ByteBuf?) {
try {
if (content != null && content.refCnt() != 0) {
content.release()
}
}
finally {
val channel = requests.remove(fastCgiRequest.requestId)
if (channel != null) {
sendBadGateway(channel)
}
}
}
fun allocateRequestId(channel: Channel): Int {
var requestId = requestIdCounter.getAndIncrement()
if (requestId >= java.lang.Short.MAX_VALUE) {
requestIdCounter.set(0)
requestId = requestIdCounter.getAndDecrement()
}
requests.put(requestId, channel)
return requestId
}
fun responseReceived(id: Int, buffer: ByteBuf?) {
val channel = requests.remove(id)
if (channel == null || !channel.isActive) {
buffer?.release()
return
}
if (buffer == null) {
Responses.sendStatus(HttpResponseStatus.BAD_GATEWAY, channel)
return
}
val httpResponse = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer)
try {
parseHeaders(httpResponse, buffer)
Responses.addServer(httpResponse)
if (!HttpUtil.isContentLengthSet(httpResponse)) {
HttpUtil.setContentLength(httpResponse, buffer.readableBytes().toLong())
}
}
catch (e: Throwable) {
buffer.release()
try {
LOG.error(e)
}
finally {
Responses.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR, channel)
}
return
}
channel.writeAndFlush(httpResponse)
}
}
private fun sendBadGateway(channel: Channel) {
try {
if (channel.isActive()) {
Responses.sendStatus(HttpResponseStatus.BAD_GATEWAY, channel)
}
}
catch (e: Throwable) {
NettyUtil.log(e, LOG)
}
}
private fun parseHeaders(response: HttpResponse, buffer: ByteBuf) {
val builder = StringBuilder()
while (buffer.isReadable) {
builder.setLength(0)
var key: String? = null
var valueExpected = true
while (true) {
val b = buffer.readByte().toInt()
if (b < 0 || b.toChar() == '\n') {
break
}
if (b.toChar() != '\r') {
if (valueExpected && b.toChar() == ':') {
valueExpected = false
key = builder.toString()
builder.setLength(0)
MessageDecoder.skipWhitespace(buffer)
}
else {
builder.append(b.toChar())
}
}
}
if (builder.length == 0) {
// end of headers
return
}
// skip standard headers
if (key.isNullOrEmpty() || key!!.startsWith("http", ignoreCase = true) || key!!.startsWith("X-Accel-", ignoreCase = true)) {
continue
}
val value = builder.toString()
if (key!!.equals("status", ignoreCase = true)) {
val index = value.indexOf(' ')
if (index == -1) {
LOG.warn("Cannot parse status: " + value)
response.setStatus(HttpResponseStatus.OK)
}
else {
response.setStatus(HttpResponseStatus.valueOf(Integer.parseInt(value.substring(0, index))))
}
}
else if (!(key.startsWith("http") || key.startsWith("HTTP"))) {
response.headers().add(key, value)
}
}
} | apache-2.0 | f6bf7fc49d95831da17d7ba36d65fe5e | 28.213636 | 128 | 0.652505 | 4.410432 | false | false | false | false |
jwren/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/ShowStandaloneDiffFromLogActionProvider.kt | 4 | 1170 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.vcs.log.ui.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionExtensionProvider
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
class ShowStandaloneDiffFromLogActionProvider : AnActionExtensionProvider {
override fun isActive(e: AnActionEvent): Boolean {
return e.getData(VcsLogInternalDataKeys.MAIN_UI) != null && e.getData(ChangesBrowserBase.DATA_KEY) == null
}
override fun update(e: AnActionEvent) {
val project = e.project
val logUi = e.getData(VcsLogInternalDataKeys.MAIN_UI)
if (project == null || logUi == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isVisible = true
e.presentation.isEnabled = logUi.changesBrowser.canShowDiff()
}
override fun actionPerformed(e: AnActionEvent) {
ChangesBrowserBase.showStandaloneDiff(e.project!!, e.getRequiredData(VcsLogInternalDataKeys.MAIN_UI).changesBrowser)
}
} | apache-2.0 | d775f71cf1be0d0c6ddb3238b595621e | 40.821429 | 120 | 0.775214 | 4.415094 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/impl/converters/records/ProtoToRecordUtils.kt | 3 | 4491 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:RestrictTo(RestrictTo.Scope.LIBRARY)
package androidx.health.connect.client.impl.converters.records
import androidx.annotation.RestrictTo
import androidx.health.connect.client.records.metadata.DataOrigin
import androidx.health.connect.client.records.metadata.Device
import androidx.health.connect.client.records.metadata.Metadata
import androidx.health.platform.client.proto.DataProto
import androidx.health.platform.client.proto.DataProto.DataPointOrBuilder
import androidx.health.platform.client.proto.DataProto.SeriesValueOrBuilder
import java.time.Instant
import java.time.ZoneOffset
/** Internal helper functions to convert proto to records. */
@get:SuppressWarnings("GoodTime") // Safe to use for deserialization
internal val DataProto.DataPoint.startTime: Instant
get() = Instant.ofEpochMilli(startTimeMillis)
@get:SuppressWarnings("GoodTime") // Safe to use for deserialization
internal val DataProto.DataPoint.endTime: Instant
get() = Instant.ofEpochMilli(endTimeMillis)
@get:SuppressWarnings("GoodTime") // Safe to use for deserialization
internal val DataProto.DataPoint.time: Instant
get() = Instant.ofEpochMilli(instantTimeMillis)
@get:SuppressWarnings("GoodTime") // Safe to use for deserialization
internal val DataProto.DataPoint.startZoneOffset: ZoneOffset?
get() =
if (hasStartZoneOffsetSeconds()) ZoneOffset.ofTotalSeconds(startZoneOffsetSeconds) else null
@get:SuppressWarnings("GoodTime") // Safe to use for deserialization
internal val DataProto.DataPoint.endZoneOffset: ZoneOffset?
get() = if (hasEndZoneOffsetSeconds()) ZoneOffset.ofTotalSeconds(endZoneOffsetSeconds) else null
@get:SuppressWarnings("GoodTime") // HealthDataClientImplSafe to use for deserialization
internal val DataProto.DataPoint.zoneOffset: ZoneOffset?
get() = if (hasZoneOffsetSeconds()) ZoneOffset.ofTotalSeconds(zoneOffsetSeconds) else null
internal fun DataPointOrBuilder.getLong(key: String, defaultVal: Long = 0): Long =
valuesMap[key]?.longVal ?: defaultVal
internal fun DataPointOrBuilder.getDouble(key: String, defaultVal: Double = 0.0): Double =
valuesMap[key]?.doubleVal ?: defaultVal
internal fun DataPointOrBuilder.getString(key: String): String? = valuesMap[key]?.stringVal
internal fun DataPointOrBuilder.getEnum(key: String): String? {
return valuesMap[key]?.enumVal
}
/** Maps a string enum field to public API integers. */
internal fun DataPointOrBuilder.mapEnum(
key: String,
stringToIntMap: Map<String, Int>,
default: Int
): Int {
val value = getEnum(key) ?: return default
return stringToIntMap.getOrDefault(value, default)
}
internal fun SeriesValueOrBuilder.getLong(key: String, defaultVal: Long = 0): Long =
valuesMap[key]?.longVal ?: defaultVal
internal fun SeriesValueOrBuilder.getDouble(key: String, defaultVal: Double = 0.0): Double =
valuesMap[key]?.doubleVal ?: defaultVal
internal fun SeriesValueOrBuilder.getString(key: String): String? = valuesMap[key]?.stringVal
internal fun SeriesValueOrBuilder.getEnum(key: String): String? = valuesMap[key]?.enumVal
@get:SuppressWarnings("GoodTime") // Safe to use for deserialization
internal val DataProto.DataPoint.metadata: Metadata
get() =
Metadata(
id = if (hasUid()) uid else Metadata.EMPTY_ID,
dataOrigin = DataOrigin(dataOrigin.applicationId),
lastModifiedTime = Instant.ofEpochMilli(updateTimeMillis),
clientRecordId = if (hasClientId()) clientId else null,
clientRecordVersion = clientVersion,
device = device.toDevice()
)
internal fun DataProto.Device.toDevice(): Device {
return Device(
manufacturer = if (hasManufacturer()) manufacturer else null,
model = if (hasModel()) model else null,
type = DEVICE_TYPE_STRING_TO_INT_MAP.getOrDefault(type, Device.TYPE_UNKNOWN)
)
}
| apache-2.0 | 0c4678f6618773422c7b74694f123964 | 41.367925 | 100 | 0.759296 | 4.347531 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/ExtensionParentTest.kt | 5 | 3178 | package com.intellij.workspaceModel.storage
import com.intellij.workspaceModel.storage.entities.test.api.AttachedEntityToParent
import com.intellij.workspaceModel.storage.entities.test.api.MainEntityToParent
import com.intellij.workspaceModel.storage.entities.test.api.MySource
import com.intellij.workspaceModel.storage.entities.test.api.ref
import com.intellij.workspaceModel.storage.entities.test.api.modifyEntity
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class ExtensionParentTest {
@Test
fun `access by extension`() {
val builder = createEmptyBuilder()
builder.addEntity(AttachedEntityToParent("xyz", MySource) {
ref = MainEntityToParent("123", MySource)
})
val child: AttachedEntityToParent = builder.toSnapshot().entities(MainEntityToParent::class.java).single().child!!
assertEquals("xyz", child.data)
assertTrue(builder.entities(MainEntityToParent::class.java).toList().isNotEmpty())
assertTrue(builder.entities(AttachedEntityToParent::class.java).toList().isNotEmpty())
}
@Test
fun `access by extension without builder`() {
val entity = AttachedEntityToParent("xyz", MySource) {
ref = MainEntityToParent("123", MySource)
}
assertEquals("xyz", entity.data)
val ref = entity.ref
val children = ref.child!!
assertEquals("xyz", children.data)
}
@Test
fun `access by extension opposite`() {
val builder = createEmptyBuilder()
builder.addEntity(MainEntityToParent("123", MySource) {
this.child = AttachedEntityToParent("xyz", MySource)
})
val child: AttachedEntityToParent = builder.toSnapshot().entities(MainEntityToParent::class.java).single().child!!
assertEquals("xyz", child.data)
assertTrue(builder.entities(MainEntityToParent::class.java).toList().isNotEmpty())
assertTrue(builder.entities(AttachedEntityToParent::class.java).toList().isNotEmpty())
}
@Test
fun `access by extension opposite in builder`() {
val builder = createEmptyBuilder()
val entity = MainEntityToParent("123", MySource) {
this.child = AttachedEntityToParent("xyz", MySource)
}
builder.addEntity(entity)
assertEquals("xyz", entity.child!!.data)
}
@Test
fun `access by extension opposite in modification`() {
val builder = createEmptyBuilder()
val entity = MainEntityToParent("123", MySource) {
this.child = AttachedEntityToParent("xyz", MySource)
}
builder.addEntity(entity)
val anotherChild = AttachedEntityToParent("abc", MySource)
builder.modifyEntity(entity) {
assertEquals("xyz", this.child!!.data)
this.child = anotherChild
}
assertTrue(builder.entities(MainEntityToParent::class.java).toList().isNotEmpty())
assertEquals("abc", builder.entities(AttachedEntityToParent::class.java).single().data)
}
@Test
fun `access by extension opposite without builder`() {
val entity = MainEntityToParent("123", MySource) {
this.child = AttachedEntityToParent("xyz", MySource)
}
assertEquals("123", entity.x)
val ref = entity.child!!
val children = ref.ref
assertEquals("123", children.x)
}
}
| apache-2.0 | 3933b73defc1d6648a35856239510c0d | 34.311111 | 118 | 0.726558 | 4.585859 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ui/KotlinExtractSuperDialogBase.kt | 4 | 7411 | // 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.refactoring.introduce.extractClass.ui
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.classMembers.MemberInfoChange
import com.intellij.refactoring.extractSuperclass.JavaExtractSuperBaseDialog
import com.intellij.refactoring.util.DocCommentPolicy
import com.intellij.refactoring.util.RefactoringMessageUtil
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.FormBuilder
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.base.util.onTextChange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.psi.unquoteKotlinIdentifier
import org.jetbrains.kotlin.idea.refactoring.introduce.extractClass.ExtractSuperInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberSelectionPanel
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinUsesAndInterfacesDependencyMemberInfoModel
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.psiUtil.isIdentifier
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import java.awt.BorderLayout
import javax.swing.*
abstract class KotlinExtractSuperDialogBase(
protected val originalClass: KtClassOrObject,
protected val targetParent: PsiElement,
private val conflictChecker: (KotlinExtractSuperDialogBase) -> Boolean,
private val isExtractInterface: Boolean,
@Nls refactoringName: String,
private val refactoring: (ExtractSuperInfo) -> Unit
) : JavaExtractSuperBaseDialog(originalClass.project, originalClass.toLightClass()!!, emptyList(), refactoringName) {
private var initComplete: Boolean = false
private lateinit var memberInfoModel: MemberInfoModelBase
val selectedMembers: List<KotlinMemberInfo>
get() = memberInfoModel.memberInfos.filter { it.isChecked }
private val fileNameField = JTextField()
open class MemberInfoModelBase(
originalClass: KtClassOrObject,
val memberInfos: List<KotlinMemberInfo>,
interfaceContainmentVerifier: (KtNamedDeclaration) -> Boolean
) : KotlinUsesAndInterfacesDependencyMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>(
originalClass,
null,
false,
interfaceContainmentVerifier
) {
override fun isMemberEnabled(member: KotlinMemberInfo): Boolean {
val declaration = member.member ?: return false
return !declaration.hasModifier(KtTokens.CONST_KEYWORD)
}
override fun isAbstractEnabled(memberInfo: KotlinMemberInfo): Boolean {
val member = memberInfo.member
return !(member.hasModifier(KtTokens.INLINE_KEYWORD) ||
member.hasModifier(KtTokens.EXTERNAL_KEYWORD) ||
member.hasModifier(KtTokens.LATEINIT_KEYWORD))
}
override fun isFixedAbstract(memberInfo: KotlinMemberInfo?) = true
}
val selectedTargetParent: PsiElement
get() = if (targetParent is PsiDirectory) targetDirectory else targetParent
val targetFileName: String
get() = fileNameField.text
private fun resetFileNameField() {
if (!initComplete) return
fileNameField.text = "$extractedSuperName.${KotlinFileType.EXTENSION}"
}
protected abstract fun createMemberInfoModel(): MemberInfoModelBase
override fun getDocCommentPanelName() = KotlinBundle.message("title.kdoc.for.abstracts")
override fun checkConflicts() = conflictChecker(this)
override fun createActionComponent() = Box.createHorizontalBox()!!
override fun createExtractedSuperNameField(): JTextField {
return super.createExtractedSuperNameField().apply {
onTextChange { resetFileNameField() }
}
}
override fun createDestinationRootPanel(): JPanel? {
if (targetParent !is PsiDirectory) return null
val targetDirectoryPanel = super.createDestinationRootPanel()
val targetFileNamePanel = JPanel(BorderLayout()).apply {
border = BorderFactory.createEmptyBorder(10, 0, 0, 0)
val label = JBLabel(KotlinBundle.message("label.text.target.file.name"))
add(label, BorderLayout.NORTH)
label.labelFor = fileNameField
add(fileNameField, BorderLayout.CENTER)
}
val formBuilder = FormBuilder.createFormBuilder()
if (targetDirectoryPanel != null) {
formBuilder.addComponent(targetDirectoryPanel)
}
return formBuilder.addComponent(targetFileNamePanel).panel
}
override fun createNorthPanel(): JComponent? {
return super.createNorthPanel().apply {
if (targetParent !is PsiDirectory) {
myPackageNameLabel.parent.remove(myPackageNameLabel)
myPackageNameField.parent.remove(myPackageNameField)
}
}
}
override fun createCenterPanel(): JComponent? {
memberInfoModel = createMemberInfoModel().apply {
memberInfoChanged(MemberInfoChange(memberInfos))
}
return JPanel(BorderLayout()).apply {
val memberSelectionPanel = KotlinMemberSelectionPanel(
RefactoringBundle.message(if (isExtractInterface) "members.to.form.interface" else "members.to.form.superclass"),
memberInfoModel.memberInfos,
RefactoringBundle.message("make.abstract")
)
memberSelectionPanel.table.memberInfoModel = memberInfoModel
memberSelectionPanel.table.addMemberInfoChangeListener(memberInfoModel)
add(memberSelectionPanel, BorderLayout.CENTER)
add(myDocCommentPanel, BorderLayout.EAST)
}
}
override fun init() {
super.init()
initComplete = true
resetFileNameField()
}
override fun preparePackage() {
if (targetParent is PsiDirectory) super.preparePackage()
}
override fun isExtractSuperclass() = true
override fun validateName(name: String): String? {
return when {
!name.quoteIfNeeded().isIdentifier() -> RefactoringMessageUtil.getIncorrectIdentifierMessage(name)
name.unquoteKotlinIdentifier() == mySourceClass.name -> KotlinBundle.message("error.text.different.name.expected")
else -> null
}
}
override fun createProcessor() = null
override fun executeRefactoring() {
val extractInfo = ExtractSuperInfo(
mySourceClass.unwrapped as KtClassOrObject,
selectedMembers,
if (targetParent is PsiDirectory) targetDirectory else targetParent,
targetFileName,
extractedSuperName.quoteIfNeeded(),
isExtractInterface,
DocCommentPolicy<PsiComment>(docCommentPolicy)
)
refactoring(extractInfo)
}
} | apache-2.0 | 605b5026d9ceecba0d0548022a0c3421 | 39.282609 | 158 | 0.723654 | 5.366401 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/CreateConstructorAction.kt | 5 | 3425 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.annotator.intentions.elements
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.daemon.QuickFixBundle.message
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.CreateConstructorRequest
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.plugins.groovy.GroovyFileType
import org.jetbrains.plugins.groovy.intentions.base.IntentionUtils.createTemplateForMethod
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
internal class CreateConstructorAction(
targetClass: GrTypeDefinition,
override val request: CreateConstructorRequest
) : CreateMemberAction(targetClass, request) {
override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo {
val targetClass = myTargetPointer.element ?: return IntentionPreviewInfo.EMPTY
val constructor = ConstructorMethodRenderer(project, target, request).renderConstructor()
val className = targetClass.name
return IntentionPreviewInfo.CustomDiff(GroovyFileType.GROOVY_FILE_TYPE, className, "", constructor.text)
}
override fun getFamilyName(): String = message("create.constructor.family")
override fun getText(): String = message("create.constructor.from.new.text")
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
ConstructorMethodRenderer(project, target, request).execute()
}
}
private class ConstructorMethodRenderer(
val project: Project,
val targetClass: GrTypeDefinition,
val request: CreateConstructorRequest
) {
val factory = GroovyPsiElementFactory.getInstance(project)
fun execute() {
var constructor = renderConstructor()
constructor = insertConstructor(constructor)
constructor = forcePsiPostprocessAndRestoreElement(constructor) ?: return
setupTemplate(constructor)
}
private fun setupTemplate(method: GrMethod) {
val parameters = request.expectedParameters
val typeExpressions = setupParameters(method, parameters).toTypedArray()
val nameExpressions = setupNameExpressions(parameters, project).toTypedArray()
createTemplateForMethod(typeExpressions, nameExpressions, method, targetClass, null, true, null)
}
fun renderConstructor(): GrMethod {
val constructor = factory.createConstructor()
val name = targetClass.name
if (name != null) {
constructor.name = name
}
val modifiersToRender = request.modifiers.toMutableList()
modifiersToRender -= JvmModifier.PUBLIC //public by default
for (modifier in modifiersToRender) {
constructor.modifierList.setModifierProperty(modifier.toPsiModifier(), true)
}
for (annotation in request.annotations) {
constructor.modifierList.addAnnotation(annotation.qualifiedName)
}
return constructor
}
private fun insertConstructor(method: GrMethod): GrMethod {
return targetClass.add(method) as GrMethod
}
} | apache-2.0 | bf90ae0c6f1460794a9f4cf8a8aa95ea | 38.37931 | 120 | 0.792701 | 4.913917 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/IrsOwner.kt | 4 | 1685 | // 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.ir.buildsystem
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.plus
import kotlinx.collections.immutable.toPersistentList
interface IrsOwner {
val irs: PersistentList<BuildSystemIR>
fun withReplacedIrs(irs: PersistentList<BuildSystemIR>): IrsOwner
}
@Suppress("UNCHECKED_CAST")
fun <I : IrsOwner> I.withIrs(irs: List<BuildSystemIR>) = withReplacedIrs(irs = this.irs + irs.toPersistentList()) as I
@Suppress("UNCHECKED_CAST")
fun <I : IrsOwner> I.withIrs(vararg irs: BuildSystemIR) = withReplacedIrs(irs = this.irs + irs) as I
@Suppress("UNCHECKED_CAST")
inline fun <I : IrsOwner> I.withoutIrs(filterNot: (BuildSystemIR) -> Boolean): I =
withReplacedIrs(irs = this.irs.filterNot(filterNot).toPersistentList()) as I
inline fun <reified I : BuildSystemIR> IrsOwner.irsOfType(): List<I> =
irs.filterIsInstance<I>().let { irs ->
if (irs.all { it is BuildSystemIRWithPriority })
irs.sortedBy { (it as BuildSystemIRWithPriority).priority }
else irs
}
inline fun <reified I : BuildSystemIR> IrsOwner.irsOfTypeOrNull() =
irsOfType<I>().takeIf { it.isNotEmpty() }
inline fun <reified I : BuildSystemIR> List<BuildSystemIR>.irsOfTypeOrNull() =
filterIsInstance<I>().takeIf { it.isNotEmpty() }
inline fun <reified T : BuildSystemIR> IrsOwner.firstIrOfType() =
irs.firstOrNull { ir -> ir is T } as T?
fun IrsOwner.freeIrs(): List<FreeIR> =
irs.filterIsInstance<FreeIR>()
| apache-2.0 | 6b7d3a9de04c5d2dc00e5280d92025b8 | 37.295455 | 158 | 0.734718 | 3.631466 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/actions/column/TableColumnAlignmentActionsGroup.kt | 3 | 1473 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.editor.tables.actions.column
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DefaultActionGroup
import org.intellij.plugins.markdown.editor.tables.TableModificationUtils.hasCorrectBorders
import org.intellij.plugins.markdown.lang.MarkdownLanguageUtils.isMarkdownLanguage
internal class TableColumnAlignmentActionsGroup: DefaultActionGroup() {
override fun update(event: AnActionEvent) {
val editor = event.getData(CommonDataKeys.EDITOR)
val file = event.getData(CommonDataKeys.PSI_FILE)
val offset = event.getData(CommonDataKeys.CARET)?.offset
if (editor == null
|| file == null
|| offset == null
|| !file.language.isMarkdownLanguage()) {
event.presentation.isEnabledAndVisible = false
return
}
val document = editor.document
val (table, columnIndex) = ColumnBasedTableAction.findTableAndIndex(event, file, document, offset)
event.presentation.isEnabledAndVisible = table != null && columnIndex != null && table.hasCorrectBorders()
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
}
| apache-2.0 | e9a843a8f984773f36562153f8080128 | 43.636364 | 158 | 0.775967 | 4.91 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithLambdaFix.kt | 4 | 4297 | // 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.quickfix
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.buildExpression
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isPrimitiveNumberType
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
class SurroundWithLambdaFix(
expression: KtExpression
) : KotlinQuickFixAction<KtExpression>(expression), HighPriorityAction {
override fun getFamilyName() = text
override fun getText() = KotlinBundle.message("surround.with.lambda")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val nameReference = element ?: return
val newExpression = KtPsiFactory(project).buildExpression {
appendFixedText("{ ")
appendExpression(nameReference)
appendFixedText(" }")
}
nameReference.replace(newExpression)
}
companion object : KotlinSingleIntentionActionFactory() {
private val LOG = Logger.getInstance(SurroundWithLambdaFix::class.java)
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtExpression>? {
val diagnosticFactory = diagnostic.factory
val expectedType: KotlinType
val expressionType: KotlinType
when (diagnosticFactory) {
Errors.TYPE_MISMATCH -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH.cast(diagnostic)
expectedType = diagnosticWithParameters.a
expressionType = diagnosticWithParameters.b
}
Errors.TYPE_MISMATCH_WARNING -> {
val diagnosticWithParameters = Errors.TYPE_MISMATCH_WARNING.cast(diagnostic)
expectedType = diagnosticWithParameters.a
expressionType = diagnosticWithParameters.b
}
Errors.CONSTANT_EXPECTED_TYPE_MISMATCH -> {
val context = (diagnostic.psiFile as KtFile).analyzeWithContent()
val diagnosticWithParameters = Errors.CONSTANT_EXPECTED_TYPE_MISMATCH.cast(diagnostic)
val diagnosticElement = diagnostic.psiElement
if (!(diagnosticElement is KtExpression)) {
LOG.error("Unexpected element: " + diagnosticElement.text)
return null
}
expectedType = diagnosticWithParameters.b
expressionType = context.getType(diagnosticElement) ?: return null
}
else -> {
LOG.error("Unexpected diagnostic: " + DefaultErrorMessages.render(diagnostic))
return null
}
}
if (!expectedType.isFunctionOrSuspendFunctionType) return null
if (expectedType.arguments.size != 1) return null
val lambdaReturnType = expectedType.arguments[0].type
if (!expressionType.makeNotNullable().isSubtypeOf(lambdaReturnType) &&
!(expressionType.isPrimitiveNumberType() && lambdaReturnType.isPrimitiveNumberType())
) return null
val diagnosticElement = diagnostic.psiElement as KtExpression
return SurroundWithLambdaFix(diagnosticElement)
}
}
} | apache-2.0 | 22fc69400aeb80d28ed9a3ff3fce6a23 | 46.755556 | 158 | 0.686293 | 5.767785 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/swapBinaryExpression/multipleOperandsWithDifferentPrecedence.kt | 4 | 55 | fun main() {
val rabbit = 1 == 2 <caret>|| 3 == 5
} | apache-2.0 | 9354358cd23387e2fea1ca964b3359b7 | 17.666667 | 40 | 0.454545 | 2.75 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/export/data/ExportableNote.kt | 1 | 3347 | package com.maubis.scarlet.base.export.data
import android.content.Context
import com.maubis.scarlet.base.config.CoreConfig.Companion.notesDb
import com.maubis.scarlet.base.core.note.INoteContainer
import com.maubis.scarlet.base.core.note.NoteBuilder
import com.maubis.scarlet.base.core.note.generateUUID
import com.maubis.scarlet.base.database.room.note.Note
import com.maubis.scarlet.base.database.room.tag.Tag
import com.maubis.scarlet.base.note.save
import com.maubis.scarlet.base.note.tag.save
import org.json.JSONArray
import org.json.JSONObject
import java.io.Serializable
class ExportableNote(
var uuid: String,
var description: String,
var timestamp: Long,
var updateTimestamp: Long,
var color: Int,
var state: String,
var tags: String,
var meta: Map<String, Any>,
var folder: String
) : Serializable, INoteContainer {
override fun uuid(): String = uuid
override fun description(): String = description
override fun timestamp(): Long = timestamp
override fun updateTimestamp(): Long = updateTimestamp
override fun color(): Int = color
override fun state(): String = state
override fun tags(): String = tags
override fun meta(): Map<String, Any> = emptyMap()
override fun locked(): Boolean = false
override fun pinned(): Boolean = false
override fun folder(): String = folder
constructor(note: Note) : this(
note.uuid,
note.description,
note.timestamp,
note.updateTimestamp,
note.color,
note.state,
note.tags ?: "",
emptyMap(),
note.folder
)
fun saveIfNeeded(context: Context) {
val existingNote = notesDb.existingMatch(this)
if (existingNote !== null && existingNote.updateTimestamp > this.updateTimestamp) {
return
}
val note = NoteBuilder().copy(this)
note.save(context)
}
companion object {
val KEY_NOTES: String = "notes"
fun fromJSONObjectV2(json: JSONObject): ExportableNote {
return ExportableNote(
generateUUID(),
json["description"] as String,
json["timestamp"] as Long,
json["timestamp"] as Long,
json["color"] as Int,
"",
"",
emptyMap(),
"")
}
fun fromJSONObjectV3(json: JSONObject): ExportableNote {
return ExportableNote(
generateUUID(),
json["description"] as String,
json["timestamp"] as Long,
json["timestamp"] as Long,
json["color"] as Int,
json["state"] as String,
convertTagsJSONArrayToString(json["tags"] as JSONArray),
emptyMap(),
"")
}
fun fromJSONObjectV4(json: JSONObject): ExportableNote {
return ExportableNote(
json["uuid"] as String,
json["description"] as String,
json["timestamp"] as Long,
json["timestamp"] as Long,
json["color"] as Int,
json["state"] as String,
convertTagsJSONArrayToString(json["tags"] as JSONArray),
emptyMap(),
"")
}
private fun convertTagsJSONArrayToString(tags: JSONArray): String {
val noteTags = arrayListOf<Tag>()
for (index in 0 until tags.length()) {
val tag = ExportableTag.getBestPossibleTagObject(tags.getJSONObject(index))
tag.save()
noteTags.add(tag)
}
return noteTags.map { it.uuid }.joinToString(separator = ",")
}
}
} | gpl-3.0 | 228c5464f5bf68a0794c6293a1138ebc | 25.784 | 87 | 0.661189 | 4.157764 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinJsGradleModuleConfigurator.kt | 1 | 2434 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.configuration
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.extensions.gradle.*
import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle
import org.jetbrains.kotlin.idea.gradle.configuration.GradleVersionProviderImpl
import org.jetbrains.kotlin.idea.gradleJava.KotlinGradleFacadeImpl
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.idea.versions.MAVEN_JS_STDLIB_ID
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.js.JsPlatforms
class KotlinJsGradleModuleConfigurator : KotlinWithGradleConfigurator() {
override val name: String = "gradle-js"
override val presentableText: String get() = KotlinIdeaGradleBundle.message("presentable.text.javascript.with.gradle")
override val targetPlatform: TargetPlatform = JsPlatforms.defaultJsPlatform
override val kotlinPluginName: String = KOTLIN_JS
override fun getKotlinPluginExpression(forKotlinDsl: Boolean): String =
if (forKotlinDsl) "id(\"kotlin2js\")" else "id 'kotlin2js'"
override fun getMinimumSupportedVersion() = "1.1.0"
override fun getStdlibArtifactName(sdk: Sdk?, version: IdeKotlinVersion): String = MAVEN_JS_STDLIB_ID
override fun addElementsToFile(file: PsiFile, isTopLevelProjectFile: Boolean, version: IdeKotlinVersion): Boolean {
val gradleVersion = GradleVersionProviderImpl.fetchGradleVersion(file)
if (KotlinGradleFacadeImpl.getManipulator(file).useNewSyntax(kotlinPluginName, gradleVersion, GradleVersionProviderImpl)) {
val settingsPsiFile = if (isTopLevelProjectFile) {
file.module?.getTopLevelBuildScriptSettingsPsiFile()
} else {
file.module?.getBuildScriptSettingsPsiFile()
}
if (settingsPsiFile != null) {
KotlinGradleFacadeImpl.getManipulator(settingsPsiFile).addResolutionStrategy(KOTLIN_JS)
}
}
return super.addElementsToFile(file, isTopLevelProjectFile, version)
}
companion object {
@NonNls
const val KOTLIN_JS = "kotlin2js"
}
}
| apache-2.0 | 6d1e9ea13b6060c3224a39ae69b7940f | 47.68 | 131 | 0.761298 | 4.858283 | false | true | false | false |
loxal/FreeEthereum | free-ethereum-core/src/test/java/org/ethereum/net/rlpx/EIP8HandshakeTest.kt | 1 | 13081 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.net.rlpx
import org.ethereum.crypto.ECKey
import org.ethereum.crypto.ECKey.fromPrivate
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.spongycastle.crypto.InvalidCipherTextException
import org.spongycastle.util.encoders.Hex.decode
/**
* @author Mikhail Kalinin
* *
* @since 17.02.2016
*/
class EIP8HandshakeTest {
private val keyA = fromPrivate(decode("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee"))
private val keyB = fromPrivate(decode("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291"))
private val ephemeralKeyB = fromPrivate(decode("e238eb8e04fee6511ab04c6dd3c89ce097b11f25d584863ac2b6d5b35b1847e4"))
private val nonceA = decode("7e968bba13b6c50e2c4cd7f241cc0d64d1ac25c7f5952df231ac6a2bda8ee5d6")
private val nonceB = decode("559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd")
private val signatureA = ECKey.ECDSASignature.fromComponents(
decode("299ca6acfd35e3d72d8ba3d1e2b60b5561d5af5218eb5bc182045769eb422691"),
decode("0a301acae3b369fffc4a4899d6b02531e89fd4fe36a2cf0d93607ba470b50f78"),
27.toByte()
)
private val ephemeralKeyA = fromPrivate(decode("869d6ecf5211f1cc60418a13b9d870b22959d0c16f02bec714c960dd2298a32d"))
private var handshakerA: EncryptionHandshake? = null
private var handshakerB: EncryptionHandshake? = null
@Before
fun setUp() {
handshakerA = EncryptionHandshake(keyB.pubKeyPoint)
handshakerB = EncryptionHandshake(null, ephemeralKeyB, null, nonceB, false)
}
// AuthInitiate EIP-8 format with version 4 and no additional list elements (sent from A to B)
@Test
@Throws(InvalidCipherTextException::class)
fun test1() {
val authMessageData = decode(
"01b304ab7578555167be8154d5cc456f567d5ba302662433674222360f08d5f1534499d3678b513b" +
"0fca474f3a514b18e75683032eb63fccb16c156dc6eb2c0b1593f0d84ac74f6e475f1b8d56116b84" +
"9634a8c458705bf83a626ea0384d4d7341aae591fae42ce6bd5c850bfe0b999a694a49bbbaf3ef6c" +
"da61110601d3b4c02ab6c30437257a6e0117792631a4b47c1d52fc0f8f89caadeb7d02770bf999cc" +
"147d2df3b62e1ffb2c9d8c125a3984865356266bca11ce7d3a688663a51d82defaa8aad69da39ab6" +
"d5470e81ec5f2a7a47fb865ff7cca21516f9299a07b1bc63ba56c7a1a892112841ca44b6e0034dee" +
"70c9adabc15d76a54f443593fafdc3b27af8059703f88928e199cb122362a4b35f62386da7caad09" +
"c001edaeb5f8a06d2b26fb6cb93c52a9fca51853b68193916982358fe1e5369e249875bb8d0d0ec3" +
"6f917bc5e1eafd5896d46bd61ff23f1a863a8a8dcd54c7b109b771c8e61ec9c8908c733c0263440e" +
"2aa067241aaa433f0bb053c7b31a838504b148f570c0ad62837129e547678c5190341e4f1693956c" +
"3bf7678318e2d5b5340c9e488eefea198576344afbdf66db5f51204a6961a63ce072c8926c")
// encode (on A side)
val msg1 = handshakerA!!.createAuthInitiateV4(keyA)
msg1.signature = signatureA
msg1.nonce = nonceA
msg1.version = 4
val encrypted = handshakerA!!.encryptAuthInitiateV4(msg1)
// decode (on B side)
val msg2 = handshakerB!!.decryptAuthInitiateV4(encrypted, keyB)
assertEquals(4, msg2.version.toLong())
assertArrayEquals(nonceA, msg2.nonce)
assertEquals(signatureA.r, msg2.signature.r)
assertEquals(signatureA.s, msg2.signature.s)
assertEquals(signatureA.v.toLong(), msg2.signature.v.toLong())
val msg3 = handshakerB!!.decryptAuthInitiateV4(authMessageData, keyB)
assertEquals(4, msg3.version.toLong())
assertArrayEquals(nonceA, msg3.nonce)
assertEquals(signatureA.r, msg3.signature.r)
assertEquals(signatureA.s, msg3.signature.s)
assertEquals(signatureA.v.toLong(), msg3.signature.v.toLong())
}
// AuthInitiate EIP-8 format with version 56 and 3 additional list elements (sent from A to B)
@Test
@Throws(InvalidCipherTextException::class)
fun test2() {
val authMessageData = decode(
"01b8044c6c312173685d1edd268aa95e1d495474c6959bcdd10067ba4c9013df9e40ff45f5bfd6f7" +
"2471f93a91b493f8e00abc4b80f682973de715d77ba3a005a242eb859f9a211d93a347fa64b597bf" +
"280a6b88e26299cf263b01b8dfdb712278464fd1c25840b995e84d367d743f66c0e54a586725b7bb" +
"f12acca27170ae3283c1073adda4b6d79f27656993aefccf16e0d0409fe07db2dc398a1b7e8ee93b" +
"cd181485fd332f381d6a050fba4c7641a5112ac1b0b61168d20f01b479e19adf7fdbfa0905f63352" +
"bfc7e23cf3357657455119d879c78d3cf8c8c06375f3f7d4861aa02a122467e069acaf513025ff19" +
"6641f6d2810ce493f51bee9c966b15c5043505350392b57645385a18c78f14669cc4d960446c1757" +
"1b7c5d725021babbcd786957f3d17089c084907bda22c2b2675b4378b114c601d858802a55345a15" +
"116bc61da4193996187ed70d16730e9ae6b3bb8787ebcaea1871d850997ddc08b4f4ea668fbf3740" +
"7ac044b55be0908ecb94d4ed172ece66fd31bfdadf2b97a8bc690163ee11f5b575a4b44e36e2bfb2" +
"f0fce91676fd64c7773bac6a003f481fddd0bae0a1f31aa27504e2a533af4cef3b623f4791b2cca6" +
"d490")
val msg2 = handshakerB!!.decryptAuthInitiateV4(authMessageData, keyB)
assertEquals(56, msg2.version.toLong())
assertArrayEquals(nonceA, msg2.nonce)
}
// AuthResponse EIP-8 format with version 4 and no additional list elements (sent from B to A)
@Test
@Throws(InvalidCipherTextException::class)
fun test3() {
val authInitiateData = decode(
"01b304ab7578555167be8154d5cc456f567d5ba302662433674222360f08d5f1534499d3678b513b" +
"0fca474f3a514b18e75683032eb63fccb16c156dc6eb2c0b1593f0d84ac74f6e475f1b8d56116b84" +
"9634a8c458705bf83a626ea0384d4d7341aae591fae42ce6bd5c850bfe0b999a694a49bbbaf3ef6c" +
"da61110601d3b4c02ab6c30437257a6e0117792631a4b47c1d52fc0f8f89caadeb7d02770bf999cc" +
"147d2df3b62e1ffb2c9d8c125a3984865356266bca11ce7d3a688663a51d82defaa8aad69da39ab6" +
"d5470e81ec5f2a7a47fb865ff7cca21516f9299a07b1bc63ba56c7a1a892112841ca44b6e0034dee" +
"70c9adabc15d76a54f443593fafdc3b27af8059703f88928e199cb122362a4b35f62386da7caad09" +
"c001edaeb5f8a06d2b26fb6cb93c52a9fca51853b68193916982358fe1e5369e249875bb8d0d0ec3" +
"6f917bc5e1eafd5896d46bd61ff23f1a863a8a8dcd54c7b109b771c8e61ec9c8908c733c0263440e" +
"2aa067241aaa433f0bb053c7b31a838504b148f570c0ad62837129e547678c5190341e4f1693956c" +
"3bf7678318e2d5b5340c9e488eefea198576344afbdf66db5f51204a6961a63ce072c8926c")
val authResponseData = decode(
"01ea0451958701280a56482929d3b0757da8f7fbe5286784beead59d95089c217c9b917788989470" +
"b0e330cc6e4fb383c0340ed85fab836ec9fb8a49672712aeabbdfd1e837c1ff4cace34311cd7f4de" +
"05d59279e3524ab26ef753a0095637ac88f2b499b9914b5f64e143eae548a1066e14cd2f4bd7f814" +
"c4652f11b254f8a2d0191e2f5546fae6055694aed14d906df79ad3b407d94692694e259191cde171" +
"ad542fc588fa2b7333313d82a9f887332f1dfc36cea03f831cb9a23fea05b33deb999e85489e645f" +
"6aab1872475d488d7bd6c7c120caf28dbfc5d6833888155ed69d34dbdc39c1f299be1057810f34fb" +
"e754d021bfca14dc989753d61c413d261934e1a9c67ee060a25eefb54e81a4d14baff922180c395d" +
"3f998d70f46f6b58306f969627ae364497e73fc27f6d17ae45a413d322cb8814276be6ddd13b885b" +
"201b943213656cde498fa0e9ddc8e0b8f8a53824fbd82254f3e2c17e8eaea009c38b4aa0a3f306e8" +
"797db43c25d68e86f262e564086f59a2fc60511c42abfb3057c247a8a8fe4fb3ccbadde17514b7ac" +
"8000cdb6a912778426260c47f38919a91f25f4b5ffb455d6aaaf150f7e5529c100ce62d6d92826a7" +
"1778d809bdf60232ae21ce8a437eca8223f45ac37f6487452ce626f549b3b5fdee26afd2072e4bc7" +
"5833c2464c805246155289f4")
// agree (on B side)
val initiate = handshakerB!!.decryptAuthInitiateV4(authInitiateData, keyB)
val response = handshakerB!!.makeAuthInitiateV4(initiate, keyB)
assertArrayEquals(keyA.pubKey, handshakerB!!.remotePublicKey.getEncoded(false))
handshakerB!!.agreeSecret(authInitiateData, authResponseData)
assertArrayEquals(decode("80e8632c05fed6fc2a13b0f8d31a3cf645366239170ea067065aba8e28bac487"), handshakerB!!.secrets.aes)
assertArrayEquals(decode("2ea74ec5dae199227dff1af715362700e989d889d7a493cb0639691efb8e5f98"), handshakerB!!.secrets.mac)
val fooHash = ByteArray(32)
handshakerB!!.secrets.ingressMac.update("foo".toByteArray(), 0, "foo".toByteArray().size)
handshakerB!!.secrets.ingressMac.doFinal(fooHash, 0)
assertArrayEquals(decode("0c7ec6340062cc46f5e9f1e3cf86f8c8c403c5a0964f5df0ebd34a75ddc86db5"), fooHash)
// decode (on A side)
response.ephemeralPublicKey = ephemeralKeyB.pubKeyPoint
val encrypted = handshakerB!!.encryptAuthResponseV4(response)
val msg2 = handshakerA!!.decryptAuthResponseV4(encrypted, keyA)
assertEquals(4, msg2.version.toLong())
assertArrayEquals(nonceB, msg2.nonce)
assertArrayEquals(ephemeralKeyB.pubKey, msg2.ephemeralPublicKey!!.getEncoded(false))
val msg3 = handshakerA!!.decryptAuthResponseV4(authResponseData, keyA)
assertEquals(4, msg3.version.toLong())
assertArrayEquals(nonceB, msg3.nonce)
assertArrayEquals(ephemeralKeyB.pubKey, msg3.ephemeralPublicKey!!.getEncoded(false))
}
// AuthResponse EIP-8 format with version 57 and 3 additional list elements (sent from B to A)
@Test
@Throws(InvalidCipherTextException::class)
fun test4() {
val authMessageData = decode(
"01f004076e58aae772bb101ab1a8e64e01ee96e64857ce82b1113817c6cdd52c09d26f7b90981cd7" +
"ae835aeac72e1573b8a0225dd56d157a010846d888dac7464baf53f2ad4e3d584531fa203658fab0" +
"3a06c9fd5e35737e417bc28c1cbf5e5dfc666de7090f69c3b29754725f84f75382891c561040ea1d" +
"dc0d8f381ed1b9d0d4ad2a0ec021421d847820d6fa0ba66eaf58175f1b235e851c7e2124069fbc20" +
"2888ddb3ac4d56bcbd1b9b7eab59e78f2e2d400905050f4a92dec1c4bdf797b3fc9b2f8e84a482f3" +
"d800386186712dae00d5c386ec9387a5e9c9a1aca5a573ca91082c7d68421f388e79127a5177d4f8" +
"590237364fd348c9611fa39f78dcdceee3f390f07991b7b47e1daa3ebcb6ccc9607811cb17ce51f1" +
"c8c2c5098dbdd28fca547b3f58c01a424ac05f869f49c6a34672ea2cbbc558428aa1fe48bbfd6115" +
"8b1b735a65d99f21e70dbc020bfdface9f724a0d1fb5895db971cc81aa7608baa0920abb0a565c9c" +
"436e2fd13323428296c86385f2384e408a31e104670df0791d93e743a3a5194ee6b076fb6323ca59" +
"3011b7348c16cf58f66b9633906ba54a2ee803187344b394f75dd2e663a57b956cb830dd7a908d4f" +
"39a2336a61ef9fda549180d4ccde21514d117b6c6fd07a9102b5efe710a32af4eeacae2cb3b1dec0" +
"35b9593b48b9d3ca4c13d245d5f04169b0b1")
// decode (on A side)
val msg2 = handshakerA!!.decryptAuthResponseV4(authMessageData, keyA)
assertEquals(57, msg2.version.toLong())
assertArrayEquals(nonceB, msg2.nonce)
}
}
| mit | 876c6b7eda5d3e57a5238485fbe54549 | 56.625551 | 128 | 0.731519 | 2.713337 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/AddChangeListAction.kt | 12 | 1161 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.ui.NewChangelistDialog
class AddChangeListAction : AbstractChangeListAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val dialog = NewChangelistDialog(project)
if (dialog.showAndGet()) {
val changeListManager = ChangeListManager.getInstance(project)
val changeList = changeListManager.addChangeList(dialog.name, dialog.description)
if (dialog.isNewChangelistActive) {
changeListManager.defaultChangeList = changeList
}
dialog.panel.changelistCreatedOrChanged(changeList)
}
}
override fun update(e: AnActionEvent) {
val project = e.project
val enabled = project != null && ChangeListManager.getInstance(project).areChangeListsEnabled()
updateEnabledAndVisible(e, enabled, !getChangeLists(e).none())
}
} | apache-2.0 | 51d7964fc9f472ae2c1a9948b993ba6a | 37.733333 | 140 | 0.762274 | 4.588933 | false | false | false | false |
smmribeiro/intellij-community | plugins/gradle-maven/src/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/completion/GradleMapStyleInsertHandler.kt | 11 | 4098 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.integrations.maven.codeInsight.completion
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import org.jetbrains.idea.maven.onlinecompletion.model.MavenRepositoryArtifactInfo
import org.jetbrains.plugins.gradle.integrations.maven.codeInsight.completion.MavenDependenciesGradleCompletionContributor.Companion.GROUP_LABEL
import org.jetbrains.plugins.gradle.integrations.maven.codeInsight.completion.MavenDependenciesGradleCompletionContributor.Companion.NAME_LABEL
import org.jetbrains.plugins.gradle.integrations.maven.codeInsight.completion.MavenDependenciesGradleCompletionContributor.Companion.VERSION_LABEL
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument
import runCompletion
abstract class GradleMapStyleInsertHandler : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
val file = context.file as? GroovyFile ?: return
val element = file.findElementAt(context.startOffset)
val psiElement = element?.parent?.parent as? GrNamedArgument ?: return
val parent = psiElement.parent as? GrArgumentList ?: return
val factory = GroovyPsiElementFactory.getInstance(parent.project)
val artifactInfo = item.`object` as? MavenRepositoryArtifactInfo ?: return
doInsert(psiElement, parent, factory, artifactInfo, context)
}
abstract fun doInsert(psiElement: GrNamedArgument,
parent: GrArgumentList,
factory: GroovyPsiElementFactory,
artifactInfo: MavenRepositoryArtifactInfo,
context: InsertionContext)
}
class GradleMapStyleInsertGroupHandler : GradleMapStyleInsertHandler() {
override fun doInsert(psiElement: GrNamedArgument,
parent: GrArgumentList,
factory: GroovyPsiElementFactory,
artifactInfo: MavenRepositoryArtifactInfo,
context: InsertionContext) {
setValue(GROUP_LABEL, artifactInfo.groupId, parent, factory)
val artifactPsi = setValue(NAME_LABEL, "", parent, factory)
runCompletion(artifactPsi, context)
}
companion object {
val INSTANCE = GradleMapStyleInsertGroupHandler()
}
}
class GradleMapStyleInsertArtifactIdHandler : GradleMapStyleInsertHandler() {
override fun doInsert(psiElement: GrNamedArgument,
parent: GrArgumentList,
factory: GroovyPsiElementFactory,
artifactInfo: MavenRepositoryArtifactInfo,
context: InsertionContext) {
setValue(NAME_LABEL, artifactInfo.artifactId, parent, factory)
if (artifactInfo.items.size != 1) {
val versionPsi = setValue(VERSION_LABEL, "", parent, factory)
context.commitDocument()
runCompletion(versionPsi, context)
}
else {
setValue(VERSION_LABEL, artifactInfo.items[0].version.orEmpty(), parent, factory)
context.commitDocument()
}
}
companion object {
val INSTANCE = GradleMapStyleInsertArtifactIdHandler()
}
}
private fun setValue(name: String, value: String, parent: GrArgumentList, factory: GroovyPsiElementFactory): GrNamedArgument {
val namedArgument = parent.findNamedArgument(name)
if (namedArgument != null) {
namedArgument.expression?.replaceWithExpression(factory.createExpressionFromText("'$value'"), true)
return namedArgument
}
return parent.addAfter(factory.createNamedArgument(name, factory.createExpressionFromText("'$value'")),
parent.lastChild) as GrNamedArgument
}
| apache-2.0 | 45c64fb09109ecc09a089f32e966dbb0 | 45.044944 | 146 | 0.745486 | 5.267352 | false | false | false | false |
anastr/SpeedView | app/src/main/java/com/github/anastr/speedviewapp/SectionActivity.kt | 1 | 1777 | package com.github.anastr.speedviewapp
import android.graphics.Color
import android.os.Bundle
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import com.github.anastr.speedviewlib.components.Style
import com.github.anastr.speedviewlib.util.doOnSections
import kotlinx.android.synthetic.main.activity_section.*
class SectionActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_section)
title = "Sections"
seekBar.setOnSeekBarChangeListener(object: SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
speedView.makeSections(progress, 0, Style.BUTT)
textSpeed.text = "$progress"
randomColors()
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
button_random_color.setOnClickListener { randomColors() }
seekBar.progress = 5
speedView.speedTo(50f)
}
private fun randomColors() {
speedView.doOnSections { it.color = Color.rgb((0..255).random(), (0..255).random(), (0..255).random()) }
/*
the next code is slow, because if you call
`section.color = ...`
every time, it will redraw the speedometer and take a lot of time.
sections are observable by its speedometer, so any change in section will redraw the speedometer.
*/
// speedView.sections.forEach {
// it.color = Color.rgb((0..255).random(), (0..255).random(), (0..255).random())
// }
}
}
| apache-2.0 | dbe84252d9e73bd711c3b5e05d99d8c4 | 36.020833 | 112 | 0.658413 | 4.476071 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/GetLocationActionType.kt | 1 | 585 | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.http_shortcuts.scripting.ActionAlias
import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO
class GetLocationActionType : BaseActionType() {
override val type = TYPE
override fun fromDTO(actionDTO: ActionDTO) = GetLocationAction()
override fun getAlias() = ActionAlias(
functionName = FUNCTION_NAME,
parameters = 0,
)
companion object {
private const val TYPE = "get_location"
private const val FUNCTION_NAME = "getLocation"
}
}
| mit | 707834c0ed2f01d682acc34835d54501 | 26.857143 | 68 | 0.717949 | 4.178571 | false | false | false | false |
nischalbasnet/kotlin-android-tictactoe | app/src/main/java/com/nbasnet/tictactoe/Constants.kt | 1 | 287 | package com.nbasnet.tictactoe
/**
* Activity payload constants
*/
val PLAYER1 = "player1"
val PLAYER2 = "player2"
val PLAYER1_AI = "player1AI"
val PLAYER2_AI = "player2AI"
val GRID_ROW = "gridRow"
/**
* APP constants
*/
val APP_DATE_FORMAT = "MM/dd/yyyy"
val APP_PAYLOAD = "payload" | mit | 455a273cedac530e2b9b3b383f286726 | 18.2 | 34 | 0.69338 | 2.786408 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/original/AdBlockArrayRecyclerAdapter.kt | 1 | 2368 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.adblock.ui.original
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import jp.hazuki.yuzubrowser.adblock.R
import jp.hazuki.yuzubrowser.adblock.repository.original.AdBlock
import jp.hazuki.yuzubrowser.core.utility.extensions.getResColor
import jp.hazuki.yuzubrowser.ui.widget.recycler.ArrayRecyclerAdapter
import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener
class AdBlockArrayRecyclerAdapter(context: Context, list: MutableList<AdBlock>, listener: OnRecyclerListener) : ArrayRecyclerAdapter<AdBlock, AdBlockArrayRecyclerAdapter.ItemHolder>(context, list, listener) {
private val foregroundOverlay = ColorDrawable(context.getResColor(R.color.selected_overlay))
override fun onBindViewHolder(holder: ItemHolder, item: AdBlock, position: Int) {
holder.match.text = item.match
holder.checkBox.isChecked = item.isEnable
holder.foreground.background = if (isMultiSelectMode && isSelected(position)) foregroundOverlay else null
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup?, viewType: Int): ItemHolder =
ItemHolder(inflater.inflate(R.layout.fragment_ad_block_list_item, parent, false), this)
class ItemHolder(itemView: View, adapter: AdBlockArrayRecyclerAdapter) : ArrayRecyclerAdapter.ArrayViewHolder<AdBlock>(itemView, adapter) {
val match: TextView = itemView.findViewById(R.id.matchTextView)
val checkBox: CheckBox = itemView.findViewById(R.id.checkBox)
val foreground: View = itemView.findViewById(R.id.foreground)
}
}
| apache-2.0 | 2bbb6ee21fc1cedbd1c9f22ab6ca72da | 45.431373 | 208 | 0.779561 | 4.426168 | false | false | false | false |
rohitsuratekar/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/models/Trip.kt | 1 | 1896 | package com.rohitsuratekar.NCBSinfo.models
import android.util.Log
import com.rohitsuratekar.NCBSinfo.common.Constants
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
class Trip(private var tripString: String, private var dayIndex: Int, private var cal: Calendar) {
fun displayTime(): String {
val inputFormat = SimpleDateFormat(Constants.FORMAT_TRIP_LIST, Locale.ENGLISH)
val outputFormat = SimpleDateFormat(Constants.FORMAT_DISPLAY_TIME, Locale.ENGLISH)
val returnCal = Calendar.getInstance().apply { timeInMillis = cal.timeInMillis }
val tempCal = Calendar.getInstance()
try {
tempCal.timeInMillis = inputFormat.parse(tripString)?.time!!
} catch (e: ParseException) {
Log.e("Trip", "Message : ${e.localizedMessage}")
return "--:--"
}
returnCal.set(Calendar.HOUR_OF_DAY, tempCal.get(Calendar.HOUR_OF_DAY))
returnCal.set(Calendar.MINUTE, tempCal.get(Calendar.MINUTE))
return outputFormat.format(Date(returnCal.timeInMillis))
}
fun raw(): String {
return tripString
}
fun tripHighlightDay(): Int {
val tempCal = Calendar.getInstance().apply { cal.timeInMillis }
when (dayIndex) {
-1 -> {
tempCal.add(Calendar.DATE, -1)
}
2 -> {
tempCal.add(Calendar.DATE, 1)
}
}
return tempCal.get(Calendar.DAY_OF_WEEK)
}
fun tripCalender(): Calendar {
val tempCal = Calendar.getInstance().apply { cal.timeInMillis }
when (dayIndex) {
-1 -> {
tempCal.add(Calendar.DATE, -1)
}
2 -> {
tempCal.add(Calendar.DATE, 1)
}
}
return tempCal
}
} | mit | e5a020c10239ce212a772c2f56690e9d | 31.892857 | 98 | 0.581751 | 4.368664 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/korio/async/AsyncPoolCompat.kt | 1 | 694 | package com.soywiz.korio.async
import kotlinx.coroutines.channels.*
class AsyncPoolCompat<T>(val maxItems: Int = Int.MAX_VALUE, val create: suspend () -> T) {
var createdItems = 0
private val freedItem = Channel<T>(maxItems)
suspend fun alloc(): T {
return if (createdItems >= maxItems) {
freedItem.receive()
} else {
createdItems++
create()
}
}
fun free(item: T) {
freedItem.trySend(item)
}
suspend inline fun <TR> alloc(callback: suspend (T) -> TR): TR {
val item = alloc()
try {
return callback(item)
} finally {
free(item)
}
}
}
| mit | d69cf91ba3ecdda1e3a3bcb2ba2f5eda | 22.133333 | 90 | 0.541787 | 3.965714 | false | false | false | false |
tekinarslan/RxJavaKotlinSample | app/src/main/java/com/tekinarslan/kotlinrxjavasample/core/CoreApp.kt | 1 | 639 | package com.tekinarslan.kotlinrxjavasample.core
import android.app.Application
import com.tekinarslan.kotlinrxjavasample.network.NetworkManager
/**
* Created by selimtekinarslan on 6/29/2017.
*/
class CoreApp : Application() {
companion object {
var instance: CoreApp? = null
}
private var networkManager: NetworkManager? = null
override fun onCreate() {
super.onCreate()
instance = this
}
fun getNetworkManager(): NetworkManager {
if (networkManager == null) {
networkManager = NetworkManager()
}
return networkManager as NetworkManager
}
} | apache-2.0 | fa2fb654042bce36cdf6b37371586b9d | 20.333333 | 64 | 0.668232 | 4.733333 | false | false | false | false |
sonnytron/FitTrainerBasic | mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/fragments/WorkoutStatusFragment.kt | 1 | 3922 | package com.sonnyrodriguez.fittrainer.fittrainerbasic.fragments
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.sonnyrodriguez.fittrainer.fittrainerbasic.R
import com.sonnyrodriguez.fittrainer.fittrainerbasic.database.WorkoutHistoryObject
import com.sonnyrodriguez.fittrainer.fittrainerbasic.database.WorkoutObject
import com.sonnyrodriguez.fittrainer.fittrainerbasic.models.LocalExerciseObject
import com.sonnyrodriguez.fittrainer.fittrainerbasic.models.MuscleEnum
import com.sonnyrodriguez.fittrainer.fittrainerbasic.presenter.HistoryPresenter
import com.sonnyrodriguez.fittrainer.fittrainerbasic.ui.WorkoutStatusFragmentUi
import com.sonnyrodriguez.fittrainer.fittrainerbasic.values.KeyConstants
import com.sonnyrodriguez.fittrainer.fittrainerbasic.values.RequestConstants
import org.jetbrains.anko.AnkoContext
import org.jetbrains.anko.support.v4.ctx
import org.jetbrains.anko.support.v4.toast
class WorkoutStatusFragment: Fragment(), HistoryPresenter {
internal lateinit var ui: WorkoutStatusFragmentUi
internal var localExercises = ArrayList<String>()
internal lateinit var localWorkout: WorkoutObject
internal lateinit var appActivity: AppCompatActivity
companion object {
fun newInstance(workoutObject: WorkoutObject, appCompatActivity: AppCompatActivity) = WorkoutStatusFragment().apply {
val bundle = Bundle()
bundle.putParcelable(KeyConstants.INTENT_WORKOUT_OBJECT, workoutObject)
appActivity = appCompatActivity
arguments = bundle
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
ui = WorkoutStatusFragmentUi()
return ui.createView(AnkoContext.Companion.create(ctx, this)).apply {
loadExercises()
}
}
override fun loadAllHistory(historyObjects: List<WorkoutHistoryObject>) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun historySaved() {
}
internal fun loadExercises() {
localWorkout = arguments.getParcelable(KeyConstants.INTENT_WORKOUT_OBJECT)
localExercises.clear().apply {
localExercises.addAll(localWorkout.exerciseMetaList.map { it.title })
}
val muscleTitles = localWorkout.exerciseMetaList.map { MuscleEnum.fromMuscleNumber(it.muscleGroup).title }
val muscleArrayList: ArrayList<String> = arrayListOf()
muscleArrayList.addAll(
muscleTitles.filter { !muscleArrayList.contains(it) }
)
ui.muscleGroups.addAll(muscleArrayList)
val muscleCountText = ctx.getString(R.string.exercise_count_title, localExercises.count())
ui.setMuscleGroupText(title = localWorkout.title, muscleCountString = muscleCountText)
}
internal fun startWorkout() {
val workoutArrayList = ArrayList<LocalExerciseObject>()
workoutArrayList.addAll(localWorkout.exerciseMetaList)
}
internal fun endWorkout() {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
data?.run {
when (requestCode) {
RequestConstants.INTENT_EXERCISE_LIST -> {
val completedExercises: ArrayList<LocalExerciseObject> = getParcelableArrayListExtra(KeyConstants.INTENT_COMPLETED_EXERCISES)
toast("You completed ${completedExercises.count()} exercises! Congratulations!")
}
}
}
}
}
}
| apache-2.0 | a363d26a888eac4230ab1de63885b889 | 41.172043 | 149 | 0.731515 | 4.866005 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/account/ConfirmRevocationDialog.kt | 1 | 4380 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Alexandre Lision <[email protected]>
* Adrien Beraud <[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 cx.ring.account
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import cx.ring.R
import cx.ring.databinding.DialogConfirmRevocationBinding
class ConfirmRevocationDialog : DialogFragment() {
private var mDeviceId: String? = null
private var mHasPassword = true
private var mListener: ConfirmRevocationListener? = null
private var binding: DialogConfirmRevocationBinding? = null
fun setListener(listener: ConfirmRevocationListener) {
mListener = listener
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
binding = DialogConfirmRevocationBinding.inflate(requireActivity().layoutInflater)
mDeviceId = requireArguments().getString(DEVICEID_KEY)
mHasPassword = requireArguments().getBoolean(HAS_PASSWORD_KEY)
val result = MaterialAlertDialogBuilder(requireContext())
.setView(binding!!.root)
.setMessage(getString(R.string.revoke_device_message, mDeviceId))
.setTitle(getText(R.string.revoke_device_title))
.setPositiveButton(R.string.revoke_device_title, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel) { _, _ -> dismiss() }
.create()
result.setOnShowListener { dialog: DialogInterface ->
val positiveButton = (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)
positiveButton.setOnClickListener {
if (validate()) {
dismiss()
}
}
}
if (mHasPassword) {
result.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
} else {
binding!!.passwordTxtBox.visibility = View.GONE
}
binding!!.passwordTxt.setOnEditorActionListener { _, actionId: Int, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
val validationResult = validate()
if (validationResult) {
dialog!!.dismiss()
}
return@setOnEditorActionListener validationResult
}
false
}
return result
}
private fun checkInput(): Boolean {
if (mHasPassword && binding!!.passwordTxt.text.toString().isEmpty()) {
binding!!.passwordTxtBox.isErrorEnabled = true
binding!!.passwordTxtBox.error = getText(R.string.enter_password)
return false
} else {
binding!!.passwordTxtBox.isErrorEnabled = false
binding!!.passwordTxtBox.error = null
}
return true
}
private fun validate(): Boolean {
if (checkInput() && mListener != null) {
val password = binding!!.passwordTxt.text.toString()
mListener!!.onConfirmRevocation(mDeviceId!!, password)
return true
}
return false
}
interface ConfirmRevocationListener {
fun onConfirmRevocation(deviceId: String, password: String)
}
companion object {
const val DEVICEID_KEY = "deviceid_key"
const val HAS_PASSWORD_KEY = "has_password_key"
val TAG = ConfirmRevocationDialog::class.simpleName!!
}
} | gpl-3.0 | 3fafb5b1c8cbd7edc9ddfa1906da8388 | 38.827273 | 105 | 0.665525 | 4.818482 | false | false | false | false |
tommyettinger/SquidSetup | src/main/kotlin/com/github/czyzby/setup/data/libs/unofficial/thirdPartyExtensions.kt | 1 | 26873 | package com.github.czyzby.setup.data.libs.unofficial
import com.github.czyzby.setup.data.files.CopiedFile
import com.github.czyzby.setup.data.files.path
import com.github.czyzby.setup.data.libs.Library
import com.github.czyzby.setup.data.libs.official.Controllers
import com.github.czyzby.setup.data.platforms.*
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.views.Extension
/**
* Abstract base for unofficial extensions.
* @author MJ
*/
abstract class ThirdPartyExtension : Library {
override val official = false
override fun initiate(project: Project) {
project.properties[id + "Version"] = project.extensions.getVersion(id)
initiateDependencies(project)
}
abstract fun initiateDependencies(project: Project)
override fun addDependency(project: Project, platform: String, dependency: String) {
if(dependency.count { it == ':' } > 1) {
super.addDependency(project, platform, dependency.substringBeforeLast(':') + ":\$${id}Version:" + dependency.substringAfterLast(':'))
} else {
super.addDependency(project, platform, dependency + ":\$${id}Version")
}
}
fun addExternalDependency(project: Project, platform: String, dependency: String) {
super.addDependency(project, platform, dependency)
}
}
/**
* A high performance Entity-Component-System framework.
* If you target GWT, this setup tool handles some of this library's complicated steps for you.
* @author junkdog
*/
@Extension
class ArtemisOdb : ThirdPartyExtension() {
override val id = "artemisOdb"
override val defaultVersion = "2.3.0"
override val url = "https://github.com/junkdog/artemis-odb"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "net.onedaybeard.artemis:artemis-odb");
addDependency(project, GWT.ID, "net.onedaybeard.artemis:artemis-odb-gwt")
addDependency(project, GWT.ID, "net.onedaybeard.artemis:artemis-odb-gwt:sources")
addDependency(project, GWT.ID, "net.onedaybeard.artemis:artemis-odb:sources")
addGwtInherit(project, "com.artemis.backends.artemis_backends_gwt")
if (project.hasPlatform(GWT.ID)) {
project.files.add(
CopiedFile(
projectName = GWT.ID,
original = path("generator", GWT.ID, "jsr305.gwt.xml"),
path = path("src", "main", "java", "jsr305.gwt.xml")
)
)
addGwtInherit(project, "jsr305")
}
}
}
/**
* General libGDX utilities.
* @author Dermetfan
* @author Maintained by Tommy Ettinger
*/
@Extension
class LibgdxUtils : ThirdPartyExtension() {
override val id = "utils"
override val defaultVersion = "0.13.7"
override val url = "https://github.com/tommyettinger/gdx-utils"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.tommyettinger:libgdx-utils")
addDependency(project, GWT.ID, "com.github.tommyettinger:libgdx-utils:sources")
addGwtInherit(project, "libgdx-utils")
}
}
/**
* Box2D libGDX utilities.
* @author Dermetfan
* @author Maintained by Tommy Ettinger
*/
@Extension
class LibgdxUtilsBox2D : ThirdPartyExtension() {
override val id = "utilsBox2d"
override val defaultVersion = "0.13.7"
override val url = "https://github.com/tommyettinger/gdx-utils"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.tommyettinger:libgdx-utils-box2d")
addDependency(project, GWT.ID, "com.github.tommyettinger:libgdx-utils-box2d:sources")
addGwtInherit(project, "libgdx-utils-box2d")
LibgdxUtils().initiate(project)
}
}
/**
* Facebook graph API wrapper. iOS-incompatible! Also, out-of-date.
* @author Tom Grill
*/
@Extension
class Facebook : ThirdPartyExtension() {
override val id = "facebook"
override val defaultVersion = "1.5.0"
override val url = "https://github.com/TomGrill/gdx-facebook"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "de.tomgrill.gdxfacebook:gdx-facebook-core")
addDependency(project, Android.ID, "de.tomgrill.gdxfacebook:gdx-facebook-android")
addDesktopDependency(project, "de.tomgrill.gdxfacebook:gdx-facebook-desktop")
//// This is a problem for the App Store, removed.
// addDependency(project, iOS.ID, "de.tomgrill.gdxfacebook:gdx-facebook-ios")
addDependency(project, GWT.ID, "de.tomgrill.gdxfacebook:gdx-facebook-core:sources")
addDependency(project, GWT.ID, "de.tomgrill.gdxfacebook:gdx-facebook-html")
addDependency(project, GWT.ID, "de.tomgrill.gdxfacebook:gdx-facebook-html:sources")
addGwtInherit(project, "de.tomgrill.gdxfacebook.html.gdx_facebook_gwt")
}
}
/**
* Native dialogs support.
* @author Tom Grill
*/
@Extension
class Dialogs : ThirdPartyExtension() {
override val id = "dialogs"
override val defaultVersion = "1.3.0"
override val url = "https://github.com/TomGrill/gdx-dialogs"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "de.tomgrill.gdxdialogs:gdx-dialogs-core")
addDependency(project, Android.ID, "de.tomgrill.gdxdialogs:gdx-dialogs-android")
addDesktopDependency(project, "de.tomgrill.gdxdialogs:gdx-dialogs-desktop")
addDependency(project, iOS.ID, "de.tomgrill.gdxdialogs:gdx-dialogs-ios")
addDependency(project, GWT.ID, "de.tomgrill.gdxfacebook:gdx-dialogs-core:sources")
addDependency(project, GWT.ID, "de.tomgrill.gdxfacebook:gdx-dialogs-html")
addDependency(project, GWT.ID, "de.tomgrill.gdxfacebook:gdx-dialogs-html:sources")
addGwtInherit(project, "de.tomgrill.gdxfacebook.html.gdx_dialogs_html")
}
}
/**
* In-game console implementation; GWT-incompatible. If you target GWT, you can use JACI GWT.
* @author StrongJoshua
*/
@Extension
class InGameConsole : ThirdPartyExtension() {
override val id = "inGameConsole"
override val defaultVersion = "1.0.0"
override val url = "https://github.com/StrongJoshua/libgdx-inGameConsole"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.strongjoshua:libgdx-inGameConsole")
}
}
/**
* Java Annotation Console Interface. In-game console implementation, for non-GWT usage.
* If you target GWT, use JaciGwt instead.
* @author Yevgeny Krasik
*/
@Extension
class Jaci : ThirdPartyExtension() {
override val id = "jaci"
override val defaultVersion = "0.4.0"
override val url = "https://github.com/ykrasik/jaci"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.ykrasik:jaci-libgdx-cli-java")
}
}
/**
* Java Annotation Console Interface. GWT-compatible in-game console implementation.
* Don't use this at the same time as JACI (the non-GWT version).
* @author Yevgeny Krasik
*/
@Extension
class JaciGwt : ThirdPartyExtension() {
override val id = "jaciGwt"
override val defaultVersion = "0.4.0"
override val url = "https://github.com/ykrasik/jaci"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.ykrasik:jaci-libgdx-cli-gwt")
addDependency(project, GWT.ID, "com.github.ykrasik:jaci-libgdx-cli-gwt:sources")
addGwtInherit(project, "com.github.ykrasik.jaci")
}
}
/**
* Simple map generators. Noise4J can be used as a continuous noise generator, but you're better served by
* joise or make-some-noise in that case. There are also many kinds of map generator in squidlib-util.
* @author MJ
*/
@Extension
class Noise4J : ThirdPartyExtension() {
override val id = "noise4j"
override val defaultVersion = "0.1.0"
override val url = "https://github.com/czyzby/noise4j"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.czyzby:noise4j")
addDependency(project, GWT.ID, "com.github.czyzby:noise4j:sources")
addGwtInherit(project, "com.github.czyzby.noise4j.Noise4J")
}
}
/**
* Java implementation of Ink language: a scripting language for writing interactive narrative.
* @author bladecoder
*/
@Extension
class BladeInk : ThirdPartyExtension() {
override val id = "bladeInk"
override val defaultVersion = "0.7.4"
override val url = "https://github.com/bladecoder/blade-ink"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.bladecoder.ink:blade-ink")
}
}
/**
* 2D, 3D, 4D and 6D modular noise library written in Java.
* Joise can combine noise in versatile ways, and can serialize the "recipes" for a particular type of noise generator.
* @author SudoPlayGames
*/
@Extension
class Joise : ThirdPartyExtension() {
override val id = "joise"
override val defaultVersion = "1.1.0"
override val url = "https://github.com/SudoPlayGames/Joise"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.sudoplay.joise:joise")
addDependency(project, GWT.ID, "com.sudoplay.joise:joise:sources")
addGwtInherit(project, "joise")
}
}
/**
* Another 2D, 3D, 4D, 5D, and 6D noise library, supporting some unusual types of noise.
* The API is more "raw" than Joise, and is meant as a building block for things that use noise, rather
* than something that generates immediately-usable content. It is still a more convenient API than
* Noise4J when making fields of noise.
* @author Tommy Ettinger
*/
@Extension
class MakeSomeNoise : ThirdPartyExtension() {
override val id = "makeSomeNoise"
override val defaultVersion = "0.2"
override val url = "https://github.com/tommyettinger/make-some-noise"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.tommyettinger:make_some_noise")
addDependency(project, GWT.ID, "com.github.tommyettinger:make_some_noise:sources")
addGwtInherit(project, "make.some.noise")
}
}
/**
* An animated Label equivalent that appears as if it was being typed in real time.
* This is really just a wonderful set of effects for games to have.
* @author Rafa Skoberg
*/
@Extension
class TypingLabel : ThirdPartyExtension() {
override val id = "typingLabel"
override val defaultVersion = "1.2.0"
override val url = "https://github.com/rafaskb/typing-label"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.rafaskoberg.gdx:typing-label")
addDependency(project, GWT.ID, "com.rafaskoberg.gdx:typing-label:sources")
addGwtInherit(project, "com.rafaskoberg.gdx.typinglabel.typinglabel")
RegExodus().initiate(project)
}
}
/**
* A high-performance alternative to libGDX's built-in ShapeRenderer, with smoothing and more shapes.
* Better in just about every way when compared with ShapeRenderer.
* @author earlygrey
*/
@Extension
class ShapeDrawer : ThirdPartyExtension() {
override val id = "shapeDrawer"
override val defaultVersion = "2.4.0"
override val url = "https://github.com/earlygrey/shapedrawer"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "space.earlygrey:shapedrawer")
addDependency(project, GWT.ID, "space.earlygrey:shapedrawer:sources")
addGwtInherit(project, "space.earlygrey.shapedrawer")
}
}
/**
* Provides various frequently-used graph algorithms, aiming to be lightweight, fast, and intuitive.
* A good substitute for the pathfinding in gdx-ai, but it doesn't include path smoothing or any of the
* non-pathfinding AI tools in gdx-ai.
* @author earlygrey
*/
@Extension
class SimpleGraphs : ThirdPartyExtension() {
override val id = "simpleGraphs"
override val defaultVersion = "3.0.0"
override val url = "https://github.com/earlygrey/simple-graphs"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "space.earlygrey:simple-graphs")
addDependency(project, GWT.ID, "space.earlygrey:simple-graphs:sources")
addGwtInherit(project, "simple_graphs")
}
}
/**
* Provides a replacement for GWT's missing String.format() with its Stringf.format().
* Only relevant if you target the HTML platform or intend to in the future.
* @author Tommy Ettinger
*/
@Extension
class Formic : ThirdPartyExtension() {
override val id = "formic"
override val defaultVersion = "0.1.4"
override val url = "https://github.com/tommyettinger/formic"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.tommyettinger:formic")
addDependency(project, GWT.ID, "com.github.tommyettinger:formic:sources")
addGwtInherit(project, "formic")
}
}
/**
* Alternative color models for changing the colors of sprites and scenes, including brightening.
* @author Tommy Ettinger
*/
@Extension
class Colorful : ThirdPartyExtension() {
override val id = "colorful"
override val defaultVersion = "0.6.0"
override val url = "https://github.com/tommyettinger/colorful-gdx"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.tommyettinger:colorful")
addDependency(project, GWT.ID, "com.github.tommyettinger:colorful:sources")
addGwtInherit(project, "com.github.tommyettinger.colorful.colorful")
}
}
/**
* Support for writing animated GIF and animated PNG images from libGDX, as well as 8-bit-palette PNGs.
* This can be useful for making short captures of gameplay, or making animated characters into GIFs.
* @author Tommy Ettinger
*/
@Extension
class Anim8 : ThirdPartyExtension() {
override val id = "anim8"
override val defaultVersion = "0.2.10"
override val url = "https://github.com/tommyettinger/anim8-gdx"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.tommyettinger:anim8-gdx")
addDependency(project, GWT.ID, "com.github.tommyettinger:anim8-gdx:sources")
addGwtInherit(project, "anim8")
}
}
/**
* Bonus features for 9-patch images, filling significant gaps in normal 9-patch functionality.
* @author Raymond Buckley
*/
@Extension
class TenPatch : ThirdPartyExtension() {
override val id = "tenPatch"
override val defaultVersion = "5.0.1"
override val url = "https://github.com/raeleus/TenPatch"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.raeleus.TenPatch:tenpatch")
addDependency(project, GWT.ID, "com.github.raeleus.TenPatch:tenpatch:sources")
addGwtInherit(project, "com.ray3k.tenpatch.tenpatch")
}
}
/**
* The libGDX runtime for Spine, a commercial (and very powerful) skeletal-animation editor.
* You must have a license for Spine to use the runtime in your code.
* @author Esoteric Software
*/
@Extension
class SpineRuntime : ThirdPartyExtension() {
override val id = "spineRuntime"
override val defaultVersion = "3.8.55.1"
override val url = "https://github.com/EsotericSoftware/spine-runtimes/tree/3.8/spine-libgdx"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.esotericsoftware.spine:spine-libgdx")
addDependency(project, GWT.ID, "com.esotericsoftware.spine:spine-libgdx:sources")
addGwtInherit(project, "com.esotericsoftware.spine")
}
}
/**
* Legacy: MrStahlfelge's upgrades to controller support, now part of the official controllers extension.
* This is here so older projects that don't use the official controllers can be ported more easily.
* Change the version to 1.0.1 if you use libGDX 1.9.10 or earlier!
* @author MrStahlfelge
*/
@Extension
class ControllerUtils : ThirdPartyExtension() {
override val id = "controllerUtils"
override val defaultVersion = "2.2.1"
override val url = "https://github.com/MrStahlfelge/gdx-controllerutils"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "de.golfgl.gdxcontrollerutils:gdx-controllers-advanced")
addDependency(project, Desktop.ID, "de.golfgl.gdxcontrollerutils:gdx-controllers-jamepad")
addDependency(project, LWJGL3.ID, "de.golfgl.gdxcontrollerutils:gdx-controllers-jamepad")
addDependency(project, Android.ID, "de.golfgl.gdxcontrollerutils:gdx-controllers-android")
addDependency(project, iOS.ID, "de.golfgl.gdxcontrollerutils:gdx-controllers-iosrvm")
addDependency(project, GWT.ID, "de.golfgl.gdxcontrollerutils:gdx-controllers-gwt")
addDependency(project, GWT.ID, "de.golfgl.gdxcontrollerutils:gdx-controllers-gwt:sources")
addDependency(project, GWT.ID, "de.golfgl.gdxcontrollerutils:gdx-controllers-advanced:sources")
addGwtInherit(project, "com.badlogic.gdx.controllers.controllers-gwt")
}
}
/**
* MrStahlfelge's controller-imitating Scene2D widgets, for players who don't have a controller.
* <a href="https://github.com/MrStahlfelge/gdx-controllerutils/wiki/Button-operable-Scene2d">See the docs before using</a>.
* Change the version to 1.0.1 if you use libGDX 1.9.10 or earlier!
* @author MrStahlfelge
*/
@Extension
class ControllerScene2D : ThirdPartyExtension() {
override val id = "controllerScene2D"
override val defaultVersion = "2.3.0"
override val url = "https://github.com/MrStahlfelge/gdx-controllerutils/wiki/Button-operable-Scene2d"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "de.golfgl.gdxcontrollerutils:gdx-controllerutils-scene2d")
addDependency(project, GWT.ID, "de.golfgl.gdxcontrollerutils:gdx-controllerutils-scene2d:sources")
addGwtInherit(project, "de.golfgl.gdx.controllers.controller_scene2d")
}
}
/**
* MrStahlfelge's configurable mapping for game controllers.
* Not compatible with libGDX 1.9.10 or older!
* @author MrStahlfelge
*/
@Extension
class ControllerMapping : ThirdPartyExtension() {
override val id = "controllerMapping"
override val defaultVersion = "2.3.0"
override val url = "https://github.com/MrStahlfelge/gdx-controllerutils/wiki/Configurable-Game-Controller-Mappings"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "de.golfgl.gdxcontrollerutils:gdx-controllerutils-mapping")
addDependency(project, GWT.ID, "de.golfgl.gdxcontrollerutils:gdx-controllerutils-mapping:sources")
Controllers().initiate(project)
}
}
/**
* Code for making post-processing effects without so much hassle.
* @author crashinvaders
* @author metaphore
*/
@Extension
class GdxVfxCore : ThirdPartyExtension() {
override val id = "gdxVfxCore"
override val defaultVersion = "0.5.0"
override val url = "https://github.com/crashinvaders/gdx-vfx"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.crashinvaders.vfx:gdx-vfx-core")
addDependency(project, GWT.ID, "com.crashinvaders.vfx:gdx-vfx-core:sources")
addDependency(project, GWT.ID, "com.crashinvaders.vfx:gdx-vfx-gwt")
addDependency(project, GWT.ID, "com.crashinvaders.vfx:gdx-vfx-gwt:sources")
addGwtInherit(project, "com.crashinvaders.vfx.GdxVfxCore")
addGwtInherit(project, "com.crashinvaders.vfx.GdxVfxGwt")
}
}
/**
* A wide range of predefined post-processing effects using gdx-vfx core.
* @author crashinvaders
* @author metaphore
*/
@Extension
class GdxVfxStandardEffects : ThirdPartyExtension() {
override val id = "gdxVfxEffects"
override val defaultVersion = "0.5.0"
override val url = "https://github.com/crashinvaders/gdx-vfx"
override fun initiateDependencies(project: Project) {
GdxVfxCore().initiate(project)
addDependency(project, Core.ID, "com.crashinvaders.vfx:gdx-vfx-effects")
addDependency(project, GWT.ID, "com.crashinvaders.vfx:gdx-vfx-effects:sources")
addGwtInherit(project, "com.crashinvaders.vfx.GdxVfxEffects")
}
}
/**
* Cross-platform regex utilities that work the same on HTML as they do on desktop or mobile platforms.
* This is not 100% the same as the java.util.regex package, but is similar, and sometimes offers more.
* @author Tommy Ettinger
* @author based on JRegex by Sergey A. Samokhodkin
*/
@Extension()
class RegExodus : ThirdPartyExtension() {
override val id = "regExodus"
override val defaultVersion = "0.1.12"
override val url = "https://github.com/tommyettinger/RegExodus"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.tommyettinger:regexodus")
addDependency(project, GWT.ID, "com.github.tommyettinger:regexodus:sources")
addGwtInherit(project, "regexodus")
}
}
/**
* UI toolkit with extra widgets and a different theme style.
* Check the vis-ui changelog for what vis-ui versions are compatible
* with which libGDX versions; vis-ui 1.5.0 is the default and is
* compatible with libGDX 1.10.0.
* @author Kotcrab
*/
@Extension
class VisUI : ThirdPartyExtension() {
override val id = "visUi"
//You may need to skip a check: VisUI.setSkipGdxVersionCheck(true);
override val defaultVersion = "1.5.0"
override val url = "https://github.com/kotcrab/vis-ui"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.kotcrab.vis:vis-ui")
addDependency(project, GWT.ID, "com.kotcrab.vis:vis-ui:sources")
addGwtInherit(project, "com.kotcrab.vis.vis-ui")
}
}
/**
* A library to obtain a circular WidgetGroup or context menu using scene2d.ui.
* Pie menus can be easier for players to navigate with a mouse than long lists.
* @author Jérémi Grenier-Berthiaume
*/
@Extension
class PieMenu : ThirdPartyExtension() {
override val id = "pieMenu"
override val defaultVersion = "5.0.0"
override val url = "https://github.com/payne911/PieMenu"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.payne911:PieMenu")
addDependency(project, GWT.ID, "com.github.payne911:PieMenu:sources")
addGwtInherit(project, "PieMenu")
ShapeDrawer().initiate(project)
}
}
/**
* A 2D AABB collision detection and response library; like a basic/easy version of box2d.
* Note, AABB means this only handles non-rotated rectangular collision boxes.
* @author implicit-invocation
* @author Raymond Buckley
*/
@Extension
class JBump : ThirdPartyExtension() {
override val id = "jbump"
override val defaultVersion = "v1.0.1"
override val url = "https://github.com/tommyettinger/jbump"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.tommyettinger:jbump")
addDependency(project, GWT.ID, "com.github.tommyettinger:jbump:sources")
addGwtInherit(project, "com.dongbat.jbump")
}
}
/**
* A fast and efficient binary object graph serialization framework for Java.
* @author Nathan Sweet
*/
@Extension
class Kryo : ThirdPartyExtension() {
override val id = "kryo"
override val defaultVersion = "5.1.1"
override val url = "https://github.com/EsotericSoftware/kryo"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.esotericsoftware:kryo")
}
}
/**
* A Java library that provides a clean and simple API for efficient network communication, using Kryo.
* This is crykn's fork (AKA damios), which is much more up-to-date than the official repo.
* @author Nathan Sweet
* @author damios/crykn
*/
@Extension
class KryoNet : ThirdPartyExtension() {
override val id = "kryoNet"
override val defaultVersion = "2.22.7"
override val url = "https://github.com/crykn/kryonet"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.crykn:kryonet")
}
}
/**
* A small collection of some common and very basic utilities for libGDX games.
* @author damios/crykn
*/
@Extension
class Guacamole : ThirdPartyExtension() {
override val id = "guacamole"
override val defaultVersion = "0.3.1"
override val url = "https://github.com/crykn/guacamole"
override fun initiateDependencies(project: Project) {
addDependency(project, Core.ID, "com.github.crykn.guacamole:core")
addDependency(project, Core.ID, "com.github.crykn.guacamole:gdx")
addDependency(project, Desktop.ID, "com.github.crykn.guacamole:gdx-desktop")
addDependency(project, LWJGL3.ID, "com.github.crykn.guacamole:gdx-desktop")
addDependency(project, GWT.ID, "com.github.crykn.guacamole:core:sources")
addDependency(project, GWT.ID, "com.github.crykn.guacamole:gdx:sources")
addDependency(project, GWT.ID, "com.github.crykn.guacamole:gdx-gwt")
addDependency(project, GWT.ID, "com.github.crykn.guacamole:gdx-gwt:sources")
addGwtInherit(project, "guacamole_gdx_gwt")
}
}
//
// /**
// * An immediate-mode GUI library (LWJGL3-only!) that can be an alternative to scene2d.ui.
// * NOTE: this is only accessible from the lwjgl3 project, and may require unusual
// * project configuration to use.
// * @author SpaiR
// */
// @Extension
// class Imgui : ThirdPartyExtension() {
// override val id = "imgui"
// override val defaultVersion = "1.82.2"
// override val url = "https://github.com/SpaiR/imgui-java"
//
// override fun initiateDependencies(project: Project) {
//
// addDependency(project, LWJGL3.ID, "io.github.spair:imgui-java-binding");
// addDependency(project, LWJGL3.ID, "io.github.spair:imgui-java-lwjgl3");
// addDependency(project, LWJGL3.ID, "io.github.spair:imgui-java-natives-linux");
// addDependency(project, LWJGL3.ID, "io.github.spair:imgui-java-natives-linux-x86");
// addDependency(project, LWJGL3.ID, "io.github.spair:imgui-java-natives-macos");
// addDependency(project, LWJGL3.ID, "io.github.spair:imgui-java-natives-windows");
// addDependency(project, LWJGL3.ID, "io.github.spair:imgui-java-natives-windows-x86");
//
//// addDependency(project, Core.ID, "com.github.kotlin-graphics.imgui:core")
//// addDependency(project, LWJGL3.ID, "com.github.kotlin-graphics.imgui:gl")
//// addDependency(project, LWJGL3.ID, "com.github.kotlin-graphics.imgui:glfw")
// }
// }
//} | apache-2.0 | 955eb2a43ca85116c9be3b629f47ab6b | 36.901269 | 145 | 0.709464 | 3.665894 | false | false | false | false |
GoldRenard/JuniperBotJ | modules/jb-module-misc/src/main/java/ru/juniperbot/module/misc/commands/MathCommand.kt | 1 | 3496 | /*
* This file is part of JuniperBot.
*
* JuniperBot 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.
* JuniperBot 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 JuniperBot. If not, see <http://www.gnu.org/licenses/>.
*/
package ru.juniperbot.module.misc.commands
import com.udojava.evalex.AbstractFunction
import com.udojava.evalex.Expression
import net.dv8tion.jda.api.entities.MessageEmbed
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent
import ru.juniperbot.common.worker.command.model.AbstractCommand
import ru.juniperbot.common.worker.command.model.BotContext
import ru.juniperbot.common.worker.command.model.DiscordCommand
import java.math.BigDecimal
@DiscordCommand(
key = "discord.command.math.key",
description = "discord.command.math.desc",
group = ["discord.command.group.utility"],
priority = 30)
class MathCommand : AbstractCommand() {
override fun doCommand(message: GuildMessageReceivedEvent, context: BotContext, query: String): Boolean {
if (query.isEmpty()) {
messageService.onTempEmbedMessage(message.channel, 5, "discord.command.math.help")
return false
}
try {
val expression = createExpression(query)
val result = expression.eval()
val resultMessage = messageService.getMessage("discord.command.math.result", query, result)
if (resultMessage.length > MessageEmbed.TEXT_MAX_LENGTH) {
messageService.onError(message.channel, null, "discord.command.math.length")
return true
}
val builder = messageService.baseEmbed.setDescription(resultMessage)
messageService.sendMessageSilent({ message.channel.sendMessage(it) }, builder.build())
} catch (e: Expression.ExpressionException) {
messageService.onError(message.channel, null, "discord.command.math.error", query, e.message)
return false
} catch (e: ArithmeticException) {
messageService.onError(message.channel, null, "discord.command.math.error", query, e.message)
return false
}
return true
}
private fun createExpression(query: String): Expression {
val expression = Expression(query).setPrecision(32)
// limit fact calculation
expression.addFunction(object : AbstractFunction("FACT", 1, false) {
override fun eval(parameters: List<BigDecimal?>): BigDecimal {
val value = parameters[0] ?: throw ArithmeticException("Operand may not be null")
val number = value.toInt()
if (number > 100) {
throw ArithmeticException("Cannot calculate factorial more than 100")
}
var factorial = BigDecimal.ONE
for (i in 1..number) {
factorial = factorial.multiply(BigDecimal(i))
}
return factorial
}
})
return expression
}
}
| gpl-3.0 | fe120b8b429195a3386c81d8e24b8aea | 41.634146 | 109 | 0.666476 | 4.705249 | false | false | false | false |
Fondesa/RecyclerViewDivider | recycler-view-divider/src/main/kotlin/com/fondesa/recyclerviewdivider/DividerBuilder.kt | 1 | 18305 | /*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.util.TypedValue
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.Px
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.fondesa.recyclerviewdivider.cache.InMemoryGridCache
import com.fondesa.recyclerviewdivider.drawable.DrawableProvider
import com.fondesa.recyclerviewdivider.drawable.DrawableProviderImpl
import com.fondesa.recyclerviewdivider.drawable.getThemeDrawable
import com.fondesa.recyclerviewdivider.drawable.transparentDrawable
import com.fondesa.recyclerviewdivider.inset.InsetProvider
import com.fondesa.recyclerviewdivider.inset.InsetProviderImpl
import com.fondesa.recyclerviewdivider.inset.getThemeInsetEndOrDefault
import com.fondesa.recyclerviewdivider.inset.getThemeInsetStartOrDefault
import com.fondesa.recyclerviewdivider.log.logWarning
import com.fondesa.recyclerviewdivider.offset.DividerOffsetProvider
import com.fondesa.recyclerviewdivider.offset.DividerOffsetProviderImpl
import com.fondesa.recyclerviewdivider.size.SizeProvider
import com.fondesa.recyclerviewdivider.size.SizeProviderImpl
import com.fondesa.recyclerviewdivider.size.getThemeSize
import com.fondesa.recyclerviewdivider.space.getThemeAsSpaceOrDefault
import com.fondesa.recyclerviewdivider.tint.TintProvider
import com.fondesa.recyclerviewdivider.tint.TintProviderImpl
import com.fondesa.recyclerviewdivider.tint.getThemeTintColor
import com.fondesa.recyclerviewdivider.visibility.VisibilityProvider
import com.fondesa.recyclerviewdivider.visibility.VisibilityProviderImpl
/**
* Builds a divider for a [LinearLayoutManager] or its subclasses (e.g. [GridLayoutManager]).
* The following properties of a divider can be configured:
*
* - asSpace
* Makes the divider as a simple space, so the divider leaves the space between two cells but it is not rendered.
* Since the rendering is totally skipped in this case, it's better than using a transparent color.
* The asSpace property can be defined in the theme with the attribute "recyclerViewDividerAsSpace".
* By default it's false.
*
* - color/drawable
* Specifies the color/drawable of the divider used when it will be rendered.
* The color/drawable of the divider can be defined in the theme with the attribute "recyclerViewDividerDrawable".
* If it's not defined, it will be picked by the attribute "android:listDivider".
* If the Android attribute's value is null, the divider won't be rendered and it will behave as a space.
*
* - insets
* Specifies the start and the end insets of a divider's color/drawable.
* The insets of the divider can be defined in the theme with the attributes "recyclerViewDividerInsetStart" and
* "recyclerViewDividerInsetEnd".
* The inset will behave as a margin/padding of the divider's drawable.
* The start inset in an horizontal divider is the left inset in left-to-right and the right inset in right-to-left.
* The start inset in a vertical divider is the top inset in top-to-bottom and the bottom inset in bottom-to-top.
* The end inset in an horizontal divider is the right inset in left-to-right and the left inset in right-to-left.
* The end inset in a vertical divider is the bottom inset in top-to-bottom and the top inset in bottom-to-top.
* By default the divider has no insets.
*
* - size
* Specifies the divider's size.
* The size of the divider can be defined in the theme with the attribute "recyclerViewDividerSize".
* If it's not defined, the divider size will be inherited from the divider's drawable.
* If it can't be inherited from the divider's drawable (e.g. the drawable is a solid color), the default size of 1dp will be used.
* The size of an horizontal divider is its height.
* The size of a vertical divider is its width.
*
* - tint
* Specifies the tint color of the divider's drawable.
* The tint color of the divider can be defined in the theme with the attribute "recyclerViewDividerTint".
* By default the divider's drawable isn't tinted.
*
* - visibility
* Specifies if a divider is visible or not.
* When the divider isn't visible, it means the divider won't exist on the layout so its space between the two adjacent cells won't appear.
* By default the divider before the first item, after the last item and the side dividers aren't visible, all the others are.
*
* - offsets
* Specifies the divider's offset.
* It's useful to balance the size of the items in a grid with multiple columns/rows.
* By default, all the offsets are balanced between the items to render an equal size for each cell.
*
* @param context the [Context] used to build the divider.
*/
public class DividerBuilder internal constructor(private val context: Context) {
private var asSpace = false
private var drawableProvider: DrawableProvider? = null
@Px private var insetStart: Int? = null
@Px private var insetEnd: Int? = null
private var insetProvider: InsetProvider? = null
private var sizeProvider: SizeProvider? = null
private var tintProvider: TintProvider? = null
private var visibilityProvider: VisibilityProvider? = null
private var isFirstDividerVisible = false
private var isLastDividerVisible = false
private var areSideDividersVisible = false
private var offsetProvider: DividerOffsetProvider? = null
private var couldUnbalanceItems = false
/**
* Sets the divider as a simple space, so the divider leaves the space between two cells but it is not rendered.
* Since the rendering is totally skipped in this case, it's better than using a transparent color.
*
* @return this [DividerBuilder] instance.
*/
public fun asSpace(): DividerBuilder = apply { asSpace = true }
/**
* Sets the divider's drawable as a solid color.
*
* @param colorRes the resource of the color used for each divider.
* @return this [DividerBuilder] instance.
*/
public fun colorRes(@ColorRes colorRes: Int): DividerBuilder = color(ContextCompat.getColor(context, colorRes))
/**
* Sets the divider's drawable as a solid color.
*
* @param color the color used for each divider.
* @return this [DividerBuilder] instance.
*/
public fun color(@ColorInt color: Int): DividerBuilder = drawable(drawable = ColorDrawable(color))
/**
* Sets the divider's drawable.
*
* @param drawableRes the resource of the [Drawable] used for each divider.
* @return this [DividerBuilder] instance.
*/
public fun drawableRes(@DrawableRes drawableRes: Int): DividerBuilder = drawable(context.getDrawableCompat(drawableRes))
/**
* Sets the divider's drawable.
*
* @param drawable the [Drawable] used for each divider.
* @return this [DividerBuilder] instance.
*/
public fun drawable(drawable: Drawable): DividerBuilder =
drawableProvider(provider = DrawableProviderImpl(drawable = drawable), couldUnbalanceItems = false)
/**
* Sets the divider's start inset.
* The inset will behave as a margin/padding of the divider's drawable.
* The start inset in an horizontal divider is the left inset in left-to-right and the right inset in right-to-left.
* The start inset in a vertical divider is the top inset in top-to-bottom and the bottom inset in bottom-to-top.
*
* @param start the start inset size in pixels used for each divider.
* @return this [DividerBuilder] instance.
*/
public fun insetStart(@Px start: Int): DividerBuilder = apply { insetStart = start }
/**
* Sets the divider's end inset.
* The inset will behave as a margin/padding of the divider's drawable.
* The end inset in an horizontal divider is the right inset in left-to-right and the left inset in right-to-left.
* The end inset in a vertical divider is the bottom inset in top-to-bottom and the top inset in bottom-to-top.
*
* @param end the end inset size in pixels used for each divider.
* @return this [DividerBuilder] instance.
*/
public fun insetEnd(@Px end: Int): DividerBuilder = apply { insetEnd = end }
/**
* Sets the divider's insets.
* The inset will behave as a margin/padding of the divider's drawable.
* The start inset in an horizontal divider is the left inset in left-to-right and the right inset in right-to-left.
* The start inset in a vertical divider is the top inset in top-to-bottom and the bottom inset in bottom-to-top.
* The end inset in an horizontal divider is the right inset in left-to-right and the left inset in right-to-left.
* The end inset in a vertical divider is the bottom inset in top-to-bottom and the top inset in bottom-to-top.
*
* @param start the start inset size in pixels used for each divider.
* @param end the end inset size in pixels used for each divider.
* @return this [DividerBuilder] instance.
*/
public fun insets(@Px start: Int, @Px end: Int): DividerBuilder = apply {
insetStart = start
insetEnd = end
}
/**
* Sets the divider's size.
* The size of an horizontal divider is its height.
* The size of a vertical divider is its width.
*
* @param size the divider's size.
* @param sizeUnit the divider's size measurement unit (e.g. [TypedValue.COMPLEX_UNIT_DIP]). By default pixels.
* @return this [DividerBuilder] instance.
*/
@JvmOverloads
public fun size(size: Int, sizeUnit: Int = TypedValue.COMPLEX_UNIT_PX): DividerBuilder {
@Px val pxSize = context.resources.pxFromSize(size = size, sizeUnit = sizeUnit)
return sizeProvider(SizeProviderImpl(context = context, dividerSize = pxSize), couldUnbalanceItems = false)
}
/**
* Sets the tint color of the divider's drawable.
*
* @param color the tint color of the divider's drawable.
* @return this [DividerBuilder] instance.
*/
public fun tint(@ColorInt color: Int): DividerBuilder = tintProvider(TintProviderImpl(dividerTintColor = color))
/**
* Shows the first divider of the list/grid.
* The first divider is the one before the items in the first line.
*
* @return this [DividerBuilder] instance.
*/
public fun showFirstDivider(): DividerBuilder = apply { isFirstDividerVisible = true }
/**
* Shows the last divider of the list/grid.
* The last divider is the one after the items in the last line.
*
* @return this [DividerBuilder] instance.
*/
public fun showLastDivider(): DividerBuilder = apply { isLastDividerVisible = true }
/**
* Shows the side dividers of the list/grid.
* The side dividers are the ones before the first column and after the last column.
*
* @return this [DividerBuilder] instance.
*/
public fun showSideDividers(): DividerBuilder = apply { areSideDividersVisible = true }
/**
* Customizes the drawable of each divider in the grid.
* IMPORTANT: The default [DividerOffsetProvider] can't ensure the same size of the items in a grid when this method is called.
* If you want a different behavior, you can specify a custom [DividerOffsetProvider] with [offsetProvider].
*
* @param provider the [DrawableProvider] which will be invoked for each divider in the grid.
* @return this [DividerBuilder] instance.
*/
public fun drawableProvider(provider: DrawableProvider): DividerBuilder = drawableProvider(provider, couldUnbalanceItems = true)
/**
* Customizes the insets of each divider in the grid.
*
* @param provider the [InsetProvider] which will be invoked for each divider in the grid.
* @return this [DividerBuilder] instance.
*/
public fun insetProvider(provider: InsetProvider): DividerBuilder = apply { insetProvider = provider }
/**
* Customizes the size of each divider in the grid.
* IMPORTANT: The default [DividerOffsetProvider] can't ensure the same size of the items in a grid when this method is called.
* If you want a different behavior, you can specify a custom [DividerOffsetProvider] with [offsetProvider].
*
* @param provider the [SizeProvider] which will be invoked for each divider in the grid.
* @return this [DividerBuilder] instance.
*/
public fun sizeProvider(provider: SizeProvider): DividerBuilder = sizeProvider(provider, couldUnbalanceItems = true)
/**
* Customizes the tint color of each divider's drawable in the grid.
*
* @param provider the [TintProvider] which will be invoked for each divider in the grid.
* @return this [DividerBuilder] instance.
*/
public fun tintProvider(provider: TintProvider): DividerBuilder = apply { tintProvider = provider }
/**
* Customizes the visibility of each divider in the grid.
* IMPORTANT: The default [DividerOffsetProvider] can't ensure the same size of the items in a grid when this method is called.
* If you want a different behavior, you can specify a custom [DividerOffsetProvider] with [offsetProvider].
*
* @param provider the [VisibilityProvider] which will be invoked for each divider in the grid.
* @return this [DividerBuilder] instance.
*/
public fun visibilityProvider(provider: VisibilityProvider): DividerBuilder = apply {
visibilityProvider = provider
couldUnbalanceItems = true
}
/**
* Customizes the offset of each divider in the grid.
* This method is useful to balance the size of the items in a grid with multiple columns/rows.
*
* @param provider the [DividerOffsetProvider] which will be invoked for each divider in the grid.
* @return this [DividerBuilder] instance.
*/
public fun offsetProvider(provider: DividerOffsetProvider): DividerBuilder = apply {
offsetProvider = provider
}
/**
* Creates the [RecyclerView.ItemDecoration] using the configuration specified in this builder.
* If this builder doesn't specify the configuration of some divider's properties, those properties will be picked from the theme
* or their default will be used.
*
* @return a new [RecyclerView.ItemDecoration] which can be attached to the [RecyclerView].
*/
public fun build(): BaseDividerItemDecoration {
val asSpace = asSpace || context.getThemeAsSpaceOrDefault()
if (offsetProvider == null && couldUnbalanceItems) {
logWarning(
"The default ${DividerOffsetProvider::class.java.simpleName} can't ensure the same size of the items in a grid " +
"with more than 1 column/row using a custom ${DrawableProvider::class.java.simpleName}, " +
"${SizeProvider::class.java.simpleName} or ${VisibilityProvider::class.java.simpleName}."
)
}
return DividerItemDecoration(
asSpace = asSpace,
drawableProvider = drawableProvider ?: DrawableProviderImpl(drawable = context.getThemeDrawableOrDefault(asSpace)),
insetProvider = insetProvider ?: InsetProviderImpl(
dividerInsetStart = insetStart ?: context.getThemeInsetStartOrDefault(),
dividerInsetEnd = insetEnd ?: context.getThemeInsetEndOrDefault()
),
sizeProvider = sizeProvider ?: SizeProviderImpl(context = context, dividerSize = context.getThemeSize()),
tintProvider = tintProvider ?: TintProviderImpl(dividerTintColor = context.getThemeTintColor()),
visibilityProvider = visibilityProvider ?: VisibilityProviderImpl(
isFirstDividerVisible = isFirstDividerVisible,
isLastDividerVisible = isLastDividerVisible,
areSideDividersVisible = areSideDividersVisible
),
offsetProvider = offsetProvider ?: DividerOffsetProviderImpl(areSideDividersVisible),
cache = InMemoryGridCache()
)
}
private fun drawableProvider(provider: DrawableProvider, couldUnbalanceItems: Boolean): DividerBuilder = apply {
drawableProvider = provider
if (couldUnbalanceItems) {
this.couldUnbalanceItems = true
}
}
private fun sizeProvider(provider: SizeProvider, couldUnbalanceItems: Boolean): DividerBuilder = apply {
sizeProvider = provider
if (couldUnbalanceItems) {
this.couldUnbalanceItems = true
}
}
private fun Context.getThemeDrawableOrDefault(asSpace: Boolean): Drawable {
val drawable = getThemeDrawable()
if (drawable != null) return drawable
if (!asSpace) {
// If the divider should be treated as a space, its drawable isn't necessary so the log can be skipped.
logWarning(
"Can't render the divider without a color/drawable. " +
"Specify \"recyclerViewDividerDrawable\" or \"android:listDivider\" in the theme or set a color/drawable " +
"in this ${DividerBuilder::class.java.simpleName}."
)
}
return transparentDrawable()
}
private fun Context.getDrawableCompat(@DrawableRes drawableRes: Int): Drawable = ContextCompat.getDrawable(this, drawableRes)
?: throw NullPointerException("The drawable with resource id $drawableRes can't be loaded. Use the method .drawable() instead.")
}
| apache-2.0 | 67baa20d5232d7e1e2b03ea972da7189 | 48.206989 | 139 | 0.719148 | 4.645939 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/graphics/FontTextureFactoryViaAWT.kt | 1 | 6093 | /*
Tickle
Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.tickle.graphics
import org.lwjgl.opengl.GL11
import org.lwjgl.system.MemoryUtil
import uk.co.nickthecoder.tickle.Pose
import uk.co.nickthecoder.tickle.util.YDownRect
import java.awt.Font
import java.awt.FontMetrics
import java.awt.RenderingHints
import java.awt.image.BufferedImage
/**
*
* Note. Some fonts may extend higher than their ascent, or lower than their descent. In such cases, padding is
* required around each glyph to prevent one glyph overlapping another.
*/
open class FontTextureFactoryViaAWT(
val font: Font,
val xPadding: Int = 1,
val yPadding: Int = 1,
val maxTextureWidth: Int = (font.size + xPadding * 2) * 12) {
protected val glyphDataMap = mutableMapOf<Char, GlyphData>()
protected var requiredWidth: Int = 0
protected var requiredHeight: Int = 0
/**
* Only used to gather font metrics
*/
private val prepareImage = BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)
private val prepareG = prepareImage.createGraphics()
protected val metrics: FontMetrics
/** The next position to place a glyph in the texture.*/
private var nextX: Int = 0
private var nextY: Int = 0
init {
prepareG.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
prepareG.font = font
metrics = prepareG.fontMetrics
requiredHeight = metrics.height
}
fun range(from: Char, to: Char): FontTextureFactoryViaAWT {
return range(from.toInt(), to.toInt())
}
fun range(from: Int = 32, to: Int = 255): FontTextureFactoryViaAWT {
for (i in from..to) {
val c = i.toChar()
if (font.canDisplay(c)) {
val cWidth = metrics.charWidth(c)
val advance = metrics.charWidth(c).toDouble()
if (nextX + cWidth + xPadding * 2 > maxTextureWidth) {
nextX = 0
nextY += metrics.height + yPadding * 2
}
val glyphData = GlyphData(cWidth.toDouble() + xPadding * 2, advance, nextX, nextY)
nextX += cWidth + xPadding * 2
if (nextX > requiredWidth) {
requiredWidth = nextX
}
glyphDataMap[c] = glyphData
}
}
requiredHeight = nextY
return this
}
open fun create(): FontTexture {
// If no ranges were specified, use the default range of 32..255
if (glyphDataMap.isEmpty()) {
range()
}
val bufferedImage = BufferedImage(requiredWidth, requiredHeight, BufferedImage.TYPE_INT_ARGB)
val g = bufferedImage.createGraphics()
g.font = font
g.paint = java.awt.Color.WHITE
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
glyphDataMap.forEach { c, glyphData ->
g.drawString(c.toString(), glyphData.x + xPadding.toInt(), glyphData.y + metrics.ascent + yPadding.toInt())
}
/* Get pixel data of image */
val pixels = IntArray(requiredWidth * requiredHeight)
bufferedImage.getRGB(0, 0, requiredWidth, requiredHeight, pixels, 0, requiredWidth)
/* Put pixel data into a ByteBuffer, ensuring it is in RGBA order */
val buffer = MemoryUtil.memAlloc(requiredWidth * requiredHeight * 4)
for (y in 0..requiredHeight - 1) {
for (x in 0..requiredWidth - 1) {
/* Pixel format is : 0xAARRGGBB */
val pixel = pixels[y * requiredWidth + x]
buffer.put((pixel shr 16 and 0xFF).toByte()) // R
buffer.put((pixel shr 8 and 0xFF).toByte()) // G
buffer.put((pixel and 0xFF).toByte()) // B
buffer.put((pixel shr 24 and 0xFF).toByte()) // A
}
}
buffer.flip()
val texture = Texture(requiredWidth, requiredHeight, GL11.GL_RGBA, buffer)
MemoryUtil.memFree(buffer)
val glyphs = mutableMapOf<Char, Glyph>()
glyphDataMap.forEach { c, glyphData ->
val rect = YDownRect(
glyphData.x,
glyphData.y,
glyphData.x + glyphData.width.toInt(),
glyphData.y + metrics.height + yPadding * 2)
val pose = Pose(texture, rect)
pose.offsetX = xPadding.toDouble()
pose.offsetY = metrics.height + yPadding.toDouble()
glyphs[c] = Glyph(pose, glyphData.advance)
}
return FontTexture(
glyphs, metrics.height.toDouble(),
leading = metrics.leading.toDouble(),
ascent = metrics.ascent.toDouble(),
descent = metrics.descent.toDouble())
}
}
data class GlyphData(
/** The width of this glyph (i.e. the width of the bounding rectangle which encompases the glyph */
val width: Double,
/** The starting position of the NEXT glyph relative to this one when rendering text. This of course
* does not take into accound kerning. Kerning is not supported by the fonts in Tickle.
*/
val advance: Double,
/** The position of the top of the glyph within the texture image */
val x: Int,
/** The position of the left of the glyph within the texture image */
val y: Int) | gpl-3.0 | 0b4bfaa0d9a46b60c8c0581ed15be88d | 33.625 | 119 | 0.618907 | 4.424837 | false | false | false | false |
paoneJP/AppAuthDemo-Android | app/src/main/java/net/paonejp/kndzyb/appauthdemo/MainActivity.kt | 1 | 12896 | /*
* AppAuth for Android demonstration application.
* Author: Takashi Yahata (@paoneJP)
* Copyright: (c) 2017 Takashi Yahata
* License: MIT License
*/
package net.paonejp.kndzyb.appauthdemo
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import net.openid.appauth.*
import net.paonejp.kndzyb.appauthdemo.util.HttpRequestJsonTask
import net.paonejp.kndzyb.appauthdemo.util.decryptString
import net.paonejp.kndzyb.appauthdemo.util.encryptString
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.net.HttpURLConnection.*
import java.text.DateFormat
import java.util.*
private val ISSUER_URI = "https://accounts.google.com"
private val CLIENT_ID = "999999999999-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"
private val REDIRECT_URI = "net.paonejp.kndzyb.appauthdemo:/cb"
private val SCOPE = "profile"
private val API_URI = "https://www.googleapis.com/oauth2/v3/userinfo"
private val REQCODE_AUTH = 100
private val X_HTTP_NEED_REAUTHZ = -1
private val X_HTTP_ERROR = -9
private val LOG_TAG = "MainActivity"
class MainActivity : AppCompatActivity() {
private lateinit var appAuthState: AuthState
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState != null) {
try {
appAuthState = savedInstanceState
.getString("appAuthState", "{}")
.let { AuthState.jsonDeserialize(it) }
} catch (ex: JSONException) {
val m = Throwable().stackTrace[0]
Log.e(LOG_TAG, "${m}: ${ex}")
appAuthState = AuthState()
}
} else {
val prefs = getSharedPreferences("appAuthPreference", MODE_PRIVATE)
val data = decryptString(this, prefs.getString("appAuthState", null)) ?: "{}"
appAuthState = AuthState.jsonDeserialize(data)
}
if (savedInstanceState != null) {
uAppAuthStateView.text = savedInstanceState.getCharSequence("appAuthStateView")
uResponseView.text = savedInstanceState.getCharSequence("responseView")
uAppAuthStateFullView.text = savedInstanceState.getCharSequence("appAuthStateFullView")
} else {
doShowAppAuthState()
uResponseView.text = getText(R.string.msg_app_start)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQCODE_AUTH) {
handleAuthorizationResponse(data)
}
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.putString("appAuthState", appAuthState.jsonSerializeString())
outState?.putCharSequence("appAuthStateView", uAppAuthStateView.text)
outState?.putCharSequence("responseView", uResponseView.text)
outState?.putCharSequence("appAuthStateFullView", uAppAuthStateFullView.text)
}
override fun onPause() {
super.onPause()
getSharedPreferences("appAuthPreference", MODE_PRIVATE)
.edit()
.putString("appAuthState", encryptString(this, appAuthState.jsonSerializeString()))
.apply()
}
fun onClickSigninButton(view: View) {
startAuthorization()
}
fun onClickSignoutButton(view: View) {
revokeAuthorization()
}
fun onClickCallApiButton(view: View) {
showApiResult()
}
fun onClickShowStatusButton(view: View) {
showAppAuthStatus()
}
fun onClickTokenRefreshButton(view: View) {
tokenRefreshAndShowApiResult()
}
private fun startAuthorization() {
AuthorizationServiceConfiguration.fetchFromIssuer(Uri.parse(ISSUER_URI), { config, ex ->
if (config != null) {
val req = AuthorizationRequest
.Builder(config, CLIENT_ID, ResponseTypeValues.CODE, Uri.parse(REDIRECT_URI))
.setScope(SCOPE)
.build()
val intent = AuthorizationService(this).getAuthorizationRequestIntent(req)
startActivityForResult(intent, REQCODE_AUTH)
} else {
if (ex != null) {
val m = Throwable().stackTrace[0]
Log.e(LOG_TAG, "${m}: ${ex}")
}
whenAuthorizationFails(ex)
}
})
}
private fun handleAuthorizationResponse(data: Intent?) {
if (data == null) {
val m = Throwable().stackTrace[0]
Log.e(LOG_TAG, "${m}: unexpected intent call")
return
}
val resp = AuthorizationResponse.fromIntent(data)
val ex = AuthorizationException.fromIntent(data)
appAuthState.update(resp, ex)
if (ex != null || resp == null) {
val m = Throwable().stackTrace[0]
Log.e(LOG_TAG, "${m}: ${ex}")
whenAuthorizationFails(ex)
return
}
AuthorizationService(this)
.performTokenRequest(resp.createTokenExchangeRequest(), { resp2, ex2 ->
appAuthState.update(resp2, ex2)
if (resp2 != null) {
whenAuthorizationSucceeds()
} else {
whenAuthorizationFails(ex2)
}
})
}
// 認証成功時の処理を書く。
// Write program to be executed when authorization succeeds.
private fun whenAuthorizationSucceeds() {
uResponseView.text = getText(R.string.msg_auth_ok)
doShowAppAuthState()
}
// 認証エラー時の処理を書く。
// Write program to be executed when authorization fails.
private fun whenAuthorizationFails(ex: AuthorizationException?) {
uResponseView.text = "%s\n\n%s".format(getText(R.string.msg_auth_ng), ex?.message)
doShowAppAuthState()
}
private fun revokeAuthorization() {
val uri = appAuthState.authorizationServiceConfiguration?.discoveryDoc?.docJson
?.opt("revocation_endpoint") as String?
if (uri == null) {
appAuthState = AuthState()
whenRevokeAuthorizationSucceeds()
return
}
val param = "token=${appAuthState.refreshToken}&token_type_hint=refresh_token"
HttpRequestJsonTask(uri, param, null, { code, data, ex ->
when (code) {
HTTP_OK -> {
appAuthState = AuthState()
whenRevokeAuthorizationSucceeds()
}
HTTP_BAD_REQUEST -> {
// RFC 7009 に示されているように、すでに無効なトークンの無効化リクエストに
// 対しサーバーは HTTP 200 を応答するが、一部のサーバーはエラーを応答する
// ことがある。Google Accounts の場合、 HTTP 400 で "invalid_token" エラー
// を返すため、それを成功応答として処理する。
// As described in RFC 7009, the server responds with HTTP 200 for revocation
// request to already invalidated token, but some servers may respond with an
// error. Google Accounts returns "invalid_token" error with HTTP 400, it must
// be treated as a successful response.
if (data?.optString("error") == "invalid_token") {
appAuthState = AuthState()
whenRevokeAuthorizationSucceeds()
return@HttpRequestJsonTask
}
val msg = "Server returned HTTP response code: %d for URL: %s with message: %s"
.format(code, uri, data.toString())
whenRevokeAuthorizationFails(IOException(msg))
}
else -> whenRevokeAuthorizationFails(ex)
}
}).execute()
}
// 認証状態取り消し時の処理を書く。
// Write program to be executed when revoking authorization succeeds.
private fun whenRevokeAuthorizationSucceeds() {
uResponseView.text = getText(R.string.msg_auth_revoke_ok)
doShowAppAuthState()
}
// 認証状態取り消し時の処理を書く。
// Write program to be executed when revoking authorization fails.
private fun whenRevokeAuthorizationFails(ex: Exception?) {
uResponseView.text = "%s\n\n%s"
.format(getText(R.string.msg_auth_revoke_ng), ex ?: "")
doShowAppAuthState()
}
private fun showAppAuthStatus() {
uResponseView.text = getText(R.string.msg_show_auth_state)
doShowAppAuthState()
}
private fun doShowAppAuthState() {
val t = appAuthState
.accessTokenExpirationTime
?.let { DateFormat.getDateTimeInstance().format(Date(it)) }
uAppAuthStateView.text = JSONObject()
.putOpt("isAuthorized", appAuthState.isAuthorized)
.putOpt("accessToken", appAuthState.accessToken)
.putOpt("accessTokenExpirationTime", appAuthState.accessTokenExpirationTime)
.putOpt("accessTokenExpirationTime_readable", t)
.putOpt("refreshToken", appAuthState.refreshToken)
.putOpt("needsTokenRefresh", appAuthState.needsTokenRefresh)
.toString(2)
.replace("\\/", "/")
uAppAuthStateFullView.text = appAuthState
.jsonSerialize()
.toString(2)
.replace("\\/", "/")
uScrollView.scrollY = 0
}
// APIを呼び出す処理を書く。
// Write program calling the API.
private fun showApiResult() {
httpGetJson(API_URI, { code, data, ex -> showApiResultCallback(code, data, ex) })
}
private fun tokenRefreshAndShowApiResult() {
appAuthState.needsTokenRefresh = true
showApiResult()
}
// APIレスポンスに対する処理を書く。
// Write program to be executed when API responded.
private fun showApiResultCallback(code: Int, data: JSONObject?, ex: Exception?) {
when (code) {
X_HTTP_NEED_REAUTHZ, HTTP_UNAUTHORIZED -> whenReauthorizationRequired(ex)
HTTP_OK -> {
uResponseView.text = "%s\n\n%s"
.format(getText(R.string.msg_api_ok),
data?.toString(2)?.replace("\\/", "/"))
}
else -> {
uResponseView.text = "%s\n\n%d\n%s\n%s"
.format(getText(R.string.msg_api_error),
code, data ?: "", ex ?: "")
}
}
doShowAppAuthState()
}
// 再認証が必要な状態の時の処理を書く。
// Write program to be executed when reauthorization required.
private fun whenReauthorizationRequired(ex: Exception?) {
uResponseView.text = "%s\n\n%s"
.format(getText(R.string.msg_reauthz_required), ex ?: "")
doShowAppAuthState()
}
private fun httpGetJson(uri: String,
callback: (code: Int, json: JSONObject?, ex: Exception?) -> Unit) {
val service = AuthorizationService(this)
appAuthState.performActionWithFreshTokens(service, { accessToken, _, ex ->
if (ex != null) {
val m = Throwable().stackTrace[0]
Log.e(LOG_TAG, "${m}: ${ex}")
if (appAuthState.isAuthorized) {
callback(X_HTTP_ERROR, null, ex)
} else {
callback(X_HTTP_NEED_REAUTHZ, null, ex)
}
} else {
if (accessToken == null) {
callback(X_HTTP_ERROR, null, null)
} else {
HttpRequestJsonTask(uri, null, accessToken, { code, data, ex2 ->
callback(code, data, ex2)
}).execute()
}
}
})
}
}
| mit | 95c49d39634871bc559e4fb71af71402 | 34.662757 | 101 | 0.568309 | 4.531352 | false | false | false | false |
cketti/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageListActivityConfig.kt | 1 | 3633 | package com.fsck.k9.activity
import com.fsck.k9.K9
import com.fsck.k9.SwipeAction
import com.fsck.k9.preferences.AppTheme
import com.fsck.k9.preferences.GeneralSettingsManager
import com.fsck.k9.preferences.SubTheme
data class MessageListActivityConfig(
val appTheme: AppTheme,
val isShowUnifiedInbox: Boolean,
val isShowMessageListStars: Boolean,
val isShowCorrespondentNames: Boolean,
val isMessageListSenderAboveSubject: Boolean,
val isShowContactName: Boolean,
val isChangeContactNameColor: Boolean,
val isShowContactPicture: Boolean,
val isColorizeMissingContactPictures: Boolean,
val isUseBackgroundAsUnreadIndicator: Boolean,
val contactNameColor: Int,
val messageViewTheme: SubTheme,
val messageListPreviewLines: Int,
val splitViewMode: K9.SplitViewMode,
val fontSizeMessageListSubject: Int,
val fontSizeMessageListSender: Int,
val fontSizeMessageListDate: Int,
val fontSizeMessageListPreview: Int,
val fontSizeMessageViewSender: Int,
val fontSizeMessageViewTo: Int,
val fontSizeMessageViewCC: Int,
val fontSizeMessageViewBCC: Int,
val fontSizeMessageViewAdditionalHeaders: Int,
val fontSizeMessageViewSubject: Int,
val fontSizeMessageViewDate: Int,
val fontSizeMessageViewContentAsPercent: Int,
val swipeRightAction: SwipeAction,
val swipeLeftAction: SwipeAction,
) {
companion object {
fun create(generalSettingsManager: GeneralSettingsManager): MessageListActivityConfig {
val settings = generalSettingsManager.getSettings()
return MessageListActivityConfig(
appTheme = settings.appTheme,
isShowUnifiedInbox = K9.isShowUnifiedInbox,
isShowMessageListStars = K9.isShowMessageListStars,
isShowCorrespondentNames = K9.isShowCorrespondentNames,
isMessageListSenderAboveSubject = K9.isMessageListSenderAboveSubject,
isShowContactName = K9.isShowContactName,
isChangeContactNameColor = K9.isChangeContactNameColor,
isShowContactPicture = K9.isShowContactPicture,
isColorizeMissingContactPictures = K9.isColorizeMissingContactPictures,
isUseBackgroundAsUnreadIndicator = K9.isUseBackgroundAsUnreadIndicator,
contactNameColor = K9.contactNameColor,
messageViewTheme = settings.messageViewTheme,
messageListPreviewLines = K9.messageListPreviewLines,
splitViewMode = K9.splitViewMode,
fontSizeMessageListSubject = K9.fontSizes.messageListSubject,
fontSizeMessageListSender = K9.fontSizes.messageListSender,
fontSizeMessageListDate = K9.fontSizes.messageListDate,
fontSizeMessageListPreview = K9.fontSizes.messageListPreview,
fontSizeMessageViewSender = K9.fontSizes.messageViewSender,
fontSizeMessageViewTo = K9.fontSizes.messageViewTo,
fontSizeMessageViewCC = K9.fontSizes.messageViewCC,
fontSizeMessageViewBCC = K9.fontSizes.messageViewBCC,
fontSizeMessageViewAdditionalHeaders = K9.fontSizes.messageViewAdditionalHeaders,
fontSizeMessageViewSubject = K9.fontSizes.messageViewSubject,
fontSizeMessageViewDate = K9.fontSizes.messageViewDate,
fontSizeMessageViewContentAsPercent = K9.fontSizes.messageViewContentAsPercent,
swipeRightAction = K9.swipeRightAction,
swipeLeftAction = K9.swipeLeftAction,
)
}
}
}
| apache-2.0 | 5b9fb7cb4a67bbf7e7444039b25c06b6 | 47.44 | 97 | 0.719791 | 5.197425 | false | false | false | false |
coil-kt/coil | coil-base/src/main/java/coil/disk/DiskCache.kt | 1 | 7021 | package coil.disk
import android.os.StatFs
import androidx.annotation.FloatRange
import coil.annotation.ExperimentalCoilApi
import java.io.File
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import okio.Closeable
import okio.FileSystem
import okio.Path
import okio.Path.Companion.toOkioPath
/**
* An LRU cache of files.
*/
interface DiskCache {
/** The current size of the cache in bytes. */
@ExperimentalCoilApi
val size: Long
/** The maximum size of the cache in bytes. */
@ExperimentalCoilApi
val maxSize: Long
/** The directory where the cache stores its data. */
@ExperimentalCoilApi
val directory: Path
/** The file system that contains the cache's files. */
@ExperimentalCoilApi
val fileSystem: FileSystem
/**
* Get the entry associated with [key].
*
* IMPORTANT: **You must** call either [Snapshot.close] or [Snapshot.closeAndEdit] when finished
* reading the snapshot. An open snapshot prevents editing the entry or deleting it on disk.
*/
@ExperimentalCoilApi
operator fun get(key: String): Snapshot?
/**
* Edit the entry associated with [key].
*
* IMPORTANT: **You must** call one of [Editor.commit], [Editor.commitAndGet], or [Editor.abort]
* to complete the edit. An open editor prevents opening new [Snapshot]s or opening a new
* [Editor].
*/
@ExperimentalCoilApi
fun edit(key: String): Editor?
/**
* Delete the entry referenced by [key].
*
* @return 'true' if [key] was removed successfully. Else, return 'false'.
*/
@ExperimentalCoilApi
fun remove(key: String): Boolean
/** Delete all entries in the disk cache. */
@ExperimentalCoilApi
fun clear()
/**
* A snapshot of the values for an entry.
*
* IMPORTANT: You must **only read** [metadata] or [data]. Mutating either file can corrupt the
* disk cache. To modify the contents of those files, use [edit].
*/
@ExperimentalCoilApi
interface Snapshot : Closeable {
/** Get the metadata for this entry. */
val metadata: Path
/** Get the data for this entry. */
val data: Path
/** Close the snapshot to allow editing. */
override fun close()
/** Close the snapshot and call [edit] for this entry atomically. */
fun closeAndEdit(): Editor?
}
/**
* Edits the values for an entry.
*
* Calling [metadata] or [data] marks that file as dirty so it will be persisted to disk
* if this editor is committed.
*
* IMPORTANT: You must **only read or modify the contents** of [metadata] or [data].
* Renaming, locking, or other mutating file operations can corrupt the disk cache.
*/
@ExperimentalCoilApi
interface Editor {
/** Get the metadata for this entry. */
val metadata: Path
/** Get the data for this entry. */
val data: Path
/** Commit the edit so the changes are visible to readers. */
fun commit()
/** Commit the edit and open a new [Snapshot] atomically. */
fun commitAndGet(): Snapshot?
/** Abort the edit. Any written data will be discarded. */
fun abort()
}
class Builder {
private var directory: Path? = null
private var fileSystem = FileSystem.SYSTEM
private var maxSizePercent = 0.02 // 2%
private var minimumMaxSizeBytes = 10L * 1024 * 1024 // 10MB
private var maximumMaxSizeBytes = 250L * 1024 * 1024 // 250MB
private var maxSizeBytes = 0L
private var cleanupDispatcher = Dispatchers.IO
/**
* Set the [directory] where the cache stores its data.
*
* IMPORTANT: It is an error to have two [DiskCache] instances active in the same
* directory at the same time as this can corrupt the disk cache.
*/
fun directory(directory: File) = directory(directory.toOkioPath())
/**
* Set the [directory] where the cache stores its data.
*
* IMPORTANT: It is an error to have two [DiskCache] instances active in the same
* directory at the same time as this can corrupt the disk cache.
*/
fun directory(directory: Path) = apply {
this.directory = directory
}
/**
* Set the [fileSystem] where the cache stores its data, usually [FileSystem.SYSTEM].
*/
fun fileSystem(fileSystem: FileSystem) = apply {
this.fileSystem = fileSystem
}
/**
* Set the maximum size of the disk cache as a percentage of the device's free disk space.
*/
fun maxSizePercent(@FloatRange(from = 0.0, to = 1.0) percent: Double) = apply {
require(percent in 0.0..1.0) { "size must be in the range [0.0, 1.0]." }
this.maxSizeBytes = 0
this.maxSizePercent = percent
}
/**
* Set the minimum size of the disk cache in bytes.
* This is ignored if [maxSizeBytes] is set.
*/
fun minimumMaxSizeBytes(size: Long) = apply {
require(size > 0) { "size must be > 0." }
this.minimumMaxSizeBytes = size
}
/**
* Set the maximum size of the disk cache in bytes.
* This is ignored if [maxSizeBytes] is set.
*/
fun maximumMaxSizeBytes(size: Long) = apply {
require(size > 0) { "size must be > 0." }
this.maximumMaxSizeBytes = size
}
/**
* Set the maximum size of the disk cache in bytes.
*/
fun maxSizeBytes(size: Long) = apply {
require(size > 0) { "size must be > 0." }
this.maxSizePercent = 0.0
this.maxSizeBytes = size
}
/**
* Set the [CoroutineDispatcher] that cache size trim operations will be executed on.
*/
fun cleanupDispatcher(dispatcher: CoroutineDispatcher) = apply {
this.cleanupDispatcher = dispatcher
}
/**
* Create a new [DiskCache] instance.
*/
fun build(): DiskCache {
val directory = checkNotNull(directory) { "directory == null" }
val maxSize = if (maxSizePercent > 0) {
try {
val stats = StatFs(directory.toFile().absolutePath)
val size = maxSizePercent * stats.blockCountLong * stats.blockSizeLong
size.toLong().coerceIn(minimumMaxSizeBytes, maximumMaxSizeBytes)
} catch (_: Exception) {
minimumMaxSizeBytes
}
} else {
maxSizeBytes
}
return RealDiskCache(
maxSize = maxSize,
directory = directory,
fileSystem = fileSystem,
cleanupDispatcher = cleanupDispatcher
)
}
}
}
| apache-2.0 | 4d0c0074279d2b2301f23d58862b419e | 31.206422 | 100 | 0.58966 | 4.769701 | false | false | false | false |
christophpickl/gadsu | src/test/kotlin/at/cpickl/gadsu/testinfra/treatment.kt | 1 | 1160 | package at.cpickl.gadsu.testinfra
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.service.minutes
import at.cpickl.gadsu.treatment.Treatment
@Suppress("UNUSED")
fun Treatment.Companion.unsavedValidInstance(clientId: String) =
Treatment(
id = null,
clientId = clientId,
created = TEST_DATETIME1,
number = 1,
date = TEST_DATETIME_FOR_TREATMENT_DATE,
duration = minutes(60),
aboutDiscomfort = "",
aboutDiagnosis = "",
aboutContent = "",
aboutFeedback = "",
aboutHomework = "",
aboutUpcoming = "",
note = "note",
dynTreatments = emptyList(),
treatedMeridians = emptyList())
fun Treatment.Companion.unsavedValidInstance(client: Client) =
unsavedValidInstance(client.id!!)
fun Treatment.Companion.savedValidInstance(
clientId: String,
treatmentId: String = TEST_UUID1,
number: Int = 1
) =
unsavedValidInstance(clientId).copy(id = treatmentId, number = number)
| apache-2.0 | 1633d6e61c7a8c849324c6327142a4c4 | 31.222222 | 78 | 0.575862 | 4.621514 | false | true | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/rx/BusDirectionObserver.kt | 1 | 4629 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.rx
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ListView
import androidx.appcompat.app.AlertDialog
import fr.cph.chicago.R
import fr.cph.chicago.core.App
import fr.cph.chicago.core.activity.BusBoundActivity
import fr.cph.chicago.core.activity.map.BusMapActivity
import fr.cph.chicago.core.adapter.PopupBusAdapter
import fr.cph.chicago.core.model.BusDirections
import fr.cph.chicago.core.model.BusRoute
import fr.cph.chicago.util.Util
import io.reactivex.rxjava3.core.SingleObserver
import io.reactivex.rxjava3.disposables.Disposable
import timber.log.Timber
class BusDirectionObserver(private val viewClickable: View, private val parent: ViewGroup, private val convertView: View, private val busRoute: BusRoute) : SingleObserver<BusDirections> {
companion object {
private val util = Util
}
override fun onSubscribe(d: Disposable) {}
override fun onSuccess(busDirections: BusDirections) {
val lBusDirections = busDirections.busDirections
val data = lBusDirections
.map { busDir -> busDir.text }
.toMutableList()
data.add(parent.context.getString(R.string.message_see_all_buses_on_line) + busDirections.id)
val vi = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val popupView = vi.inflate(R.layout.popup_bus, parent, false)
val listView = popupView.findViewById<ListView>(R.id.details)
val ada = PopupBusAdapter(parent.context.applicationContext, data)
listView.adapter = ada
val alertDialog = AlertDialog.Builder(parent.context)
alertDialog.setAdapter(ada) { _, pos ->
val extras = Bundle()
if (pos != data.size - 1) {
val intent = Intent(parent.context, BusBoundActivity::class.java)
extras.putString(parent.context.getString(R.string.bundle_bus_route_id), busRoute.id)
extras.putString(parent.context.getString(R.string.bundle_bus_route_name), busRoute.name)
extras.putString(parent.context.getString(R.string.bundle_bus_bound), lBusDirections[pos].text)
extras.putString(parent.context.getString(R.string.bundle_bus_bound_title), lBusDirections[pos].text)
intent.putExtras(extras)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
parent.context.applicationContext.startActivity(intent)
} else {
val busDirectionArray = arrayOfNulls<String>(lBusDirections.size)
var i = 0
for (busDir in lBusDirections) {
busDirectionArray[i++] = busDir.text
}
val intent = Intent(parent.context, BusMapActivity::class.java)
extras.putString(parent.context.getString(R.string.bundle_bus_route_id), busDirections.id)
extras.putStringArray(parent.context.getString(R.string.bundle_bus_bounds), busDirectionArray)
intent.putExtras(extras)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
parent.context.applicationContext.startActivity(intent)
}
}
alertDialog.setOnCancelListener { convertView.visibility = LinearLayout.GONE }
val dialog = alertDialog.create()
dialog.show()
dialog.window?.setLayout((App.instance.screenWidth * 0.7).toInt(), ViewGroup.LayoutParams.WRAP_CONTENT)
convertView.visibility = LinearLayout.GONE
viewClickable.isClickable = true
}
override fun onError(throwable: Throwable) {
viewClickable.isClickable = true
util.handleConnectOrParserException(throwable, convertView)
convertView.visibility = LinearLayout.GONE
Timber.e(throwable, "Error while loading bus directions")
}
}
| apache-2.0 | e4982c55a9da47041b5b1e29e96fe802 | 43.509615 | 187 | 0.701879 | 4.322129 | false | false | false | false |
dector/tlamp | android/app/src/main/kotlin/io/github/dector/tlamp/light/LightFragment.kt | 1 | 2970 | package io.github.dector.tlamp.light
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.github.dector.tlamp.R
import io.github.dector.tlamp.color_wheel.ColorWheelView
import io.github.dector.tlamp.connection.ILampDataLoader
import kotlinx.android.synthetic.main.fragment_light.*
class LightFragment(val dataLoader: ILampDataLoader) : Fragment() {
private var lampColor = 0
private var selectedColor = 0
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?)
= inflater?.inflate(R.layout.fragment_light, container, false)
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
light_color_picker.colorSelectedListener = object : ColorWheelView.OnColorSelectedListener {
override fun onColorSelected(color: Int) {
selectedColor = color
if (! areButtonsDisplayed()) {
displayButtons(true)
}
if (light_preview_checkbox.isChecked) {
uploadColorToLamp(color, permanent = false)
}
}
}
light_revert_button.setOnClickListener {
restoreLampColor()
}
light_save_button.setOnClickListener {
val newColor = selectedColor
uploadColorToLamp(newColor)
}
light_preview_checkbox.setOnCheckedChangeListener { button, checked ->
if (checked)
uploadColorToLamp(selectedColor, permanent = false)
}
}
override fun onStart() {
super.onStart()
reloadCurrentColor()
}
override fun onStop() {
super.onStop()
restoreLampColor()
}
private fun reloadCurrentColor() {
dataLoader.getCurrentColor(onSuccess = { onColorLoaded(it) }) // Not safe. Unknown color can be received here
displayButtons(false)
}
private fun restoreLampColor() {
uploadColorToLamp(lampColor)
}
private fun uploadColorToLamp(color: Int, permanent: Boolean = true) {
dataLoader.setStaticColor(color,
onSuccess = { if (permanent) onColorSaved(color) })
}
private fun onColorLoaded(color: Int) {
lampColor = color
selectedColor = color
light_color_picker.setSelectedColor(selectedColor)
}
private fun onColorSaved(color: Int) {
onColorLoaded(color)
displayButtons(false)
}
private fun displayButtons(display: Boolean) {
light_revert_button.visibility = if (display) View.VISIBLE else View.INVISIBLE
light_save_button.visibility = if (display) View.VISIBLE else View.INVISIBLE
}
private fun areButtonsDisplayed() = light_revert_button.visibility == View.VISIBLE
&& light_save_button.visibility == View.VISIBLE
} | mit | 6343114872f2b1826ea721ee1b27f303 | 29.316327 | 117 | 0.655219 | 4.597523 | false | false | false | false |
UKandAndroid/AndroidHelper | app/src/main/java/com/helper/lib/UiHelper.kt | 1 | 15388 | package com.stryde.base.libs
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Context
import android.graphics.Typeface
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
// Whats new Version 1.4.0
// converted to kotlin
// Get view with tag
// added method getWidth, getHeight
// attempt to fix bug where UiHelper won't work if root object is changed
// fix text color resource bug
// Removed KB detect as it's implemented in flow
// Added support for chain calls e.g ui.setText(R.id.text, "test").setColor(iColor).setBg(R.drawable.bg)
// Helper class for working with android Views
class UiHelper {
var curView: View? = null
private var arId: IntArray? = null // Store loaded arView arId, so they can checked against.
private var arView: Array<View?>? = null // keeps reference of loaded views, so they are not loaded again..
internal lateinit var uiView: ViewGroup
private lateinit var context: Context
private var progressBar: ProgressBar? = null
private var progressDialog: ProgressDialog? = null
private var layoutProgress: RelativeLayout? = null
// CONSTRUCTORS
constructor() {}
constructor(v: View) {
setRootView(v)
}
fun setRootView(v: View) {
uiView = v as ViewGroup
arId = IntArray(256) // Store loaded arView arId, so they can checked against.
arView = arrayOfNulls(256) // keeps reference of loaded views, so they are not loaded again..
context = uiView.context
mainThread = Handler(Looper.getMainLooper())
}
fun getRootView(): ViewGroup? {
return uiView
}
fun textView(id: Int): TextView {
return getView(id) as TextView
}
fun checkBox(id: Int): CheckBox {
return getView(id) as CheckBox
}
fun editText(id: Int): EditText {
return getView(id) as EditText
}
fun button(id: Int): Button {
return getView(id) as Button
}
fun setTag(id: Int, tag: Int) {
setTag(id, Integer.toString(tag))
}
fun setTag(id: Int, tag: String?) {
getView(id).tag = tag
}
fun getTag(id: Int): String {
return getView(id).tag as String
}
// Methods to set visibility
fun setVisible(id: Int) {
getView(id).visibility = View.VISIBLE
}
fun setInvisible(id: Int) {
getView(id).visibility = View.INVISIBLE
}
fun setGone(id: Int) {
getView(id).visibility = View.GONE
}
fun setVisibility(id: Int, visibility: Int) {
getView(id).visibility = visibility
}
fun getDimenRes(iRes: Int): Float {
return context.resources.getDimension(iRes)
}
fun setClickable(id: Int, bTrue: Boolean) {
getView(id).isClickable = bTrue
}
fun getStringRes(iResString: Int): String {
return context.resources.getString(iResString)
}
fun showToast(sMessage: String?) {
Toast.makeText(context, sMessage, Toast.LENGTH_SHORT).show()
}
fun showToast(iResString: Int) {
Toast.makeText(context, getStringRes(iResString), Toast.LENGTH_SHORT).show()
}
fun getText(id: Int): String {
return (getView(id) as TextView).text.toString()
}
fun setText(lText: Long): UiHelper {
return setText(curView, java.lang.Long.toString(lText))
}
fun setText(id: Int, lText: Long): UiHelper {
return setText(getView(id), java.lang.Long.toString(lText))
}
fun setText(fText: Float): UiHelper {
return setText(curView, java.lang.Float.toString(fText))
}
fun setText(id: Int, fText: Float): UiHelper {
return setText(getView(id), java.lang.Float.toString(fText))
}
fun setText(iText: Int): UiHelper {
return setText(curView, Integer.toString(iText))
}
fun setText(id: Int, iText: Int): UiHelper {
return setText(getView(id), Integer.toString(iText))
}
fun setText(sText: String): UiHelper {
return setText(curView, sText)
}
fun setText(id: Int, sText: String): UiHelper {
return setText(getView(id), sText)
}
fun setTextRes(iResString: Int): UiHelper {
return setTextRes(curView, iResString)
}
fun setTextRes(id: Int, iResString: Int): UiHelper {
return setTextRes(getView(id), iResString)
}
private fun setText(view: View?, sText: String): UiHelper {
(view as TextView?)!!.text = sText
return this
}
private fun setTextRes(view: View?, iResString: Int): UiHelper {
(view as TextView?)!!.text = context.resources.getString(iResString)
return this
}
private fun setGravity(id: Int, iGravity: Int): UiHelper {
setGravity(getView(id), iGravity)
return this
}
private fun setGravity(view: View?, iGravity: Int): UiHelper {
(view as TextView?)!!.gravity = iGravity
return this
}
fun setGravity(iGravity: Int): UiHelper {
setGravity(curView, iGravity)
return this
}
// METHOD - sets Background for a View
fun setBackground(iResId: Int): UiHelper {
setBackground(curView!!, iResId)
return this
}
fun setBackground(id: Int, iResId: Int): UiHelper {
setBackground(getView(id), iResId)
return this
}
private fun setBackground(view: View, iResId: Int): UiHelper { // Padding is lost when new background is set, so we need to reapply it.
val pL = view.paddingLeft
val pT = view.paddingTop
val pR = view.paddingRight
val pB = view.paddingBottom
view.setBackgroundResource(iResId)
view.setPadding(pL, pT, pR, pB)
return this
}
// METHOD - sets text for Button, TextView, EditText
fun setHint(id: Int, sText: String?): UiHelper {
(getView(id) as TextView).hint = sText
return this
}
// METHOD - Enables or disables a view
fun setEnabled(bEnable: Boolean): UiHelper {
return setEnabled(curView, bEnable)
}
fun setEnabled(id: Int, bEnable: Boolean): UiHelper {
return setEnabled(getView(id), bEnable)
}
private fun setEnabled(view: View?, bEnable: Boolean): UiHelper {
view!!.isEnabled = bEnable
return this
}
// METHOD - sets Text color for Button, TextView, EditText
fun setTextColorRes(id: Int, iColorRes: Int): UiHelper {
return setTextColor(getView(id), getColorRes(iColorRes))
}
fun setTextColorRes(iColorRes: Int): UiHelper {
return setTextColor(curView, getColorRes(iColorRes))
}
fun setTextColor(iRGB: Int): UiHelper {
return setTextColor(curView, iRGB)
}
fun setTextColor(id: Int, iRGB: Int): UiHelper {
return setTextColor(getView(id), iRGB)
}
private fun setTextColor(v: View?, iRGB: Int): UiHelper {
(v as TextView?)!!.setTextColor(iRGB)
return this
}
// METHOD get/set width, height
fun getWidth(iResId: Int): Int {
return getView(iResId).width
}
fun getHeight(iResId: Int): Int {
return getView(iResId).height
}
val width: Int
get() = curView?.width ?: 0
val height: Int
get() = curView?.height ?: 0
// METHOD - sets Text color Size Button, TextView, EditText, Note dimension resources are returned as pixels, that's why TypedValue.COMPLEX_UNIT_PX for resouce
fun setTextSizeRes(id: Int, iRes: Int): UiHelper {
return setTextSize(id, TypedValue.COMPLEX_UNIT_PX, getDimenRes(iRes))
}
fun setTextSizeRes(id: Int, iUnit: Int, iRes: Int): UiHelper {
return setTextSize(id, iUnit, getDimenRes(iRes))
}
fun setTextSize(id: Int, iSize: Float): UiHelper {
return setTextSize(id, TypedValue.COMPLEX_UNIT_SP, iSize)
}
fun setTextSize(id: Int, iUnit: Int, iSize: Float): UiHelper {
(getView(id) as TextView).setTextSize(iUnit, iSize)
return this
}
// METHOD - sets Text color for Button, TextView, EditText
fun setSpinSelection(iId: Int, iSel: Int) {
(getView(iId) as Spinner).setSelection(iSel)
}
/*
fun setSpinData(iId: Int, iArrId: Int): ArrayAdapter<String> {
return setSpinData(iId, context!!.resources.getStringArray(iArrId), R.layout.simple_list_item_single_choice)
}
fun setSpinData(iId: Int, iArrId: Int, iLayout: Int): ArrayAdapter<String> {
return setSpinData(iId, context!!.resources.getStringArray(iArrId), iLayout)
}
fun setSpinData(iId: Int, arr: Array<String>?, iLayout: Int): ArrayAdapter<String> {
val spin = getView(iId) as Spinner
val adaptSpin = ArrayAdapter(context, iLayout, arr)
spin.adapter = adaptSpin
return adaptSpin
}*/
// METHOD - sets Text color for Button, TextView, EditText
fun setTextBold(id: Int, bTrue: Boolean): UiHelper {
(getView(id) as TextView).setTypeface(null, if (bTrue) Typeface.BOLD else Typeface.NORMAL)
return this
}
// METHOD - Checks/Un-checks a check box, toggle and switch
fun setToggle(id: Int, bCheck: Boolean): UiHelper? { return setState(id, bCheck) }
fun setSwitch(id: Int, bCheck: Boolean): UiHelper? { return setState(id, bCheck) }
fun setState(id: Int, bCheck: Boolean): UiHelper? {
val checkBox = getView(id) as CompoundButton
checkBox.isChecked = bCheck
return this
}
// METHOD returns color from resource id
fun getColorRes(iRes: Int): Int {
return context.resources.getColor(iRes)
}
// METHOD - shows progress bar
fun showProgress(context: Context?) {
if (layoutProgress == null) {
layoutProgress = RelativeLayout(context)
progressBar = ProgressBar(context)
progressBar!!.isIndeterminate = true
val rlp = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT)
layoutProgress!!.layoutParams = rlp
layoutProgress!!.addView(progressBar)
uiView.addView(layoutProgress)
layoutProgress!!.bringToFront()
layoutProgress!!.gravity = Gravity.CENTER_HORIZONTAL or Gravity.CENTER_VERTICAL
}
layoutProgress!!.visibility = View.VISIBLE
}
// METHOD - shows progress bar
fun showProgress(context: Context?, sMessage: String?) {
if (progressDialog == null) {
progressDialog = ProgressDialog(context)
}
progressDialog!!.setMessage(sMessage)
progressDialog!!.isIndeterminate = true
progressDialog!!.show()
}
// METHOD - Hides progress bar
fun hideProgress() {
if (layoutProgress != null) {
layoutProgress!!.visibility = View.GONE
}
if (progressDialog != null) {
progressDialog!!.hide()
progressDialog!!.dismiss()
}
}
// METHOD - sets onClickListener
fun setOnClickListener(id: Int, listener: View.OnClickListener): View.OnClickListener {
getView(id).setOnClickListener(listener)
return listener
}
// METHOD - Returns view either from saved arView or by findViewById() method
fun getView(id: Int): View {
val index = (id and 0xFF).toInt()
if (arId!![index] != id) {
arId!![index] = id
arView!![index] = uiView.findViewById(id)
}
curView = arView!![index]
return curView!!
}
fun getViewWithTag(tag: Any?): View {
val v = uiView.findViewWithTag<View>(tag)
if (v != null) {
@SuppressLint("ResourceType") val index = (v.id and 0xFF).toInt()
arView!![index] = v
}
return v.also { curView = it }
}
@JvmOverloads
fun showKeyboard(v: View? = uiView) {
if (v != null) {
v.requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(v, 0)
} else {
Log.e(LOG_TAG, "Show Keyboard ERROR, rootView/supplied view is null")
}
}
@JvmOverloads
fun hideKeyboard(v: View? = uiView) {
if (v != null) {
v.requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(v.windowToken, 0)
} else {
Log.e(LOG_TAG, "Hide keyboard ERROR, rootView/supplied view is null")
}
}
// METHOD release resources
fun release() {
mainThread!!.removeCallbacksAndMessages(null)
curView = null
arId = null
arView = null
layoutProgress = null
progressBar = null
progressDialog = null
mainThread = null
}
// METHOD - Convert pixels to dp
fun pxToDp(iPixels: Int): Int {
val displayMetrics = context.resources.displayMetrics
return Math.round(iPixels / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT))
}
// METHOD - Convert dp to pixels
fun dpToPx(dp: Int): Int {
val r = context.resources
val displayMetrics = r.displayMetrics
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT))
}
val isMainThread: Boolean
get() = Looper.myLooper() == Looper.getMainLooper()
val isBgThread: Boolean
get() = Looper.myLooper() != Looper.getMainLooper()
fun ifBgThread(r: Runnable?): Boolean {
if (Looper.myLooper() != Looper.getMainLooper()) {
mainThread!!.post(r)
return true
}
return false
}
fun getIntRes(iResId: Int): Int {
return context.resources.getInteger(iResId)
}
// METHOD - sets Text color for Button, TextView, EditText
fun setTypeface(id: Int, font: Typeface?) {
val view = getView(id)
if (Looper.myLooper() == Looper.getMainLooper()) { // if current thread is main thread
(view as TextView).setTypeface(font, Typeface.NORMAL)
} else { // Update it on main thread
Handler(Looper.getMainLooper()).post { (view as TextView).setTypeface(font, Typeface.NORMAL) }
}
}
companion object {
private var mainThread: Handler? = null
private const val LOG_TAG = "UiHelper"
// METHOD - Convert pixels to dp
fun pxToDp(con: Context, iPixels: Int): Int {
val displayMetrics = con.resources.displayMetrics
return Math.round(iPixels / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT))
}
}
} | gpl-2.0 | 719b18f4bbdf10fa1a4a267454347db8 | 30.4 | 163 | 0.612425 | 4.340762 | false | false | false | false |
moezbhatti/qksms | presentation/src/main/java/com/moez/QKSMS/common/widget/QkDialog.kt | 3 | 3098 | /*
* Copyright (C) 2019 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.app.Activity
import android.view.LayoutInflater
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import com.moez.QKSMS.R
import com.moez.QKSMS.common.base.QkAdapter
import kotlinx.android.synthetic.main.qk_dialog.view.*
class QkDialog(private val context: Activity) : AlertDialog(context) {
private val view = LayoutInflater.from(context).inflate(R.layout.qk_dialog, null)
@StringRes
var titleRes: Int? = null
set(value) {
field = value
title = value?.let(context::getString)
}
var title: String? = null
set(value) {
field = value
view.title.text = value
view.title.isVisible = !value.isNullOrBlank()
}
@StringRes
var subtitleRes: Int? = null
set(value) {
field = value
subtitle = value?.let(context::getString)
}
var subtitle: String? = null
set(value) {
field = value
view.subtitle.text = value
view.subtitle.isVisible = !value.isNullOrBlank()
}
var adapter: QkAdapter<*>? = null
set(value) {
field = value
view.list.isVisible = value != null
view.list.adapter = value
}
var positiveButtonListener: (() -> Unit)? = null
@StringRes
var positiveButton: Int? = null
set(value) {
field = value
value?.run(view.positiveButton::setText)
view.positiveButton.isVisible = value != null
view.positiveButton.setOnClickListener {
positiveButtonListener?.invoke() ?: dismiss()
}
}
var negativeButtonListener: (() -> Unit)? = null
@StringRes
var negativeButton: Int? = null
set(value) {
field = value
value?.run(view.negativeButton::setText)
view.negativeButton.isVisible = value != null
view.negativeButton.setOnClickListener {
negativeButtonListener?.invoke() ?: dismiss()
}
}
var cancelListener: (() -> Unit)? = null
set(value) {
field = value
setOnCancelListener { value?.invoke() }
}
init {
setView(view)
}
}
| gpl-3.0 | 401de0024f01b9f4c0f891a8049aef4b | 28.504762 | 85 | 0.615236 | 4.489855 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/root/RootHelperManager.kt | 1 | 2179 | package app.lawnchair.root
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import app.lawnchair.preferences.PreferenceManager
import com.android.launcher3.util.MainThreadInitializedObject
import com.topjohnwu.superuser.Shell
import com.topjohnwu.superuser.ipc.RootService
import kotlinx.coroutines.*
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
class RootHelperManager(private val context: Context) {
private val scope = MainScope() + CoroutineName("RootHelperManager")
private val prefs = PreferenceManager.getInstance(context)
private val isAvailableDeferred by lazy {
scope.async(Dispatchers.IO) {
Shell.rootAccess()
}
}
private var rootHelperDeferred: Deferred<IRootHelper>? = null
suspend fun isAvailable() = isAvailableDeferred.await()
@Throws(RootNotAvailableException::class)
suspend fun getService(): IRootHelper {
prefs.autoLaunchRoot.set(isAvailable())
if (!isAvailable()) throw RootNotAvailableException()
if (rootHelperDeferred == null) {
rootHelperDeferred = scope.async {
bindImpl { rootHelperDeferred = null }
}
}
return rootHelperDeferred!!.await()
}
private suspend fun bindImpl(onDisconnected: () -> Unit): IRootHelper {
return withContext(Dispatchers.IO) {
val intent = Intent(context, RootHelper::class.java)
suspendCoroutine {
val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
it.resume(IRootHelper.Stub.asInterface(service))
}
override fun onServiceDisconnected(name: ComponentName) {
onDisconnected()
}
}
RootService.bind(intent, connection)
}
}
}
companion object {
val INSTANCE = MainThreadInitializedObject(::RootHelperManager)
}
}
| gpl-3.0 | 5a3d7ffd4e9c2ebb2400e4ad62b58ad5 | 33.587302 | 92 | 0.664066 | 5.22542 | false | false | false | false |
angryziber/picasa-gallery | src/views/gallery.kt | 1 | 1845 | package views
import integration.Profile
import photos.Config.startTime
import photos.Gallery
import web.RequestProps
//language=HTML
fun gallery(req: RequestProps, gallery: Gallery, profile: Profile) = """
<!DOCTYPE html>
<html lang="en">
<head>
<title>${+profile.name} Photography</title>
<meta name="description" content="${+profile.name} photo albums from around the World">
<meta property="og:image" content="https://${req.host}${gallery.albums.values.first().thumbUrlLarge}">
<meta property="og:description" content="${+profile.name} Photography">
${head(req, profile)}
<script src="/js/gallery.js?$startTime"></script>
<script>jQuery(GalleryMap)</script>
</head>
<body style="background:black; color: gray">
<div id="header" class="header">
<h1 id="title">${+profile.name} Photography</h1>
</div>
<div id="content" class="faded">
<div id="map"></div>
<div class="albums thumbs">
${gallery.albums.values.each { """
<a id="${+name}" class="fade" href="${url}${req.urlSuffix}"
${geo / """data-coords="${geo!!.lat}:${geo!!.lon}""""}
data-url="${url}.jpg">
<img alt="${+title} photos" title="${+description}">
<div class="title">
<span class="info">${size()}</span>
<span class="text">${+title}</span>
</div>
</a>
"""}}
</div>
<p id="footer">
Photos by ${profile.name}. All rights reserved.
<a href="?random${req.urlSuffix.replace('?', '&')}" rel="nofollow">Random photo</a>.
<br>
Rendered by <a href="https://github.com/angryziber/picasa-gallery">Picasa Gallery</a>.
View your <a href="/oauth" rel="nofollow">own gallery</a>.
</p>
</div>
${sharing()}
<script>new ThumbsView(${gallery.albums.values.first().thumbSize})</script>
<div class="load-time hidden">${gallery.loadedAt}</div>
</body>
</html>
"""
| gpl-3.0 | c790ed3543f8d0580c16baf8a7964055 | 28.758065 | 104 | 0.628726 | 3.336347 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/leaderboards/LeaderboardProductItem.kt | 1 | 6435 | package org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards
import android.text.Html
import android.text.SpannableStringBuilder
import android.text.style.URLSpan
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsApiResponse.LeaderboardItemRow
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsApiResponse.Type.PRODUCTS
/**
* The API response from the V4 Leaderboards endpoint returns the Top Performers Products list as an array of arrays,
* each inner array represents a Top Performer Product itself, so in the end it's an array of Top Performers items.
*
* Each Top Performer item is an array containing three objects with the following properties: display and value.
*
* Single Top Performer item response example:
[
{
"display": "<a href='https:\/\/mystagingwebsite.com\/wp-admin\/admin.php?page=wc-admin&path=\/analytics\/products&filter=single_product&products=14'>Beanie<\/a>",
"value": "Beanie"
},
{
"display": "2.000",
"value": 2000
},
{
"display": "<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">R$<\/span>36.000,00<\/span>",
"value": 36000
}
]
This class represents one Single Top Performer item response as a Product type one
*/
@Suppress("MaxLineLength")
class LeaderboardProductItem(
private val itemRows: Array<LeaderboardItemRow>? = null
) {
val quantity
get() = itemRows
?.second()
?.value
val total
get() = itemRows
?.third()
?.value
/**
* This property will operate and transform a HTML tag in order to retrieve the currency symbol out of it.
*
* Example:
* HTML tag -> <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">R$<\/span>36.000,00<\/span>
*
* split from ">" delimiter
* Output: string list containing
* <span class=\"woocommerce-Price-amount amount\"
* <span class=\"woocommerce-Price-currencySymbol\"
* R$<\/span
* 36.000,00<\/span
*
* first who contains "&#"
* Output: R$<\/span>
*
* split from ";" delimiter
* Output: string list containing
* R
* $
* <\/span>
*
* filter what contains "&#"
* Output: string list containing
* R
* $
*
* reduce string list
* Output: R$
*
* fromHtmlWithSafeApiCall
* Output: R$
*/
@Suppress("MaxLineLength") val currency by lazy {
priceAmountHtmlTag
?.split(">")
?.firstOrNull { it.contains("&#") }
?.split(";")
?.filter { it.contains("&#") }
?.reduce { total, new -> "$total$new" }
?.run { Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY) }
?: plainTextCurrency
}
/**
* This property will serve as a fallback for cases where the currency is represented in plain text instead of
* HTML currency code.
*
* It will extract the raw content between tags and leave only the currency information
*
* Example:
*
* HTML tag -> <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">DKK<\/span>36.000,00<\/span>
*
* parse HTML tag to string
* Output: DKK36.000,00
*
* regex filter with replace
* Output: DKK
*/
@Suppress("MaxLineLength") private val plainTextCurrency by lazy {
Html.fromHtml(priceAmountHtmlTag, Html.FROM_HTML_MODE_LEGACY)
.toString()
.replace(Regex("[0-9.,]"), "")
}
/**
* This property will operate and transform a URL string in order to retrieve the product id parameter out of it.
*
* Example:
* URL string -> https:\/\/mystagingwebsite.com\/wp-admin\/admin.php?page=wc-admin&path=\/analytics\/products&filter=single_product&products=14
*
* split from "&" delimiter
* Output: string list containing
* https:\/\/mystagingwebsite.com\/wp-admin\/admin.php?page=wc-admin
* filter=single_product
* products=14
*
* first who contains "products="
* Output: products=14
*
* split from "=" delimiter
* Output: string list containing
* products
* 14
*
* extract last string from the list
* Output: 14 as String
*
* try to convert to long
* Output: 14 as Long
*/
@Suppress("MaxLineLength") val productId by lazy {
link
?.split("&")
?.firstOrNull { it.contains("${PRODUCTS.value}=", true) }
?.split("=")
?.last()
?.toLongOrNull()
}
/**
* This property will operate and transform a HTML tag in order to retrieve the inner URL out of the <a href/> tag
* using the [SpannableStringBuilder] implementation in order to parse it
*/
private val link by lazy {
Html.fromHtml(itemHtmlTag, Html.FROM_HTML_MODE_LEGACY)
.run { this as? SpannableStringBuilder }
?.spansAsList()
?.firstOrNull()
?.url
}
private val itemHtmlTag by lazy {
itemRows
?.first()
?.display
}
private val priceAmountHtmlTag by lazy {
itemRows
?.third()
?.display
}
private fun SpannableStringBuilder.spansAsList() =
getSpans(0, length, URLSpan::class.java)
.toList()
/**
* Returns the second object of the Top Performer Item Array if exists
*/
private fun Array<LeaderboardItemRow>.second() =
takeIf { isNotEmpty() && size > 1 }
?.let { this[1] }
/**
* Returns the third object of the Top Performer Item Array if exists
*/
private fun Array<LeaderboardItemRow>.third() =
takeIf { isNotEmpty() && size > 2 }
?.let { this[2] }
}
| gpl-2.0 | e6d4b62af24a9fa39e041ce3bc0ad634 | 33.047619 | 170 | 0.563636 | 4.490579 | false | false | false | false |
SUPERCILEX/Robot-Scouter | library/core-data/src/main/java/com/supercilex/robotscouter/core/data/remote/TeamMediaUploader.kt | 1 | 2228 | package com.supercilex.robotscouter.core.data.remote
import com.google.firebase.functions.ktx.functions
import com.google.firebase.ktx.Firebase
import com.supercilex.robotscouter.core.RobotScouter
import com.supercilex.robotscouter.core.data.R
import com.supercilex.robotscouter.core.data.logFailures
import kotlinx.coroutines.tasks.await
import okhttp3.MediaType
import okhttp3.RequestBody
import retrofit2.create
import java.io.File
internal class TeamMediaUploader(
private val id: String,
private val name: String,
private val media: String,
private val shouldUploadMediaToTba: Boolean
) {
suspend fun execute() {
if (!File(media).exists()) return
val imageUrl = uploadToImgur()
notifyBackend(imageUrl)
}
private suspend fun uploadToImgur(): String {
val response = TeamMediaApi.IMGUR_RETROFIT
.create<TeamMediaApi>()
.postToImgurAsync(
RobotScouter.getString(R.string.imgur_client_id),
name,
RequestBody.create(MediaType.parse("image/*"), File(media))
)
var link: String = response.get("data").asJsonObject.get("link").asString
// Oh Imgur, why don't you use https by default? 😢
link = if (link.startsWith("https://")) link else link.replace("http://", "https://")
// And what about pngs?
link = if (link.endsWith(".png")) link else link.replace(getFileExtension(link), ".png")
return link
}
private suspend fun notifyBackend(url: String) {
Firebase.functions
.getHttpsCallable("clientApi")
.call(mapOf(
"operation" to "update-team-media",
"teamId" to id,
"url" to url,
"shouldUploadMediaToTba" to shouldUploadMediaToTba
))
.logFailures("updateTeamMedia", url)
.await()
}
/**
* @return Return a period plus the file extension
*/
private fun getFileExtension(url: String): String =
".${url.split(".").dropLastWhile(String::isEmpty).last()}"
}
| gpl-3.0 | 006321a7e1f20ceb637edf6214c82507 | 34.31746 | 96 | 0.606292 | 4.616183 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/extensions/MaterialButton.kt | 1 | 1062 | package com.booboot.vndbandroid.extensions
import android.content.res.ColorStateList
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.booboot.vndbandroid.R
import com.booboot.vndbandroid.util.Pixels
import com.google.android.material.button.MaterialButton
fun MaterialButton.selectIf(
select: Boolean,
@ColorRes textColor: Int = R.color.white
) = if (select) select(textColor) else unselect()
fun MaterialButton.select(
@ColorRes textColor: Int = R.color.white
) = apply {
val newTextColor = ContextCompat.getColor(context, textColor)
setTextColor(newTextColor)
iconTint = ColorStateList.valueOf(newTextColor)
backgroundTintList = strokeColor
elevation = Pixels.px(3).toFloat()
rippleColor = textColors
}
fun MaterialButton.unselect() = apply {
setTextColor(strokeColor)
iconTint = strokeColor
backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(context, android.R.color.transparent))
elevation = Pixels.px(0).toFloat()
rippleColor = textColors
} | gpl-3.0 | 8675abb6a055ede46ca7724e36f02ca0 | 32.21875 | 109 | 0.775895 | 4.334694 | false | false | false | false |
quarkusio/quarkus | extensions/panache/hibernate-reactive-panache-kotlin/runtime/src/main/kotlin/io/quarkus/hibernate/reactive/panache/kotlin/runtime/PanacheQueryImpl.kt | 1 | 3329 | package io.quarkus.hibernate.reactive.panache.kotlin.runtime
import io.quarkus.hibernate.reactive.panache.common.runtime.CommonPanacheQueryImpl
import io.quarkus.hibernate.reactive.panache.kotlin.PanacheQuery
import io.quarkus.panache.common.Page
import io.quarkus.panache.common.Parameters
import io.smallrye.mutiny.Multi
import io.smallrye.mutiny.Uni
import org.hibernate.reactive.mutiny.Mutiny
import javax.persistence.LockModeType
class PanacheQueryImpl<Entity : Any> : PanacheQuery<Entity> {
private var delegate: CommonPanacheQueryImpl<Entity>
internal constructor(em: Uni<Mutiny.Session>, query: String?, orderBy: String?, paramsArrayOrMap: Any?) {
delegate = CommonPanacheQueryImpl(em, query, orderBy, paramsArrayOrMap)
}
private constructor(delegate: CommonPanacheQueryImpl<Entity>) {
this.delegate = delegate
}
override fun <NewEntity : Any> project(type: Class<NewEntity>): PanacheQuery<NewEntity> {
return PanacheQueryImpl(delegate.project(type))
}
override fun page(page: Page): PanacheQuery<Entity> {
delegate.page(page)
return this
}
override fun page(pageIndex: Int, pageSize: Int): PanacheQuery<Entity> {
delegate.page(pageIndex, pageSize)
return this
}
override fun nextPage(): PanacheQuery<Entity> {
delegate.nextPage()
return this
}
override fun previousPage(): PanacheQuery<Entity> {
delegate.previousPage()
return this
}
override fun firstPage(): PanacheQuery<Entity> {
delegate.firstPage()
return this
}
override fun lastPage(): Uni<PanacheQuery<Entity>> {
return delegate.lastPage().map { this }
}
override fun hasNextPage(): Uni<Boolean> {
return delegate.hasNextPage()
}
override fun hasPreviousPage(): Boolean {
return delegate.hasPreviousPage()
}
override fun pageCount(): Uni<Int> {
return delegate.pageCount()
}
override fun page(): Page {
return delegate.page()
}
override fun range(startIndex: Int, lastIndex: Int): PanacheQuery<Entity> {
delegate.range(startIndex, lastIndex)
return this
}
override fun withLock(lockModeType: LockModeType): PanacheQuery<Entity> {
delegate.withLock(lockModeType)
return this
}
override fun withHint(hintName: String, value: Any): PanacheQuery<Entity> {
delegate.withHint(hintName, value)
return this
}
override fun filter(filterName: String, parameters: Parameters): PanacheQuery<Entity> {
delegate.filter(filterName, parameters.map())
return this
}
override fun filter(filterName: String, parameters: Map<String, Any>): PanacheQuery<Entity> {
delegate.filter(filterName, parameters)
return this
}
override fun filter(filterName: String): PanacheQuery<Entity> {
delegate.filter(filterName, emptyMap())
return this
}
// Results
override fun count() = delegate.count()
override fun list(): Uni<List<Entity>> = delegate.list()
override fun stream(): Multi<Entity> = delegate.stream()
override fun firstResult(): Uni<Entity?> = delegate.firstResult()
override fun singleResult(): Uni<Entity> = delegate.singleResult()
}
| apache-2.0 | f998e444321883562a413e8559e9e0cb | 28.460177 | 109 | 0.683989 | 4.345953 | false | false | false | false |
SixCan/SixTomato | app/src/main/java/ca/six/tomato/util/ExpandUtil.kt | 1 | 1340 | package ca.six.tomato.util
/**
* Created by songzhw on 2016-06-02.
*/
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.widget.EditText
fun Activity.jump(clz : Class<out Any>){
val it = Intent(this, clz)
this.startActivity(it)
}
fun Activity.jump(clz : Class<out Any>, args : Map<String, String>){
val it = Intent(this, clz)
for( (k,v) in args){
it.putExtra(k, v)
}
this.startActivity(it)
}
fun EditText.string() : String {
return this.getText()?.toString() ?: "" //this是指EditText对象。因为这是猴子补丁
}
fun Activity.getIntValue(key : String, default : Int) : Int {
val sp = getSharedPreferences(Globals.SP_NAME, Context.MODE_PRIVATE)
return sp.getInt(key, default)
}
fun Activity.saveIntValue(key: String, value : Int) : Unit {
val sp = getSharedPreferences(Globals.SP_NAME, Context.MODE_PRIVATE).edit()
sp.putInt(key, value)
sp.apply()
}
fun Activity.getBooleanValue(key : String) : Boolean {
val sp = getSharedPreferences(Globals.SP_NAME, Context.MODE_PRIVATE)
return sp.getBoolean(key, false)
}
fun Activity.saveBooleanValue(key: String, value : Boolean) : Unit {
val sp = getSharedPreferences(Globals.SP_NAME, Context.MODE_PRIVATE).edit()
sp.putBoolean(key, value)
sp.apply()
} | gpl-3.0 | 132bd9c3ecd30cddea5e55e74fc7e888 | 25.3 | 79 | 0.694064 | 3.326582 | false | false | false | false |
Sefford/kor | modules/kor-repositories/src/test/kotlin/com/sefford/kor/repositories/TwoTierRepositoryTest.kt | 1 | 20813 | /*
* Copyright (C) 2017 Saúl Díaz
*
* 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.sefford.kor.repositories
import arrow.core.Either
import arrow.core.Left
import com.nhaarman.mockito_kotlin.*
import com.sefford.kor.repositories.components.Repository
import com.sefford.kor.repositories.components.RepositoryError
import com.sefford.kor.test.TestElement
import org.hamcrest.core.Is.`is`
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.MockitoAnnotations.initMocks
/**
* @author Saul Diaz <[email protected]>
*/
class TwoTierRepositoryTest {
lateinit var firstLevel: Repository<Int, TestElement>
lateinit var nextLevel: Repository<Int, TestElement>
lateinit var mockedRepository: Repository<Int, TestElement>
lateinit var repository: TwoTierRepository<Int, TestElement>
@Before
@Throws(Exception::class)
fun setUp() {
initMocks(this)
firstLevel = MemoryDataSource()
nextLevel = MemoryDataSource()
mockedRepository = mock(nextLevel::class.java)
repository = TwoTierRepository(firstLevel, nextLevel)
}
@Test
fun `should return next level is not available`() {
repository = TwoTierRepository(firstLevel, DeactivatedRepository(nextLevel))
assertFalse(repository.hasNextLevel())
}
@Test
fun `should report the next level is available`() {
assertTrue(repository.hasNextLevel())
}
@Test
fun `should persist in current level when next level is not available`() {
repository = TwoTierRepository(firstLevel, DeactivatedRepository(nextLevel))
repository.save(TestElement(EXPECTED_FIRST_ID)).fold({ throw IllegalStateException("Expected a right projection") },
{ element ->
assertThat(element.id, `is`(EXPECTED_FIRST_ID))
assertThat(firstLevel.contains(EXPECTED_FIRST_ID), `is`(true))
assertThat(nextLevel.contains(EXPECTED_FIRST_ID), `is`(false))
})
}
@Test
fun `should persist in next level if current level is not available`() {
repository = TwoTierRepository(DeactivatedRepository(firstLevel), nextLevel)
repository.save(TestElement(EXPECTED_FIRST_ID)).fold({ throw IllegalStateException("Expected a right projection") },
{ element ->
assertThat(element.id, `is`(EXPECTED_FIRST_ID))
assertThat(firstLevel.contains(EXPECTED_FIRST_ID), `is`(false))
assertThat(nextLevel.contains(EXPECTED_FIRST_ID), `is`(true))
})
}
@Test
fun `should persist on both levels`() {
repository.save(TestElement(EXPECTED_FIRST_ID)).fold({},
{ element ->
assertThat(element.id, `is`(EXPECTED_FIRST_ID))
assertThat(firstLevel.contains(EXPECTED_FIRST_ID), `is`(true))
assertThat(nextLevel.contains(EXPECTED_FIRST_ID), `is`(true))
})
}
@Test
fun `should return NotReady error when the repository is not ready`() {
repository = TwoTierRepository(DeactivatedRepository(firstLevel), DeactivatedRepository(nextLevel))
repository.save(TestElement(EXPECTED_FIRST_ID)).fold({ assertTrue(it is RepositoryError.NotReady) },
{ throw IllegalStateException("Expected a left projection") })
}
@Test
fun `contains should return false if none of the levels contains the element`() {
assertFalse(repository.contains(EXPECTED_FIRST_ID))
}
@Test
fun `contains should return true if only the first level contain the element`() {
firstLevel.save(TestElement(EXPECTED_FIRST_ID))
assertTrue(repository.contains(EXPECTED_FIRST_ID))
}
@Test
fun `contains should return true if only the second level contains the element`() {
nextLevel.save(TestElement(EXPECTED_FIRST_ID))
assertTrue(repository.contains(EXPECTED_FIRST_ID))
}
@Test
fun `contains should return true if both levels contain the element`() {
nextLevel.save(TestElement(EXPECTED_FIRST_ID))
firstLevel.save(TestElement(EXPECTED_FIRST_ID))
assertTrue(repository.contains(EXPECTED_FIRST_ID))
}
@Test
fun `contains should return false if the first level does not contain the element and the second is unavailable`() {
repository = TwoTierRepository(firstLevel, DeactivatedRepository(nextLevel))
assertFalse(repository.contains(EXPECTED_FIRST_ID))
}
@Test
fun `contains should return true if the first level contains the element and the second is unavailable`() {
firstLevel.save(TestElement(EXPECTED_FIRST_ID))
repository = TwoTierRepository(firstLevel, DeactivatedRepository(nextLevel))
assertTrue(repository.contains(EXPECTED_FIRST_ID))
}
@Test
fun `should delete only in the first level if the next level is not available`() {
val deactivatedRepository = DeactivatedRepository(nextLevel)
repository = TwoTierRepository(firstLevel, deactivatedRepository)
firstLevel.save(TestElement(EXPECTED_FIRST_ID))
repository.delete(EXPECTED_FIRST_ID, TestElement(EXPECTED_FIRST_ID))
assertThat(firstLevel.contains(EXPECTED_FIRST_ID), `is`(false))
assertThat(deactivatedRepository.deleteCounter, `is`(0))
}
@Test
fun `should delete only in the first level if the next level is not available with id only`() {
val deactivatedRepo = DeactivatedRepository(nextLevel)
repository = TwoTierRepository(firstLevel, deactivatedRepo)
firstLevel.save(TestElement(EXPECTED_FIRST_ID))
repository.delete(EXPECTED_FIRST_ID)
assertThat(firstLevel.contains(EXPECTED_FIRST_ID), `is`(false))
assertThat(deactivatedRepo.deleteCounter, `is`(0))
}
@Test
fun `should delete in both levels`() {
firstLevel.save(TestElement(EXPECTED_FIRST_ID))
nextLevel.save(TestElement(EXPECTED_FIRST_ID))
repository.delete(EXPECTED_FIRST_ID)
assertThat(firstLevel.contains(EXPECTED_FIRST_ID), `is`(false))
assertThat(nextLevel.contains(EXPECTED_FIRST_ID), `is`(false))
}
@Test
fun `should delete in both levels with id only`() {
firstLevel.save(TestElement(EXPECTED_FIRST_ID))
nextLevel.save(TestElement(EXPECTED_FIRST_ID))
repository.delete(EXPECTED_FIRST_ID)
assertThat(firstLevel.contains(EXPECTED_FIRST_ID), `is`(false))
assertThat(nextLevel.contains(EXPECTED_FIRST_ID), `is`(false))
}
@Test
fun `should delete all elements via iterator`() {
repository.save(TestElement(EXPECTED_FIRST_ID), TestElement(EXPECTED_SECOND_ID), TestElement(EXPECTED_THIRD_ID))
repository.delete(listOf(TestElement(EXPECTED_FIRST_ID), TestElement(EXPECTED_SECOND_ID), TestElement(EXPECTED_THIRD_ID)).iterator())
assertThat(repository.all.isEmpty(), `is`(true))
}
@Test
fun `should delete all elements via collection`() {
repository.save(TestElement(EXPECTED_FIRST_ID), TestElement(EXPECTED_SECOND_ID), TestElement(EXPECTED_THIRD_ID))
repository.delete(listOf(TestElement(EXPECTED_FIRST_ID), TestElement(EXPECTED_SECOND_ID), TestElement(EXPECTED_THIRD_ID)))
assertThat(repository.all.isEmpty(), `is`(true))
}
@Test
fun `should delete all elements via varargs`() {
repository.save(TestElement(EXPECTED_FIRST_ID), TestElement(EXPECTED_SECOND_ID), TestElement(EXPECTED_THIRD_ID))
repository.delete(TestElement(EXPECTED_FIRST_ID), TestElement(EXPECTED_SECOND_ID), TestElement(EXPECTED_THIRD_ID))
assertThat(repository.all.isEmpty(), `is`(true))
}
@Test
fun `should return not found if both levels do not have the element`() {
repository[EXPECTED_FIRST_ID].fold({ assertTrue(it is RepositoryError.NotFound<*>) },
{ throw IllegalStateException("Expected a left projection") })
}
@Test
fun `should return not found if first level do not have the element and second is unavailable`() {
repository = TwoTierRepository(firstLevel, mockedRepository)
repository[EXPECTED_FIRST_ID].fold({
assertTrue(it is RepositoryError.NotFound<*>)
verify(mockedRepository, never()).get(EXPECTED_FIRST_ID)
},
{ throw IllegalStateException("Expected a left projection") })
}
@Test
fun `should return NotReady error if the repository is not ready`() {
repository = TwoTierRepository(mockedRepository, mockedRepository)
repository[EXPECTED_FIRST_ID].fold({ assertTrue(it is RepositoryError.NotReady) },
{ throw IllegalStateException("Expected a left projection") })
}
@Test
fun `should return the element if the first level has the element and the second is unavailable`() {
firstLevel.save(TestElement(EXPECTED_FIRST_ID))
repository = TwoTierRepository(firstLevel, mockedRepository)
repository[EXPECTED_FIRST_ID].fold({ throw IllegalStateException("Expected a right projection") },
{ assertThat(it.id, `is`(EXPECTED_FIRST_ID)) })
}
@Test
fun `should return the element if the first level has the element`() {
repository.save(TestElement(EXPECTED_FIRST_ID))
repository[EXPECTED_FIRST_ID].fold({ throw IllegalStateException("Expected a right projection") },
{ assertThat(it.id, `is`(EXPECTED_FIRST_ID)) })
}
@Test
fun `should return the element if the second level has the element`() {
nextLevel.save(TestElement(EXPECTED_FIRST_ID))
repository[EXPECTED_FIRST_ID].fold({ throw IllegalStateException("Expected a right projection") },
{ assertThat(it.id, `is`(EXPECTED_FIRST_ID)) })
}
@Test
fun `should recover if the first level has a problem retrieving the element`() {
repository = TwoTierRepository(mockedRepository, nextLevel)
nextLevel.save(TestElement(EXPECTED_FIRST_ID))
whenever(mockedRepository.contains(EXPECTED_FIRST_ID)).thenReturn(true)
whenever(mockedRepository[EXPECTED_FIRST_ID]).thenReturn(Left(RepositoryError.CannotRetrieve(Exception())))
repository[EXPECTED_FIRST_ID].fold({ throw IllegalStateException("Expected a right projection") },
{ assertThat(it.id, `is`(EXPECTED_FIRST_ID)) })
}
@Test
fun `should retrieve the element if both levels have it`() {
firstLevel.save(TestElement(EXPECTED_FIRST_ID))
nextLevel.save(TestElement(EXPECTED_FIRST_ID))
repository[EXPECTED_FIRST_ID].fold({ throw IllegalStateException("Expected a right projection") },
{ assertThat(it.id, `is`(EXPECTED_FIRST_ID)) })
}
@Test
fun `should be able to retrieve in batch via varargs`() {
firstLevel.save(FULL_ELEMENT_LIST)
nextLevel.save(FULL_ELEMENT_LIST)
val result = repository.get(EXPECTED_FIRST_ID, EXPECTED_SECOND_ID, EXPECTED_THIRD_ID)
assertThat(result.size, `is`(EXPECTED_FULL_LIST_SIZE))
result.forEach { element -> FULL_IDS_LIST.contains(element.id) }
}
@Test
fun `should be able to retrieve in batch via collection`() {
firstLevel.save(FULL_ELEMENT_LIST)
nextLevel.save(FULL_ELEMENT_LIST)
val result = repository.get(listOf(EXPECTED_FIRST_ID, EXPECTED_SECOND_ID, EXPECTED_THIRD_ID))
assertThat(result.size, `is`(EXPECTED_FULL_LIST_SIZE))
result.forEach { element -> FULL_IDS_LIST.contains(element.id) }
}
@Test
fun `should be able to retrieve in batch via iterator`() {
firstLevel.save(FULL_ELEMENT_LIST)
nextLevel.save(FULL_ELEMENT_LIST)
val result = repository.get(listOf(EXPECTED_FIRST_ID, EXPECTED_SECOND_ID, EXPECTED_THIRD_ID).iterator())
assertThat(result.size, `is`(EXPECTED_FULL_LIST_SIZE))
result.forEach { element -> FULL_IDS_LIST.contains(element.id) }
}
@Test
fun `should persist all elements if second level is unavailable via iterator`() {
repository = TwoTierRepository(firstLevel, mockedRepository)
repository.save(FULL_ELEMENT_LIST.iterator())
FULL_IDS_LIST.forEach { id: Int -> assertThat(firstLevel.contains(id), `is`(true)) }
verify(mockedRepository, never()).save(any<TestElement>())
}
@Test
fun `should persist all elements if second level is unavailable via collection`() {
repository = TwoTierRepository(firstLevel, mockedRepository)
repository.save(FULL_ELEMENT_LIST)
FULL_IDS_LIST.forEach { id: Int -> assertThat(firstLevel.contains(id), `is`(true)) }
verify(mockedRepository, never()).save(any<TestElement>())
}
@Test
fun `should persist all elements if second level is unavailable via varargs`() {
repository = TwoTierRepository(firstLevel, DeactivatedRepository(nextLevel))
repository.save(TestElement(EXPECTED_FIRST_ID), TestElement(EXPECTED_SECOND_ID), TestElement(EXPECTED_THIRD_ID))
FULL_IDS_LIST.forEach { id: Int ->
assertThat(firstLevel.contains(id), `is`(true))
assertThat(nextLevel.contains(id), `is`(false))
}
}
@Test
fun `should persist all elements via iterator`() {
repository.save(FULL_ELEMENT_LIST.iterator())
FULL_IDS_LIST.forEach { id: Int ->
assertThat(firstLevel.contains(id), `is`(true))
assertThat(nextLevel.contains(id), `is`(true))
}
}
@Test
fun `should persist all elements via collection`() {
repository.save(FULL_ELEMENT_LIST)
FULL_IDS_LIST.forEach { id: Int ->
assertThat(firstLevel.contains(id), `is`(true))
assertThat(nextLevel.contains(id), `is`(true))
}
}
@Test
fun `should persist all elements via varargs`() {
repository.save(TestElement(EXPECTED_FIRST_ID), TestElement(EXPECTED_SECOND_ID), TestElement(EXPECTED_THIRD_ID))
FULL_IDS_LIST.forEach { id: Int ->
assertThat(firstLevel.contains(id), `is`(true))
assertThat(nextLevel.contains(id), `is`(true))
}
}
@Test
fun `should clear first level when second level is not available`() {
val nextLevelMockedRepository = mock(nextLevel::class.java)
repository = TwoTierRepository(mockedRepository, nextLevelMockedRepository)
repository.clear()
verify(mockedRepository, times(1)).clear()
verify(nextLevelMockedRepository, never()).clear()
}
@Test
fun `should clear both levels`() {
val nextLevelMockedRepository = mock(nextLevel::class.java)
whenever(nextLevelMockedRepository.isReady).doReturn(true)
repository = TwoTierRepository(mockedRepository, nextLevelMockedRepository)
repository.clear()
verify(mockedRepository, times(1)).clear()
verify(nextLevelMockedRepository, times(1)).clear()
}
@Test
fun `should retrieve all elements when second level is not available`() {
repository = TwoTierRepository(firstLevel, mockedRepository)
firstLevel.save(FULL_ELEMENT_LIST)
val result = repository.all
assertThat(result.size, `is`(EXPECTED_FULL_LIST_SIZE))
result.forEach { element: TestElement -> assertThat(FULL_IDS_LIST.contains(element.id), `is`(true)) }
verify(mockedRepository, never()).all
}
@Test
fun `should retrieve all elements from second level if first does not have it`() {
nextLevel.save(FULL_ELEMENT_LIST)
val result = repository.all
assertThat(result.size, `is`(EXPECTED_FULL_LIST_SIZE))
result.forEach { element: TestElement -> assertThat(FULL_IDS_LIST.contains(element.id), `is`(true)) }
}
@Test
fun `should merge elements when retrieving all elements between both levels`() {
firstLevel.save(TestElement(EXPECTED_FIRST_ID), TestElement(EXPECTED_THIRD_ID))
nextLevel.save(TestElement(EXPECTED_SECOND_ID))
val result = repository.all
assertThat(result.size, `is`(EXPECTED_FULL_LIST_SIZE))
result.forEach { element: TestElement -> assertThat(FULL_IDS_LIST.contains(element.id), `is`(true)) }
}
@Test
fun `should not duplicate elements when retrieving all elements between both levels`() {
firstLevel.save(FULL_ELEMENT_LIST)
nextLevel.save(FULL_ELEMENT_LIST)
val result = repository.all
assertThat(result.size, `is`(EXPECTED_FULL_LIST_SIZE))
result.forEach { element: TestElement -> assertThat(FULL_IDS_LIST.contains(element.id), `is`(true)) }
}
@Test
fun `should report ready when both levels are ready`() {
assertTrue(repository.isReady)
}
@Test
fun `should report ready when only first level is ready`() {
repository = TwoTierRepository(firstLevel, DeactivatedRepository(nextLevel))
assertTrue(repository.isReady)
}
@Test
fun `should report ready when only second level is ready`() {
repository = TwoTierRepository(DeactivatedRepository(firstLevel), nextLevel)
assertTrue(repository.isReady)
}
@Test
fun `should report not ready when both levels are not ready`() {
repository = TwoTierRepository(DeactivatedRepository(firstLevel), DeactivatedRepository(nextLevel))
assertFalse(repository.isReady)
}
@Test
fun `a three tier should resolve the element correctly when the first level does not have it, the second is not ready and the third has it`() {
val thirdLevel: Repository<Int, TestElement> = MemoryDataSource()
thirdLevel.save(TestElement(EXPECTED_FIRST_ID))
val localLevel = TwoTierRepository(firstLevel, DeactivatedRepository(nextLevel))
val repository = TwoTierRepository(localLevel, thirdLevel)
repository[EXPECTED_FIRST_ID].fold({ throw IllegalStateException("Expected a right projection") },
{ assertThat(it.id, `is`(EXPECTED_FIRST_ID)) })
}
@Test
fun `a three tier should resolve contains correctly when the first level does not have it, the second is not ready and the third has it`() {
val firstLevel = mock(firstLevel::class.java)
val secondLevel = mock(firstLevel::class.java)
val thirdLevel = mock(firstLevel::class.java)
val localLevel = TwoTierRepository(firstLevel, secondLevel)
val repository = TwoTierRepository(localLevel, thirdLevel)
whenever(firstLevel.contains(EXPECTED_FIRST_ID)).thenReturn(false)
whenever(firstLevel.isReady).thenReturn(true)
whenever(secondLevel.contains(EXPECTED_FIRST_ID)).thenReturn(false)
whenever(secondLevel.isReady).thenReturn(false)
whenever(thirdLevel.isReady).thenReturn(true)
whenever(thirdLevel.contains(EXPECTED_FIRST_ID)).thenReturn(true)
assertThat(repository.contains(EXPECTED_FIRST_ID), `is`(true))
}
companion object {
private const val EXPECTED_FIRST_ID = 1
private const val EXPECTED_SECOND_ID = 2
private const val EXPECTED_THIRD_ID = 3
private const val EXPECTED_FULL_LIST_SIZE = 3
private val FULL_IDS_LIST = mutableListOf(EXPECTED_FIRST_ID, EXPECTED_SECOND_ID, EXPECTED_THIRD_ID)
private val FULL_ELEMENT_LIST = mutableListOf(TestElement(EXPECTED_FIRST_ID), TestElement(EXPECTED_SECOND_ID), TestElement(EXPECTED_THIRD_ID))
}
class DeactivatedRepository(repository: Repository<Int, TestElement>) : Repository<Int, TestElement> by repository {
var deleteCounter = 0
override val isReady: Boolean
get() = false
override fun save(element: TestElement): Either<RepositoryError, TestElement> {
return Left(RepositoryError.NotReady)
}
override fun get(id: Int): Either<RepositoryError, TestElement> {
return Left(RepositoryError.NotReady)
}
override fun delete(id: Int) {
deleteCounter++
}
override fun delete(id: Int, element: TestElement) {
deleteCounter++
}
}
}
| apache-2.0 | e5697011ac86c221bb0847d9b43afda3 | 37.467652 | 150 | 0.676709 | 4.415659 | false | true | false | false |
italoag/qksms | presentation/src/main/java/com/moez/QKSMS/common/util/Colors.kt | 3 | 6195 | /*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.content.Context
import android.graphics.Color
import androidx.core.content.res.getColorOrThrow
import com.moez.QKSMS.R
import com.moez.QKSMS.common.util.extensions.getColorCompat
import com.moez.QKSMS.model.Recipient
import com.moez.QKSMS.util.PhoneNumberUtils
import com.moez.QKSMS.util.Preferences
import io.reactivex.Observable
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.absoluteValue
@Singleton
class Colors @Inject constructor(
private val context: Context,
private val phoneNumberUtils: PhoneNumberUtils,
private val prefs: Preferences
) {
data class Theme(val theme: Int, private val colors: Colors) {
val highlight by lazy { colors.highlightColorForTheme(theme) }
val textPrimary by lazy { colors.textPrimaryOnThemeForColor(theme) }
val textSecondary by lazy { colors.textSecondaryOnThemeForColor(theme) }
val textTertiary by lazy { colors.textTertiaryOnThemeForColor(theme) }
}
val materialColors: List<List<Int>> = listOf(
R.array.material_red,
R.array.material_pink,
R.array.material_purple,
R.array.material_deep_purple,
R.array.material_indigo,
R.array.material_blue,
R.array.material_light_blue,
R.array.material_cyan,
R.array.material_teal,
R.array.material_green,
R.array.material_light_green,
R.array.material_lime,
R.array.material_yellow,
R.array.material_amber,
R.array.material_orange,
R.array.material_deep_orange,
R.array.material_brown,
R.array.material_gray,
R.array.material_blue_gray)
.map { res -> context.resources.obtainTypedArray(res) }
.map { typedArray -> (0 until typedArray.length()).map(typedArray::getColorOrThrow) }
private val randomColors: List<Int> = context.resources.obtainTypedArray(R.array.random_colors)
.let { typedArray -> (0 until typedArray.length()).map(typedArray::getColorOrThrow) }
private val minimumContrastRatio = 2
// Cache these values so they don't need to be recalculated
private val primaryTextLuminance = measureLuminance(context.getColorCompat(R.color.textPrimaryDark))
private val secondaryTextLuminance = measureLuminance(context.getColorCompat(R.color.textSecondaryDark))
private val tertiaryTextLuminance = measureLuminance(context.getColorCompat(R.color.textTertiaryDark))
fun theme(recipient: Recipient? = null): Theme {
val pref = prefs.theme(recipient?.id ?: 0)
val color = when {
recipient == null || !prefs.autoColor.get() || pref.isSet -> pref.get()
else -> generateColor(recipient)
}
return Theme(color, this)
}
fun themeObservable(recipient: Recipient? = null): Observable<Theme> {
val pref = when {
recipient == null -> prefs.theme()
prefs.autoColor.get() -> prefs.theme(recipient.id, generateColor(recipient))
else -> prefs.theme(recipient.id, prefs.theme().get())
}
return pref.asObservable()
.map { color -> Theme(color, this) }
}
fun highlightColorForTheme(theme: Int): Int = FloatArray(3)
.apply { Color.colorToHSV(theme, this) }
.let { hsv -> hsv.apply { set(2, 0.75f) } } // 75% value
.let { hsv -> Color.HSVToColor(85, hsv) } // 33% alpha
fun textPrimaryOnThemeForColor(color: Int): Int = color
.let { theme -> measureLuminance(theme) }
.let { themeLuminance -> primaryTextLuminance / themeLuminance }
.let { contrastRatio -> contrastRatio < minimumContrastRatio }
.let { contrastRatio -> if (contrastRatio) R.color.textPrimary else R.color.textPrimaryDark }
.let { res -> context.getColorCompat(res) }
fun textSecondaryOnThemeForColor(color: Int): Int = color
.let { theme -> measureLuminance(theme) }
.let { themeLuminance -> secondaryTextLuminance / themeLuminance }
.let { contrastRatio -> contrastRatio < minimumContrastRatio }
.let { contrastRatio -> if (contrastRatio) R.color.textSecondary else R.color.textSecondaryDark }
.let { res -> context.getColorCompat(res) }
fun textTertiaryOnThemeForColor(color: Int): Int = color
.let { theme -> measureLuminance(theme) }
.let { themeLuminance -> tertiaryTextLuminance / themeLuminance }
.let { contrastRatio -> contrastRatio < minimumContrastRatio }
.let { contrastRatio -> if (contrastRatio) R.color.textTertiary else R.color.textTertiaryDark }
.let { res -> context.getColorCompat(res) }
/**
* Measures the luminance value of a color to be able to measure the contrast ratio between two materialColors
* Based on https://stackoverflow.com/a/9733420
*/
private fun measureLuminance(color: Int): Double {
val array = intArrayOf(Color.red(color), Color.green(color), Color.blue(color))
.map { if (it < 0.03928) it / 12.92 else Math.pow((it + 0.055) / 1.055, 2.4) }
return 0.2126 * array[0] + 0.7152 * array[1] + 0.0722 * array[2] + 0.05
}
private fun generateColor(recipient: Recipient): Int {
val index = recipient.address.hashCode().absoluteValue % randomColors.size
return randomColors[index]
}
}
| gpl-3.0 | 279ab307110c108ffd0e0af006848cc2 | 42.93617 | 114 | 0.671994 | 4.038462 | false | false | false | false |
pnemonic78/RemoveDuplicates | duplicates-android/app/src/main/java/com/github/duplicates/alarm/AlarmComparator.kt | 1 | 3802 | /*
* 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.alarm
import android.text.format.DateUtils.MINUTE_IN_MILLIS
import com.github.duplicates.DuplicateComparator
/**
* Compare duplicate alarms.
*
* @author moshe.w
*/
class AlarmComparator : DuplicateComparator<AlarmItem>() {
override fun compare(lhs: AlarmItem, rhs: AlarmItem): Int {
var c: Int
c = compare(lhs.activate, rhs.activate)
if (c != SAME) return c
c = compare(lhs.alarmTime, rhs.alarmTime)
if (c != SAME) return c
c = compare(lhs.alertTime, rhs.alertTime)
if (c != SAME) return c
c = compare(lhs.createTime, rhs.createTime)
if (c != SAME) return c
c = compare(lhs.isDailyBriefing, rhs.isDailyBriefing)
if (c != SAME) return c
c = compare(lhs.name, rhs.name)
if (c != SAME) return c
c = compare(lhs.notificationType, rhs.notificationType)
if (c != SAME) return c
c = compare(lhs.repeat, rhs.repeat)
if (c != SAME) return c
c = compare(lhs.isSnoozeActivate, rhs.isSnoozeActivate)
if (c != SAME) return c
c = compare(lhs.snoozeDoneCount, rhs.snoozeDoneCount)
if (c != SAME) return c
c = compare(lhs.snoozeDuration, rhs.snoozeDuration)
if (c != SAME) return c
c = compare(lhs.snoozeRepeat, rhs.snoozeRepeat)
if (c != SAME) return c
c = compare(lhs.soundTone, rhs.soundTone)
if (c != SAME) return c
c = compare(lhs.soundType, rhs.soundType)
if (c != SAME) return c
c = compare(lhs.soundUri, rhs.soundUri)
if (c != SAME) return c
c = compare(lhs.isSubdueActivate, rhs.isSubdueActivate)
if (c != SAME) return c
c = compare(lhs.subdueDuration, rhs.subdueDuration)
if (c != SAME) return c
c = compare(lhs.subdueTone, rhs.subdueTone)
if (c != SAME) return c
c = compare(lhs.subdueUri, rhs.subdueUri)
if (c != SAME) return c
c = compare(lhs.volume, rhs.volume)
return if (c != SAME) c else super.compare(lhs, rhs)
}
override fun difference(lhs: AlarmItem, rhs: AlarmItem): BooleanArray {
val result = BooleanArray(4)
result[ALARM_TIME] = isDifferent(lhs.alarmTime, rhs.alarmTime)
result[ALERT_TIME] = isDifferentTime(lhs.alertTime, rhs.alertTime, MINUTE_IN_MILLIS)
result[NAME] = isDifferentIgnoreCase(lhs.name, rhs.name)
result[REPEAT] = isDifferent(lhs.repeat, rhs.repeat)
return result
}
override fun match(lhs: AlarmItem, rhs: AlarmItem, difference: BooleanArray?): Float {
val different = difference ?: difference(lhs, rhs)
var match = MATCH_SAME
if (different[ALARM_TIME]) {
match *= 0.7f
}
if (different[REPEAT]) {
match *= 0.8f
}
if (different[ALERT_TIME]) {
match *= 0.9f
}
if (different[NAME]) {
match *= matchTitle(lhs.name, rhs.name, 0.9f)
}
return match
}
companion object {
const val ALARM_TIME = 0
const val ALERT_TIME = 1
const val NAME = 2
const val REPEAT = 3
}
}
| apache-2.0 | e31b44b3e7820a1f57b5eed46221babb | 33.252252 | 92 | 0.616518 | 3.790628 | false | false | false | false |
sangcomz/FishBun | FishBun/src/main/java/com/sangcomz/fishbun/Fishton.kt | 1 | 4081 | package com.sangcomz.fishbun
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import com.sangcomz.fishbun.adapter.image.ImageAdapter
import com.sangcomz.fishbun.util.getDimension
import java.util.ArrayList
/**
* Created by seokwon.jeong on 04/01/2018.
*/
object Fishton {
lateinit var imageAdapter: ImageAdapter
var currentPickerImageList: List<Uri> = emptyList()
//BaseParams
var maxCount: Int = 0
var minCount: Int = 0
var exceptMimeTypeList = emptyList<MimeType>()
var selectedImages = ArrayList<Uri>()
//CustomizationParams
var specifyFolderList = emptyList<String>()
var photoSpanCount: Int = 0
var albumPortraitSpanCount: Int = 0
var albumLandscapeSpanCount: Int = 0
var isAutomaticClose: Boolean = false
var hasButtonInAlbumActivity: Boolean = false
var colorActionBar: Int = 0
var colorActionBarTitle: Int = 0
var colorStatusBar: Int = 0
var isStatusBarLight: Boolean = false
var hasCameraInPickerPage: Boolean = false
var albumThumbnailSize: Int = 0
var messageNothingSelected: String = ""
var messageLimitReached: String = ""
var titleAlbumAllView: String = ""
var titleActionBar: String = ""
var drawableHomeAsUpIndicator: Drawable? = null
var drawableDoneButton: Drawable? = null
var drawableAllDoneButton: Drawable? = null
var isUseAllDoneButton: Boolean = false
var strDoneMenu: String? = null
var strAllDoneMenu: String? = null
var colorTextMenu: Int = 0
var isUseDetailView: Boolean = false
var isShowCount: Boolean = false
var colorSelectCircleStroke: Int = 0
var isStartInAllView: Boolean = false
init {
initValue()
}
fun refresh() = initValue()
private fun initValue() {
//BaseParams
maxCount = 10
minCount = 1
exceptMimeTypeList = emptyList()
selectedImages = ArrayList()
//CustomizationParams
specifyFolderList = emptyList()
photoSpanCount = 4
albumPortraitSpanCount = 1
albumLandscapeSpanCount = 2
isAutomaticClose = false
hasButtonInAlbumActivity = false
colorActionBar = Color.parseColor("#3F51B5")
colorActionBarTitle = Color.parseColor("#ffffff")
colorStatusBar = Color.parseColor("#303F9F")
isStatusBarLight = false
hasCameraInPickerPage = false
albumThumbnailSize = Integer.MAX_VALUE
drawableHomeAsUpIndicator = null
drawableDoneButton = null
drawableAllDoneButton = null
strDoneMenu = null
strAllDoneMenu = null
colorTextMenu = Integer.MAX_VALUE
isUseAllDoneButton = false
isUseDetailView = true
isShowCount = true
colorSelectCircleStroke = Color.parseColor("#c1ffffff")
isStartInAllView = false
}
fun setDefaultMessage(context: Context) {
if (messageNothingSelected.isEmpty()) {
messageNothingSelected = context.getString(R.string.msg_no_selected)
}
if (messageLimitReached.isEmpty()) {
messageLimitReached = context.getString(R.string.msg_full_image)
}
if (titleAlbumAllView.isEmpty()) {
titleAlbumAllView = context.getString(R.string.str_all_view)
}
if (titleActionBar.isEmpty()) {
titleActionBar = context.getString(R.string.album)
}
}
fun setMenuTextColor() {
if (drawableDoneButton != null
|| drawableAllDoneButton != null
|| strDoneMenu == null
|| colorTextMenu != Integer.MAX_VALUE
)
return
colorTextMenu = if (isStatusBarLight) Color.BLACK else colorTextMenu
}
fun setDefaultDimen(context: Context) {
albumThumbnailSize =
if (albumThumbnailSize == Int.MAX_VALUE) {
context.getDimension(R.dimen.album_thum_size)
} else {
albumThumbnailSize
}
}
} | apache-2.0 | bff0feb6f9236da4605dc544463ba2c0 | 26.213333 | 80 | 0.655232 | 4.734339 | false | false | false | false |
goAV/NettyAndroid | netty-android/src/main/java/com/goav/netty/Handler/Client.kt | 1 | 6270 | /*
* Copyright (c) 2016.
* [email protected]
*/
package com.goav.netty.Handler
import android.system.Os.shutdown
import android.util.TimeUtils
import com.goav.netty.Impl.ChannelConnectImpl
import com.goav.netty.Impl.ClientImpl
import com.goav.netty.Impl.ClientOptImpl
import com.goav.netty.message.MessageBasic
import io.netty.bootstrap.Bootstrap
import io.netty.channel.ChannelInitializer
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.timeout.IdleStateHandler
import io.netty.util.internal.logging.InternalLoggerFactory
import java.util.concurrent.*
/**
* 长链接
*
* @time: 16/10/8 12:41.<br></br>
* @author: Created by moo<br></br>
*/
internal class Client constructor() : ClientImpl, ClientOptImpl {
private var socketChannel: SocketChannel? = null
private val service: ScheduledExecutorService
private val messageSupers: BlockingDeque<MessageBasic>
private var onDestrOY: Boolean
private val logger = InternalLoggerFactory.getInstance(this.javaClass)
private var bootstrap: Bootstrap? = null
private var host: String = ""
private var port: Int = 0
private var callBack: ChannelConnectImpl = ChannelConnectImpl.DEFAULT
private var readerIdleTimeSeconds: Int = 60
private var writerIdleTimeSeconds: Int = 60
private var allIdleTimeSeconds: Int = 90
private var reConnect: ReConnect? = null
private var mThread: Thread? = null
private var eventLoopGroup: NioEventLoopGroup? = null
init {
eventLoopGroup = NioEventLoopGroup();
service = Executors.newSingleThreadScheduledExecutor()
messageSupers = LinkedBlockingDeque()
onDestrOY = false
mThread = object : Thread("Socket_Push_Message") {
override fun run() {
while (!onDestrOY) {
var message: Any?
try {
message = messageSupers.take()
if (socketChannel == null) {
request(message)
TimeUnit.SECONDS.sleep(1)
} else {
socketChannel?.writeAndFlush(message)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
mThread!!.start()
}
override fun reConnect(reConnect: ReConnect): ClientOptImpl {
this.reConnect = reConnect
return this
}
override
fun address(host: String, port: Int): ClientOptImpl {
this.host = host
this.port = port
return this
}
override
fun addTimeOut(readerIdleTimeSeconds: Int, writerIdleTimeSeconds: Int, allIdleTimeSeconds: Int): ClientOptImpl {
this.readerIdleTimeSeconds = readerIdleTimeSeconds
this.writerIdleTimeSeconds = writerIdleTimeSeconds
this.allIdleTimeSeconds = allIdleTimeSeconds
return this
}
override
fun addCallBack(callBack: ChannelConnectImpl): ClientOptImpl {
this.callBack = callBack
return this
}
override
fun build(): ClientImpl {
bootstrap = Bootstrap()
bootstrap!!.channel(NioSocketChannel::class.java)
.group(eventLoopGroup)
.remoteAddress(host, port)
.handler(object : ChannelInitializer<SocketChannel>() {
@kotlin.jvm.Throws(java.lang.Exception::class)
override fun initChannel(ch: SocketChannel) {
var pipeline = ch.pipeline()
.addLast(IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds)
, EncodeHandler()
, DecodeHandler())
callBack.addChannelHandler(pipeline)
}
})
return this
}
private fun InitializationWithWorkThread() {
if (onDestrOY) return
try {
val future = bootstrap!!.connect().sync()
if (future.isSuccess) {
socketChannel = future.channel() as SocketChannel
} else {
socketChannel?.disconnect()
socketChannel?.close()
if (reConnect != null && reConnect!!.able) {
future.channel().eventLoop().schedule(
{ InitializationWithWorkThread() },
reConnect!!.time,
TimeUnit.SECONDS
)
} else {
throw InterruptedException()
}
}
} catch (e: Exception) {
logger.info("socketChannel连接失败", e)
// eventLoopGroup.shutdownGracefully();//it's can't restart when server close
} finally {
callBack.onConnectCallBack(socketChannel)
}
}
override fun connect() {
if (onDestrOY) return
logger.info("socket 连接2s后建立")
service.schedule({ InitializationWithWorkThread() }, 2, TimeUnit.SECONDS)
}
override fun request(message: MessageBasic) {
try {
messageSupers.put(message)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
override fun destroy() {
onDestrOY = true
mThread?.interrupt()
mThread?.join()
messageSupers.clear()
socketChannel?.close()
socketChannel = null
bootstrap = null
shutdown(service)
try {
eventLoopGroup?.shutdownGracefully()
} catch (e: Exception) {
} finally {
eventLoopGroup = null
}
}
}
@JvmSynthetic
fun shutdown(service: ExecutorService): Unit {
service.shutdown()
try {
if (!service.awaitTermination(1, TimeUnit.SECONDS)) {
service.shutdownNow()
}
} catch (e: Exception) {
} finally {
service.shutdownNow()
}
}
class ReConnect(val able: Boolean, val time: Long) {
}
| mit | d25ad2f7789015414d2d9aab384f88ae | 29.028846 | 123 | 0.580211 | 5.016867 | false | false | false | false |
Aidanvii7/Toolbox | adapterviews-databinding-recyclerview/src/test/java/com/aidanvii/toolbox/adapterviews/databinding/recyclerview/AdapterNotifierItemBoundObserverTest.kt | 1 | 2724 | package com.aidanvii.toolbox.adapterviews.databinding.recyclerview
import com.aidanvii.toolbox.DisposableItem
import com.aidanvii.toolbox.adapterviews.databinding.BindableAdapterItem
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.verify
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import java.util.concurrent.atomic.AtomicBoolean
internal class AdapterNotifierItemBoundObserverTest {
val tested = AdapterNotifierItemBoundObserver<TestItem>()
@Nested
inner class `when lazyBindableItem is not initialised` {
val testItem = TestItem()
@Nested
inner class `when onItemBound is called` {
init {
tested.onItemBound(testItem, mock())
}
// TODO only bind if lazy is initialised and is an AdapterNotifier
@Test
fun `adapter is bound and lazyBindableItem is initialised`() {
verify(testItem.adapterNotifierItem).bindAdapter(any())
}
}
@Nested
inner class `when onItemUnBound is called` {
init {
tested.onItemUnBound(testItem, mock())
}
@Test
fun `adapter is unbound and lazyBindableItem is initialised`() {
verify(testItem.adapterNotifierItem, never()).unbindAdapter(any())
}
}
}
@Nested
inner class `when lazyBindableItem is initialised` {
val testItem = TestItem().apply {
lazyBindableItem.value
}
@Nested
inner class `when onItemBound is called` {
init {
tested.onItemBound(testItem, mock())
}
@Test
fun `adapter is bound and lazyBindableItem is not initialised`() {
verify(testItem.adapterNotifierItem).bindAdapter(any())
}
}
@Nested
inner class `when onItemUnBound is called` {
init {
tested.onItemUnBound(testItem, mock())
}
@Test
fun `adapter is unbound and lazyBindableItem is not initialised`() {
verify(testItem.adapterNotifierItem).unbindAdapter(any())
}
}
}
class TestItem : BindableAdapterItem, DisposableItem {
override val _disposed = AtomicBoolean(false)
override val bindingId: Int get() = 1
override val layoutId: Int get() = 1
override val lazyBindableItem = lazy(LazyThreadSafetyMode.NONE) { adapterNotifierItem }
val adapterNotifierItem = mock<AdapterNotifier>()
}
} | apache-2.0 | 13adeee1cb000fa0e0906db842024d7e | 27.684211 | 95 | 0.618576 | 4.989011 | false | true | false | false |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/libanki/UndoTest.kt | 1 | 5284 | /*
* Copyright (c) 2020 Arthur Milchior <[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.libanki
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.RobolectricTest
import com.ichi2.libanki.Collection.UndoReview
import com.ichi2.libanki.Consts.COUNT_REMAINING
import com.ichi2.libanki.Consts.QUEUE_TYPE_LRN
import com.ichi2.libanki.Consts.QUEUE_TYPE_NEW
import com.ichi2.libanki.sched.Counts
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.instanceOf
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.test.*
@RunWith(AndroidJUnit4::class)
class UndoTest : RobolectricTest() {
/*****************
* Undo
*/
@get:Throws(Exception::class)
private val colV2: Collection
get() {
val col = col
col.changeSchedulerVer(2)
return col
}
@Test
@Ignore("We need to figure out how to test save/undo")
@Throws(Exception::class)
fun test_op() {
val col = colV2
with(col) {
// should have no undo by default
assertNull(undoType())
// let's adjust a study option
save("studyopts")
set_config("abc", 5)
// it should be listed as undoable
assertEquals("studyopts", undoName(targetContext.resources))
// with about 5 minutes until it's clobbered
/* lastSave
assertThat(getTime().now() - col._lastSave, lesserThan(1));
*/
// undoing should restore the old value
undo()
assertNull(undoType())
assertFalse(has_config("abc"))
// an (auto)save will clear the undo
save("foo")
assertEquals("foo", undoName(targetContext.resources))
save()
assertEquals("", undoName(targetContext.resources))
// and a review will, too
save("add")
val note = newNote()
note.setItem("Front", "one")
addNote(note)
reset()
assertEquals("add", undoName(targetContext.resources))
val c = sched.card
sched.answerCard(c!!, Consts.BUTTON_TWO)
assertEquals("Review", undoName(targetContext.resources))
}
}
@Test
@Throws(Exception::class)
// TODO why is this test ignored if it doesn't have @Ignore(happens for both java and kotlin versions)
fun test_review() {
val col = colV2
with(col) {
set_config("counts", COUNT_REMAINING)
var note = col.newNote()
note.setItem("Front", "one")
addNote(note)
reset()
/* TODO: undo after reset ?
assertNotNull(col.undoType())
*/
// answer
assertEquals(Counts(1, 0, 0), sched.counts())
var c = sched.card
assertEquals(QUEUE_TYPE_NEW, c!!.queue)
sched.answerCard(c, Consts.BUTTON_THREE)
assertEquals(1001, c.left)
assertEquals(Counts(0, 1, 0), sched.counts())
assertEquals(QUEUE_TYPE_LRN, c.queue)
// undo
assertNotNull(undoType())
undo()
reset()
assertEquals(Counts(1, 0, 0), sched.counts())
c.load()
assertEquals(QUEUE_TYPE_NEW, c.queue)
assertNotEquals(1001, c.left)
assertNull(undoType())
// we should be able to undo multiple answers too
note = newNote()
note.setItem("Front", "two")
addNote(note)
reset()
assertEquals(Counts(2, 0, 0), sched.counts())
c = sched.card
sched.answerCard(c!!, Consts.BUTTON_THREE)
c = sched.card
sched.answerCard(c!!, Consts.BUTTON_THREE)
assertEquals(Counts(0, 2, 0), sched.counts())
undo()
reset()
assertEquals(Counts(1, 1, 0), sched.counts())
undo()
reset()
assertEquals(Counts(2, 0, 0), sched.counts())
// performing a normal op will clear the review queue
c = sched.card
sched.answerCard(c!!, Consts.BUTTON_THREE)
assertThat(undoType(), instanceOf(UndoReview::class.java))
save("foo")
// Upstream, "save" can be undone. This test fails here because it's not the case in AnkiDroid
assumeThat(undoName(targetContext.resources), equalTo("foo"))
undo()
}
}
}
| gpl-3.0 | ba028db17f72bf139dbfd0a4f1937e60 | 35.944056 | 106 | 0.584706 | 4.373344 | false | true | false | false |
igorka48/CleanSocialAppTemplate | view/src/main/kotlin/com/social/com/view/ui/feed/fragment/FeedListFragment.kt | 1 | 1862 | package com.social.com.view.ui.feed.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.social.com.view.ui.feed.view.FeedListView
import com.social.com.view.ui.feed.presenter.FeedListPresenter
import com.arellomobile.mvp.presenter.InjectPresenter
import com.social.com.domain.interactor.tutorial.GetAllPosts
import com.social.com.domain.interactor.feed.GetFeed
import com.social.com.domain.model.Feed
import com.social.com.view.ui.R
import com.social.com.view.ui.common.BaseFragment
import com.social.com.view.ui.feed.adapters.FeedAdapter
import kotlinx.android.synthetic.main.fragment_posts_list.*
import javax.inject.Inject
class FeedListFragment : BaseFragment(), FeedListView {
@Inject
lateinit var adapter: FeedAdapter
@Inject
lateinit var feed: GetFeed
companion object {
const val TAG = "FeedListFragment"
fun newInstance(): FeedListFragment {
val fragment: FeedListFragment = FeedListFragment()
val args: Bundle = Bundle()
fragment.arguments = args
return fragment
}
}
@InjectPresenter
lateinit var presenter: FeedListPresenter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
component?.inject(this)
return inflater.inflate(R.layout.fragment_feed_list, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews()
presenter.feed = feed
presenter.initData()
}
fun initViews() {
recyclerView.adapter = adapter
}
override fun showData(data: List<Feed>) {
adapter.data = data
}
}
| apache-2.0 | fd9f5443035014643054bae72b6f5ea9 | 29.032258 | 78 | 0.708915 | 4.422803 | false | false | false | false |
SirWellington/alchemy-http | src/test/java/tech/sirwellington/alchemy/http/restful/ClearbitAPITest.kt | 1 | 3812 | /*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.http.restful
import com.natpryce.hamkrest.assertion.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.slf4j.LoggerFactory
import tech.sirwellington.alchemy.annotations.testing.IntegrationTest
import tech.sirwellington.alchemy.arguments.assertions.validURL
import tech.sirwellington.alchemy.arguments.checkThat
import tech.sirwellington.alchemy.http.AlchemyHttp
import tech.sirwellington.alchemy.http.restful.Clearbit.AutocompleteResponse
import tech.sirwellington.alchemy.http.restful.Clearbit.Endpoints
import tech.sirwellington.alchemy.test.hamcrest.nonEmptyString
import tech.sirwellington.alchemy.test.hamcrest.notEmpty
import tech.sirwellington.alchemy.test.hamcrest.notNull
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import javax.swing.ImageIcon
import kotlin.test.assertFalse
private object Clearbit
{
object Endpoints
{
const val AUTOCOMPLETE = "https://autocomplete.clearbit.com/v1/companies/suggest"
const val LOGO = "https://logo.clearbit.com"
}
data class AutocompleteResponse(val name: String,
val domain: String,
val logo: String)
}
@RunWith(AlchemyTestRunner::class)
@IntegrationTest
class ClearbitAPITest
{
private val LOG = LoggerFactory.getLogger(this::class.java)
private val http = AlchemyHttp.newBuilder().build()
@Test
fun testGetGoogleLogo()
{
val url = "${Endpoints.LOGO}/google.com"
val response = http.go().download(url)
testDownloadedLogo(response)
}
@Test
fun testGetAmazonLogo()
{
val url = "${Endpoints.LOGO}/amazon.com"
val response = http.go().download(url)
testDownloadedLogo(response)
}
@Test
fun testGithubLogo()
{
val url = "${Endpoints.LOGO}/github.com"
val response = http.go().download(url)
testDownloadedLogo(response)
}
@Test
fun testAutocomplete()
{
testAutocompleteWithText("Am")
testAutocompleteWithText("Cen")
testAutocompleteWithText("Goo")
testAutocompleteWithText("Ver")
}
private fun testDownloadedLogo(response: ByteArray)
{
assertThat(response, notNull)
assertFalse { response.isEmpty() }
val image = ImageIcon(response)
LOG.info("Downloaded logo: [${image.description}, ${image.iconWidth}x${image.iconHeight}]")
}
private fun testAutocompleteWithText(text: String)
{
val url = Endpoints.AUTOCOMPLETE
val response = http.go()
.get()
.usingQueryParam("query", text)
.expecting(Array<AutocompleteResponse>::class.java)
.at(url)
.toList()
assertThat(response, notNull)
assertThat(response, notEmpty)
response.forEach()
{
assertThat(it.name, nonEmptyString)
assertThat(it.domain, nonEmptyString)
assertThat(it.logo, nonEmptyString)
checkThat(it.logo).isA(validURL())
}
}
} | apache-2.0 | a2a5595d2258be43081264ce92307fb3 | 27.661654 | 99 | 0.669641 | 4.520759 | false | true | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/maptiles/MapTilesDownloadCacheConfig.kt | 1 | 1478 | package de.westnordost.streetcomplete.data.maptiles
import android.content.Context
import androidx.preference.PreferenceManager
import de.westnordost.streetcomplete.ApplicationConstants.DELETE_OLD_DATA_AFTER
import de.westnordost.streetcomplete.Prefs
import okhttp3.*
import java.io.File
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
/** Configuration for the common cache shared by tangram-es and the map tile ("pre"-)downloader
* integrated into the normal map download process */
@Singleton class MapTilesDownloadCacheConfig @Inject constructor(context: Context) {
val cacheControl = CacheControl.Builder()
.maxAge(12, TimeUnit.HOURS)
.maxStale(DELETE_OLD_DATA_AFTER.toInt(), TimeUnit.MILLISECONDS)
.build()
val cache: Cache?
init {
val cacheDir = context.externalCacheDir
val tileCacheDir: File?
if (cacheDir != null) {
tileCacheDir = File(cacheDir, TILE_CACHE_DIR)
if (!tileCacheDir.exists()) tileCacheDir.mkdir()
} else {
tileCacheDir = null
}
cache = if (tileCacheDir?.exists() == true) {
val mbs = PreferenceManager.getDefaultSharedPreferences(context).getInt(Prefs.MAP_TILECACHE_IN_MB, 50)
Cache(tileCacheDir, mbs * 1000L * 1000L)
} else {
null
}
}
companion object {
private const val TILE_CACHE_DIR = "tile_cache"
}
}
| gpl-3.0 | af97cc3d93f6f5ca8329fdbf92aadf58 | 31.844444 | 114 | 0.684032 | 4.385757 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/notequests/OsmNoteQuestController.kt | 1 | 10453 | package de.westnordost.streetcomplete.data.osmnotes.notequests
import de.westnordost.streetcomplete.ApplicationConstants
import de.westnordost.streetcomplete.data.osm.mapdata.BoundingBox
import de.westnordost.streetcomplete.data.osmnotes.Note
import de.westnordost.streetcomplete.data.osmnotes.NoteComment
import de.westnordost.streetcomplete.data.osmnotes.edits.NotesWithEditsSource
import de.westnordost.streetcomplete.data.user.UserDataSource
import de.westnordost.streetcomplete.data.user.UserLoginStatusSource
import java.util.concurrent.CopyOnWriteArrayList
import javax.inject.Inject
import javax.inject.Singleton
/** Used to get visible osm note quests */
@Singleton class OsmNoteQuestController @Inject constructor(
private val noteSource: NotesWithEditsSource,
private val hiddenDB: NoteQuestsHiddenDao,
private val userDataSource: UserDataSource,
private val userLoginStatusSource: UserLoginStatusSource,
private val notesPreferences: NotesPreferences,
): OsmNoteQuestSource {
/* Must be a singleton because there is a listener that should respond to a change in the
* database table */
interface HideOsmNoteQuestListener {
fun onHid(edit: OsmNoteQuestHidden)
fun onUnhid(edit: OsmNoteQuestHidden)
fun onUnhidAll()
}
private val hideListeners: MutableList<HideOsmNoteQuestListener> = CopyOnWriteArrayList()
private val listeners: MutableList<OsmNoteQuestSource.Listener> = CopyOnWriteArrayList()
private val showOnlyNotesPhrasedAsQuestions: Boolean get() =
notesPreferences.showOnlyNotesPhrasedAsQuestions
private val noteUpdatesListener = object : NotesWithEditsSource.Listener {
override fun onUpdated(added: Collection<Note>, updated: Collection<Note>, deleted: Collection<Long>) {
val hiddenNoteIds = getNoteIdsHidden()
val quests = mutableListOf<OsmNoteQuest>()
val deletedQuestIds = ArrayList(deleted)
for (note in added) {
val q = createQuestForNote(note, hiddenNoteIds)
if (q != null) quests.add(q)
}
for (note in updated) {
val q = createQuestForNote(note, hiddenNoteIds)
if (q != null) quests.add(q)
else deletedQuestIds.add(note.id)
}
onUpdated(quests, deletedQuestIds)
}
override fun onCleared() {
listeners.forEach { it.onInvalidated() }
}
}
private val userLoginStatusListener = object : UserLoginStatusSource.Listener {
override fun onLoggedIn() {
// notes created by the user in this app or commented on by this user should not be shown
onInvalidated()
}
override fun onLoggedOut() {}
}
private val notesPreferencesListener = object : NotesPreferences.Listener {
override fun onNotesPreferencesChanged() {
// a lot of notes become visible/invisible if this option is changed
onInvalidated()
}
}
init {
noteSource.addListener(noteUpdatesListener)
userLoginStatusSource.addListener(userLoginStatusListener)
notesPreferences.listener = notesPreferencesListener
}
override fun get(questId: Long): OsmNoteQuest? {
if (isNoteHidden(questId)) return null
return noteSource.get(questId)?.let { createQuestForNote(it) }
}
override fun getAllVisibleInBBox(bbox: BoundingBox): List<OsmNoteQuest> {
return createQuestsForNotes(noteSource.getAll(bbox))
}
private fun createQuestsForNotes(notes: Collection<Note>): List<OsmNoteQuest> {
val blockedNoteIds = getNoteIdsHidden()
return notes.mapNotNull { createQuestForNote(it, blockedNoteIds) }
}
private fun createQuestForNote(note: Note, blockedNoteIds: Set<Long> = setOf()): OsmNoteQuest? =
if(note.shouldShowAsQuest(userDataSource.userId, showOnlyNotesPhrasedAsQuestions, blockedNoteIds))
OsmNoteQuest(note.id, note.position)
else null
/* ----------------------------------- Hiding / Unhiding ----------------------------------- */
/** Mark the quest as hidden by user interaction */
fun hide(questId: Long) {
val hidden: OsmNoteQuestHidden?
synchronized(this) {
hiddenDB.add(questId)
hidden = getHidden(questId)
}
if (hidden != null) onHid(hidden)
onUpdated(deletedQuestIds = listOf(questId))
}
/** Un-hides a specific hidden quest by user interaction */
fun unhide(questId: Long): Boolean {
val hidden = getHidden(questId)
synchronized(this) {
if (!hiddenDB.delete(questId)) return false
}
if (hidden != null) onUnhid(hidden)
val quest = noteSource.get(questId)?.let { createQuestForNote(it, emptySet()) }
if (quest != null) onUpdated(quests = listOf(quest))
return true
}
/** Un-hides all previously hidden quests by user interaction */
fun unhideAll(): Int {
val previouslyHiddenNotes = noteSource.getAll(hiddenDB.getAllIds())
val unhidCount = synchronized(this) { hiddenDB.deleteAll() }
val unhiddenNoteQuests = previouslyHiddenNotes.mapNotNull { createQuestForNote(it, emptySet()) }
onUnhidAll()
onUpdated(quests = unhiddenNoteQuests)
return unhidCount
}
fun getHidden(questId: Long): OsmNoteQuestHidden? {
val timestamp = hiddenDB.getTimestamp(questId) ?: return null
val note = noteSource.get(questId) ?: return null
return OsmNoteQuestHidden(note, timestamp)
}
fun getAllHiddenNewerThan(timestamp: Long): List<OsmNoteQuestHidden> {
val noteIdsWithTimestamp = hiddenDB.getNewerThan(timestamp)
val notesById = noteSource.getAll(noteIdsWithTimestamp.map { it.noteId }).associateBy { it.id }
return noteIdsWithTimestamp.mapNotNull { (noteId, timestamp) ->
notesById[noteId]?.let { OsmNoteQuestHidden(it, timestamp) }
}
}
private fun isNoteHidden(noteId: Long): Boolean = hiddenDB.contains(noteId)
private fun getNoteIdsHidden(): Set<Long> = hiddenDB.getAllIds().toSet()
/* ---------------------------------------- Listener ---------------------------------------- */
override fun addListener(listener: OsmNoteQuestSource.Listener) {
listeners.add(listener)
}
override fun removeListener(listener: OsmNoteQuestSource.Listener) {
listeners.remove(listener)
}
private fun onUpdated(
quests: Collection<OsmNoteQuest> = emptyList(),
deletedQuestIds: Collection<Long> = emptyList()
) {
if (quests.isEmpty() && deletedQuestIds.isEmpty()) return
listeners.forEach { it.onUpdated(quests, deletedQuestIds) }
}
private fun onInvalidated() {
listeners.forEach { it.onInvalidated() }
}
/* ------------------------------------- Hide Listeners ------------------------------------- */
fun addHideQuestsListener(listener: HideOsmNoteQuestListener) {
hideListeners.add(listener)
}
fun removeHideQuestsListener(listener: HideOsmNoteQuestListener) {
hideListeners.remove(listener)
}
private fun onHid(edit: OsmNoteQuestHidden) {
hideListeners.forEach { it.onHid(edit) }
}
private fun onUnhid(edit: OsmNoteQuestHidden) {
hideListeners.forEach { it.onUnhid(edit) }
}
private fun onUnhidAll() {
hideListeners.forEach { it.onUnhidAll() }
}
}
private fun Note.shouldShowAsQuest(
userId: Long,
showOnlyNotesPhrasedAsQuestions: Boolean,
blockedNoteIds: Set<Long>
): Boolean {
// don't show notes hidden by user
if (id in blockedNoteIds) return false
/* don't show notes where user replied last unless he wrote a survey required marker */
if (comments.last().isReplyFromUser(userId) &&
!comments.last().containsSurveyRequiredMarker()
) return false
/* newly created notes by user should not be shown if it was both created in this app and has no
replies yet */
if (probablyCreatedByUserInThisApp(userId) && !hasReplies) return false
/* many notes are created to report problems on the map that cannot be resolved
* through an on-site survey.
* Likely, if something is posed as a question, the reporter expects someone to
* answer/comment on it, possibly an information on-site is missing, so let's only show these */
if (showOnlyNotesPhrasedAsQuestions &&
!probablyContainsQuestion() &&
!containsSurveyRequiredMarker()
) return false
return true
}
private fun Note.probablyContainsQuestion(): Boolean {
/* from left to right (if smartass IntelliJ wouldn't mess up left-to-right):
- latin question mark
- greek question mark (a different character than semikolon, though same appearance)
- semikolon (often used instead of proper greek question mark)
- mirrored question mark (used in script written from right to left, like Arabic)
- armenian question mark
- ethopian question mark
- full width question mark (often used in modern Chinese / Japanese)
(Source: https://en.wikipedia.org/wiki/Question_mark)
NOTE: some languages, like Thai, do not use any question mark, so this would be more
difficult to determine.
*/
val questionMarksAroundTheWorld = "[?;;؟՞፧?]"
val text = comments.firstOrNull()?.text
return text?.matches(".*$questionMarksAroundTheWorld.*".toRegex()) ?: false
}
private fun Note.containsSurveyRequiredMarker(): Boolean =
comments.any { it.containsSurveyRequiredMarker() }
private fun NoteComment.containsSurveyRequiredMarker(): Boolean =
text?.matches(".*#surveyme.*".toRegex()) == true
private fun Note.probablyCreatedByUserInThisApp(userId: Long): Boolean {
val firstComment = comments.first()
val isViaApp = firstComment.text?.contains("via " + ApplicationConstants.NAME) == true
return firstComment.isFromUser(userId) && isViaApp
}
private val Note.hasReplies: Boolean get() =
comments.any { it.isReply }
private fun NoteComment.isReplyFromUser(userId: Long): Boolean =
isFromUser(userId) && isReply
private val NoteComment.isReply: Boolean get() =
action == NoteComment.Action.COMMENTED
private fun NoteComment.isFromUser(userId: Long): Boolean =
user?.id == userId
| gpl-3.0 | f636f4aec208e614ae3c227541cff688 | 37.977612 | 111 | 0.676814 | 4.549652 | false | false | false | false |
devulex/eventorage | frontend/src/com/devulex/eventorage/react/dom/ReactDOMAttributes.kt | 1 | 4051 | package com.devulex.eventorage.react.dom
import kotlinx.html.*
import kotlinx.html.attributes.*
private val events = listOf(
"onCopy",
"onCut",
"onPaste",
"onCompositionEnd",
"onCompositionStart",
"onCompositionUpdate",
"onKeyDown",
"onKeyPress",
"onKeyUp",
"onFocus",
"onBlur",
"onChange",
"onInput",
"onSubmit",
"onClick",
"onContextMenu",
"onDoubleClick",
"onDrag",
"onDragEnd",
"onDragEnter",
"onDragExit",
"onDragLeave",
"onDragOver",
"onDragStart",
"onDrop",
"onMouseDown",
"onMouseEnter",
"onMouseLeave",
"onMouseMove",
"onMouseOut",
"onMouseOver",
"onMouseUp",
"onSelect",
"onTouchCancel",
"onTouchEnd",
"onTouchMove",
"onTouchStart",
"onScroll",
"onWheel",
"onAbort",
"onCanPlay",
"onCanPlayThrough",
"onDurationChange",
"onEmptied",
"onEncrypted",
"onEnded",
"onError",
"onLoadedData",
"onLoadedMetadata",
"onLoadStart",
"onPause",
"onPlay",
"onPlaying",
"onProgress",
"onRateChange",
"onSeeked",
"onSeeking",
"onStalled",
"onSuspend",
"onTimeUpdate",
"onVolumeChange",
"onWaiting",
"onLoad",
"onError",
"onAnimationStart",
"onAnimationEnd",
"onAnimationIteration",
"onTransitionEnd",
// HTML attributes
"accept",
"acceptCharset",
"accessKey",
"action",
"allowFullScreen",
"allowTransparency",
"alt",
"async",
"autoComplete",
"autoFocus",
"autoPlay",
"capture",
"cellPadding",
"cellSpacing",
"challenge",
"charSet",
"checked",
"cite",
"classID",
"className",
"colSpan",
"cols",
"content",
"contentEditable",
"contextMenu",
"controls",
"coords",
"crossOrigin",
"data",
"dateTime",
"default",
"defer",
"dir",
"disabled",
"download",
"draggable",
"encType",
"form",
"formAction",
"formEncType",
"formMethod",
"formNoValidate",
"formTarget",
"frameBorder",
"headers",
"height",
"hidden",
"high",
"href",
"hrefLang",
"htmlFor",
"httpEquiv",
"icon",
"id",
"inputMode",
"integrity",
"is",
"keyParams",
"keyType",
"kind",
"label",
"lang",
"list",
"loop",
"low",
"manifest",
"marginHeight",
"marginWidth",
"max",
"maxLength",
"media",
"mediaGroup",
"method",
"min",
"minLength",
"multiple",
"muted",
"name",
"noValidate",
"nonce",
"open",
"optimum",
"pattern",
"placeholder",
"poster",
"preload",
"profile",
"radioGroup",
"readOnly",
"rel",
"required",
"reversed",
"role",
"rowSpan",
"rows",
"sandbox",
"scope",
"scoped",
"scrolling",
"seamless",
"selected",
"shape",
"size",
"sizes",
"span",
"spellCheck",
"src",
"srcDoc",
"srcLang",
"srcSet",
"start",
"step",
"style",
"summary",
"tabIndex",
"target",
"title",
"type",
"useMap",
"value",
"width",
"wmode",
"wrap")
private val eventMap = events.map {it.toLowerCase() to it}.toMap()
fun fixAttributeName(event: String): String = eventMap[event] ?: if (event == "class") "className" else event
private val attributeStringString : Attribute<String> = StringAttribute()
// See https://facebook.github.io/react/docs/forms.html
var INPUT.defaultValue : String
get() = attributeStringString.get(this, "defaultValue")
set(newValue) {attributeStringString.set(this, "defaultValue", newValue)}
var TEXTAREA.defaultValue : String
get() = attributeStringString.get(this, "defaultValue")
set(newValue) {attributeStringString.set(this, "defaultValue", newValue)}
var TEXTAREA.value : String
get() = attributeStringString.get(this, "value")
set(newValue) {attributeStringString.set(this, "value", newValue)}
| mit | fcc045dfd4e165b53a9edb8d9412f924 | 17.413636 | 109 | 0.561343 | 3.633184 | false | false | false | false |
FHannes/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/util.kt | 12 | 7304 | /*
* 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.plugins.gradle.service.resolve
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.gradle.util.GradleConstants.EXTENSION
import org.jetbrains.plugins.groovy.codeInspection.assignment.GrMethodCallInfo
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
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.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.resolve.NON_CODE
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.processAllDeclarations
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getDelegatesToInfo
import org.jetbrains.plugins.groovy.lang.resolve.processors.AccessorResolverProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint
import org.jetbrains.plugins.groovy.lang.resolve.processors.MethodResolverProcessor
import java.util.*
/**
* @author Vladislav.Soroka
* @since 11/11/2016
*/
internal fun PsiClass?.isResolvedInGradleScript() = this is GroovyScriptClass && this.containingFile.isGradleScript()
internal fun PsiFile?.isGradleScript() = this?.originalFile?.virtualFile?.extension == EXTENSION
@JvmField val RESOLVED_CODE = Key.create<Boolean?>("gradle.resolved")
fun processDeclarations(aClass: PsiClass,
processor: PsiScopeProcessor,
state: ResolveState,
place: PsiElement): Boolean {
val name = processor.getHint(com.intellij.psi.scope.NameHint.KEY)?.getName(state)
if (name == null) {
aClass.processDeclarations(processor, state, null, place)
}
else {
val propCandidate = place.references.singleOrNull()?.canonicalText
if (propCandidate != null) {
val closure = PsiTreeUtil.getParentOfType(place, GrClosableBlock::class.java)
val typeToDelegate = closure?.let { getDelegatesToInfo(it)?.typeToDelegate }
if (typeToDelegate != null) {
val fqNameToDelegate = TypesUtil.getQualifiedName(typeToDelegate) ?: return true
val classToDelegate = JavaPsiFacade.getInstance(place.project).findClass(fqNameToDelegate, place.resolveScope) ?: return true
if (classToDelegate !== aClass) {
val parent = place.parent
if (parent is GrMethodCall) {
if (canBeMethodOf(propCandidate, parent, typeToDelegate)) return true
}
}
}
}
val lValue: Boolean = place is GrReferenceExpression && PsiUtil.isLValue(place)
if (!lValue) {
val isSetterCandidate = name.startsWith("set")
val isGetterCandidate = name.startsWith("get")
val processedSignatures = HashSet<List<String>>()
if (isGetterCandidate || !isSetterCandidate) {
val propertyName = name.removePrefix("get").decapitalize()
for (method in aClass.findMethodsByName(propertyName, true)) {
processedSignatures.add(method.getSignature(PsiSubstitutor.EMPTY).parameterTypes.map({ it.canonicalText }))
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(method, state)) return false
}
for (method in aClass.findMethodsByName("set" + propertyName.capitalize(), true)) {
if (PsiType.VOID != method.returnType) continue
if (processedSignatures.contains(method.getSignature(PsiSubstitutor.EMPTY).parameterTypes.map({ it.canonicalText }))) continue
processedSignatures.add(method.getSignature(PsiSubstitutor.EMPTY).parameterTypes.map({ it.canonicalText }))
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(method, state)) return false
}
}
if (!isGetterCandidate && !isSetterCandidate) {
for (method in aClass.findMethodsByName("get" + name.capitalize(), true)) {
if (processedSignatures.contains(method.getSignature(PsiSubstitutor.EMPTY).parameterTypes.map({ it.canonicalText }))) continue
processedSignatures.add(method.getSignature(PsiSubstitutor.EMPTY).parameterTypes.map({ it.canonicalText }))
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(method, state)) return false
}
}
for (method in aClass.findMethodsByName(name, true)) {
if (processedSignatures.contains(method.getSignature(PsiSubstitutor.EMPTY).parameterTypes.map({ it.canonicalText }))) continue
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(method, state)) return false
}
}
else {
for (method in aClass.findMethodsByName(name, true)) {
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(method, state)) return false
}
}
}
return true
}
fun canBeMethodOf(methodName: String,
place: GrMethodCall,
type: PsiType): Boolean {
val methodCallInfo = GrMethodCallInfo(place)
val invoked = methodCallInfo.invokedExpression ?: return false
val argumentTypes = methodCallInfo.argumentTypes
val thisType = TypesUtil.boxPrimitiveType(type, place.manager, place.resolveScope)
val processor = MethodResolverProcessor(methodName, invoked, false, thisType, argumentTypes, PsiType.EMPTY_ARRAY, false)
val state = ResolveState.initial().let {
it.put(ClassHint.RESOLVE_CONTEXT, invoked)
it.put(NON_CODE, false)
}
processAllDeclarations(thisType, processor, state, invoked)
val hasApplicableMethods = processor.hasApplicableCandidates()
if (hasApplicableMethods) {
return true
}
//search for getters
for (getterName in GroovyPropertyUtils.suggestGettersName(methodName)) {
val getterResolver = AccessorResolverProcessor(getterName, methodName, invoked, true, thisType, PsiType.EMPTY_ARRAY)
processAllDeclarations(thisType, getterResolver, state, invoked)
if (getterResolver.hasApplicableCandidates()) {
return true
}
}
//search for setters
for (setterName in GroovyPropertyUtils.suggestSettersName(methodName)) {
val getterResolver = AccessorResolverProcessor(setterName, methodName, invoked, false, thisType, PsiType.EMPTY_ARRAY)
processAllDeclarations(thisType, getterResolver, state, invoked)
if (getterResolver.hasApplicableCandidates()) {
return true
}
}
return false
}
| apache-2.0 | 87342dabea170b5fa3c933222045bdcf | 46.122581 | 136 | 0.736309 | 4.57931 | false | false | false | false |
tasks/tasks | app/src/main/java/com/todoroo/astrid/repeats/RepeatTaskHelper.kt | 1 | 11362 | /*
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.repeats
import com.todoroo.andlib.utility.DateUtilities
import com.todoroo.astrid.alarms.AlarmService
import com.todoroo.astrid.dao.TaskDao
import com.todoroo.astrid.data.Task
import com.todoroo.astrid.data.Task.Companion.createDueDate
import com.todoroo.astrid.gcal.GCalHelper
import com.todoroo.astrid.service.TaskCompleter
import net.fortuna.ical4j.model.Date
import net.fortuna.ical4j.model.Recur
import net.fortuna.ical4j.model.WeekDay
import org.tasks.LocalBroadcastManager
import org.tasks.data.Alarm
import org.tasks.data.Alarm.Companion.TYPE_SNOOZE
import org.tasks.date.DateTimeUtils.newDateTime
import org.tasks.repeats.RecurrenceUtils.newRecur
import org.tasks.time.DateTime
import timber.log.Timber
import java.text.ParseException
import java.util.*
import javax.inject.Inject
class RepeatTaskHelper @Inject constructor(
private val gcalHelper: GCalHelper,
private val alarmService: AlarmService,
private val taskDao: TaskDao,
private val localBroadcastManager: LocalBroadcastManager,
private val taskCompleter: TaskCompleter,
) {
suspend fun handleRepeat(task: Task) {
val recurrence = task.recurrence
if (recurrence.isNullOrBlank()) {
return
}
val repeatAfterCompletion = task.repeatAfterCompletion()
val newDueDate: Long
val rrule: Recur
val count: Int
try {
rrule = initRRule(recurrence)
count = rrule.count
if (count == 1) {
broadcastCompletion(task)
return
}
newDueDate = computeNextDueDate(task, recurrence, repeatAfterCompletion)
if (newDueDate == -1L) {
return
}
} catch (e: ParseException) {
Timber.e(e)
return
}
val oldDueDate = task.dueDate
val repeatUntil = task.repeatUntil
if (repeatFinished(newDueDate, repeatUntil)) {
broadcastCompletion(task)
return
}
if (count > 1) {
rrule.count = count - 1
task.setRecurrence(rrule)
}
task.reminderLast = 0L
task.completionDate = 0L
task.setDueDateAdjustingHideUntil(newDueDate)
gcalHelper.rescheduleRepeatingTask(task)
taskDao.save(task)
val previousDueDate =
oldDueDate
.takeIf { it > 0 }
?: newDueDate - (computeNextDueDate(task, recurrence, repeatAfterCompletion) - newDueDate)
rescheduleAlarms(task.id, previousDueDate, newDueDate)
taskCompleter.setComplete(task, false)
broadcastCompletion(task, previousDueDate)
}
private fun broadcastCompletion(task: Task, oldDueDate: Long = 0L) {
if (!task.isSuppressRefresh()) {
localBroadcastManager.broadcastTaskCompleted(task.id, oldDueDate)
}
}
suspend fun undoRepeat(task: Task, oldDueDate: Long) {
task.completionDate = 0L
try {
val recur = newRecur(task.recurrence!!)
val count = recur.count
if (count > 0) {
recur.count = count + 1
}
task.setRecurrence(recur)
val newDueDate = task.dueDate
task.setDueDateAdjustingHideUntil(
if (oldDueDate > 0) {
oldDueDate
} else {
newDueDate - (computeNextDueDate(task, task.recurrence!!, false) - newDueDate)
}
)
rescheduleAlarms(task.id, newDueDate, task.dueDate)
} catch (e: ParseException) {
Timber.e(e)
}
taskDao.save(task)
}
private suspend fun rescheduleAlarms(taskId: Long, oldDueDate: Long, newDueDate: Long) {
if (oldDueDate <= 0 || newDueDate <= 0) {
return
}
alarmService.getAlarms(taskId)
.filter { it.type != TYPE_SNOOZE }
.onEach {
if (it.type == Alarm.TYPE_DATE_TIME) {
it.time += newDueDate - oldDueDate
}
}
.let { alarmService.synchronizeAlarms(taskId, it.toMutableSet()) }
}
companion object {
private val weekdayCompare = Comparator { object1: WeekDay, object2: WeekDay -> WeekDay.getCalendarDay(object1) - WeekDay.getCalendarDay(object2) }
private fun repeatFinished(newDueDate: Long, repeatUntil: Long): Boolean {
return repeatUntil > 0 && newDateTime(newDueDate).startOfDay().millis > repeatUntil
}
/** Compute next due date */
@Throws(ParseException::class)
fun computeNextDueDate(task: Task, recurrence: String, repeatAfterCompletion: Boolean): Long {
val rrule = initRRule(recurrence)
// initialize startDateAsDV
val original = setUpStartDate(task, repeatAfterCompletion, rrule.frequency)
val startDateAsDV = setUpStartDateAsDV(task, original)
return if (rrule.frequency == Recur.Frequency.HOURLY || rrule.frequency == Recur.Frequency.MINUTELY) {
handleSubdayRepeat(original, rrule)
} else if (rrule.frequency == Recur.Frequency.WEEKLY && rrule.dayList.isNotEmpty() && repeatAfterCompletion) {
handleWeeklyRepeatAfterComplete(rrule, original, task.hasDueTime())
} else if (rrule.frequency == Recur.Frequency.MONTHLY && rrule.dayList.isEmpty()) {
handleMonthlyRepeat(original, startDateAsDV, task.hasDueTime(), rrule)
} else {
invokeRecurrence(rrule, original, startDateAsDV)
}
}
private fun handleWeeklyRepeatAfterComplete(
recur: Recur, original: DateTime, hasDueTime: Boolean): Long {
val byDay = recur.dayList
var newDate = original.millis
newDate += DateUtilities.ONE_WEEK * (recur.interval - 1)
var date = DateTime(newDate)
Collections.sort(byDay, weekdayCompare)
val next = findNextWeekday(byDay, date)
do {
date = date.plusDays(1)
} while (date.dayOfWeek != WeekDay.getCalendarDay(next))
val time = date.millis
return if (hasDueTime) {
createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, time)
} else {
createDueDate(Task.URGENCY_SPECIFIC_DAY, time)
}
}
private fun handleMonthlyRepeat(
original: DateTime, startDateAsDV: Date, hasDueTime: Boolean, recur: Recur): Long {
return if (original.isLastDayOfMonth) {
val interval = recur.interval.coerceAtLeast(1)
val newDateTime = original.plusMonths(interval)
val time = newDateTime.withDayOfMonth(newDateTime.numberOfDaysInMonth).millis
if (hasDueTime) {
createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, time)
} else {
createDueDate(Task.URGENCY_SPECIFIC_DAY, time)
}
} else {
invokeRecurrence(recur, original, startDateAsDV)
}
}
private fun findNextWeekday(byDay: List<WeekDay>, date: DateTime): WeekDay {
val next = byDay[0]
for (weekday in byDay) {
if (WeekDay.getCalendarDay(weekday) > date.dayOfWeek) {
return weekday
}
}
return next
}
private fun invokeRecurrence(recur: Recur, original: DateTime, startDateAsDV: Date): Long {
return recur.getNextDate(startDateAsDV, startDateAsDV)
?.let { buildNewDueDate(original, it) }
?: throw IllegalStateException("recur=$recur original=$original startDateAsDv=$startDateAsDV")
}
/** Compute long due date from DateValue */
private fun buildNewDueDate(original: DateTime, nextDate: Date): Long {
val newDueDate: Long
if (nextDate is net.fortuna.ical4j.model.DateTime) {
var date = DateTime.from(nextDate)
// time may be inaccurate due to DST, force time to be same
date = date.withHourOfDay(original.hourOfDay).withMinuteOfHour(original.minuteOfHour)
newDueDate = createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, date.millis)
} else {
newDueDate = createDueDate(
Task.URGENCY_SPECIFIC_DAY,
DateTime.from(nextDate).millis)
}
return newDueDate
}
/** Initialize RRule instance */
@Throws(ParseException::class)
private fun initRRule(recurrence: String): Recur {
val rrule = newRecur(recurrence)
// handle the iCalendar "byDay" field differently depending on if
// we are weekly or otherwise
if (rrule.frequency != Recur.Frequency.WEEKLY && rrule.frequency != Recur.Frequency.MONTHLY) {
rrule.dayList.clear()
}
return rrule
}
/** Set up repeat start date */
private fun setUpStartDate(
task: Task, repeatAfterCompletion: Boolean, frequency: Recur.Frequency): DateTime {
return if (repeatAfterCompletion) {
var startDate = if (task.isCompleted) newDateTime(task.completionDate) else newDateTime()
if (task.hasDueTime() && frequency != Recur.Frequency.HOURLY && frequency != Recur.Frequency.MINUTELY) {
val dueDate = newDateTime(task.dueDate)
startDate = startDate
.withHourOfDay(dueDate.hourOfDay)
.withMinuteOfHour(dueDate.minuteOfHour)
.withSecondOfMinute(dueDate.secondOfMinute)
}
startDate
} else {
if (task.hasDueDate()) newDateTime(task.dueDate) else newDateTime()
}
}
private fun setUpStartDateAsDV(task: Task, startDate: DateTime): Date {
return if (task.hasDueTime()) {
startDate.toDateTime()
} else {
startDate.toDate()
}
}
private fun handleSubdayRepeat(startDate: DateTime, recur: Recur): Long {
val millis: Long = when (recur.frequency) {
Recur.Frequency.HOURLY -> DateUtilities.ONE_HOUR
Recur.Frequency.MINUTELY -> DateUtilities.ONE_MINUTE
else -> throw RuntimeException(
"Error handing subday repeat: " + recur.frequency) // $NON-NLS-1$
}
val newDueDate = startDate.millis + millis * recur.interval
return createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, newDueDate)
}
private val Task.repeatUntil: Long
get() = recurrence
?.takeIf { it.isNotBlank() }
?.let { newRecur(it) }
?.until
?.let { DateTime.from(it) }
?.millis
?: 0L
}
} | gpl-3.0 | ddb2f3b950a7ee142bbbf4513f3a8379 | 39.727599 | 155 | 0.58678 | 4.452194 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/strategy/manual/StdinCommandI.kt | 1 | 721 | package org.droidmate.exploration.strategy.manual
interface StdinCommandI<T,R> {
val createAction:CandidateCreator<T, R?>
val actionOptions: List<TargetTypeI<T, R?>>
val isValid : (input: List<String>, suggested: T?, numCandidates: Int) -> TargetTypeI<T, R?>
suspend fun decideBySTDIN(suggested: T? = null, candidates: List<T> = emptyList()): R {
println("_____________________________")
var action: R?
do {
action = fromSTDIN(isValid,
widgetTarget = { null },
candidates = candidates,
suggested = suggested
)
}while(action == null)
return action
}
}
@Suppress("ClassName")
class LIST_C<T,R>(createCandidate: CandidateCreator<T, R>, id: Int): ControlCmd<T, R>(createCandidate, id)
| gpl-3.0 | 1339adb93e971962c647c1d6971913bd | 26.730769 | 107 | 0.662968 | 3.277273 | false | false | false | false |
arturbosch/detekt | detekt-rules-coroutines/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/coroutines/SuspendFunWithFlowReturnType.kt | 1 | 3578 | package io.gitlab.arturbosch.detekt.rules.coroutines
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution
import io.gitlab.arturbosch.detekt.rules.fqNameOrNull
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
/**
* Functions that return `Flow` from `kotlinx.coroutines.flow` should not be marked as `suspend`.
* `Flows` are intended to be cold observable streams. The act of simply invoking a function that
* returns a `Flow`, should not have any side effects. Only once collection begins against the
* returned `Flow`, should work actually be done.
*
* See https://kotlinlang.org/docs/reference/coroutines/flow.html#flows-are-cold
*
* <noncompliant>
* suspend fun observeSignals(): Flow<Unit> {
* val pollingInterval = getPollingInterval() // Done outside of the flow builder block.
* return flow {
* while (true) {
* delay(pollingInterval)
* emit(Unit)
* }
* }
* }
*
* private suspend fun getPollingInterval(): Long {
* // Return the polling interval from some repository
* // in a suspending manner.
* }
* </noncompliant>
*
* <compliant>
* fun observeSignals(): Flow<Unit> {
* return flow {
* val pollingInterval = getPollingInterval() // Moved into the flow builder block.
* while (true) {
* delay(pollingInterval)
* emit(Unit)
* }
* }
* }
*
* private suspend fun getPollingInterval(): Long {
* // Return the polling interval from some repository
* // in a suspending manner.
* }
* </compliant>
*
*/
@RequiresTypeResolution
class SuspendFunWithFlowReturnType(config: Config) : Rule(config) {
override val issue = Issue(
id = "SuspendFunWithFlowReturnType",
severity = Severity.Minor,
description = "`suspend` modifier should not be used for functions that return a " +
"Coroutines Flow type. Flows are cold streams and invoking a function that returns " +
"one should not produce any side effects.",
debt = Debt.TEN_MINS
)
override fun visitNamedFunction(function: KtNamedFunction) {
if (bindingContext == BindingContext.EMPTY) return
val suspendModifier = function.modifierList?.getModifier(KtTokens.SUSPEND_KEYWORD) ?: return
bindingContext[BindingContext.FUNCTION, function]
?.returnType
?.takeIf { it.isCoroutinesFlow() }
?.also {
report(
CodeSmell(
issue = issue,
entity = Entity.from(suspendModifier),
message = "`suspend` function returns Coroutines Flow."
)
)
}
}
private fun KotlinType.isCoroutinesFlow(): Boolean {
return sequence {
yield(this@isCoroutinesFlow)
yieldAll([email protected]())
}
.mapNotNull { it.fqNameOrNull()?.asString() }
.contains("kotlinx.coroutines.flow.Flow")
}
}
| apache-2.0 | c57943ce5d20e3f4d94d20661f3f6e1e | 35.510204 | 100 | 0.65735 | 4.379437 | false | false | false | false |
ReDFoX43rus/Sirius-Mileage | app/src/main/java/com/liberaid/siriusmileage/obd/SiriusD42IgnitionCount.kt | 1 | 725 | package com.liberaid.siriusmileage.obd
import com.github.pires.obd.commands.ObdCommand
/**
* [SiriusD42IgnitionCount] is custom OBDCommand
* @property _name is the name of this command
* @property _calculatedResult the units
* */
class SiriusD42IgnitionCount(val _name: String, val _calculatedResult: String) : ObdCommand("2107"){
private var counter = -1
override fun getName(): String = _name
override fun getFormattedResult(): String = "$counter $_calculatedResult"
override fun getCalculatedResult(): String = _calculatedResult
/**
* Decode bytes to integer
* */
override fun performCalculations() {
counter = (buffer[15] shl 8) + buffer[16]
}
} | gpl-3.0 | c5852f206a7d5ac0ff53b58048f6d114 | 29.608696 | 100 | 0.68 | 3.856383 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/ProjectIndicator.kt | 1 | 935 | package net.nemerosa.ontrack.extension.indicators.ui
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.extension.indicators.model.Indicator
import net.nemerosa.ontrack.extension.indicators.model.IndicatorCompliance
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.model.structure.Signature
data class ProjectIndicator(
val project: Project,
val type: ProjectIndicatorType,
val value: JsonNode,
val compliance: IndicatorCompliance?,
val comment: String?,
val signature: Signature
) {
constructor(project: Project, indicator: Indicator<*>) : this(
project = project,
type = ProjectIndicatorType(indicator.type),
value = indicator.toClientJson(),
compliance = indicator.compliance,
comment = indicator.comment,
signature = indicator.signature
)
} | mit | ea0b7a46d90f27db422face4dc2f7d7f | 33.666667 | 74 | 0.705882 | 4.973404 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/control/EditControllerSettingsActivity.kt | 1 | 2901 | package treehou.se.habit.ui.control
import android.graphics.PorterDuff
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import javax.inject.Inject
import treehou.se.habit.BaseActivity
import treehou.se.habit.HabitApplication
import treehou.se.habit.R
import treehou.se.habit.core.db.model.controller.ControllerDB
import treehou.se.habit.ui.colorpicker.ColorDialog
class EditControllerSettingsActivity : BaseActivity(), ColorDialog.ColorDialogCallback {
private lateinit var txtName: EditText
private lateinit var btnColor: Button
private lateinit var cbxAsNotification: CheckBox
@Inject lateinit var controllerUtil: ControllerUtil
private var controller: ControllerDB? = null
override fun onCreate(savedInstanceState: Bundle?) {
(applicationContext as HabitApplication).component().inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_controller_settings)
if (intent.extras != null) {
val id = intent.extras!!.getLong(ARG_ID)
controller = ControllerDB.load(realm, id)
}
txtName = findViewById(R.id.txt_name)
txtName.setText(controller!!.name)
btnColor = findViewById(R.id.btn_color)
btnColor.setOnClickListener {
val fragmentManager = supportFragmentManager
val fragment = ColorDialog.instance()
fragmentManager.beginTransaction()
.add(fragment, "colordialog")
.commit()
}
cbxAsNotification = findViewById(R.id.as_notification)
cbxAsNotification.isChecked = controller!!.showNotification
cbxAsNotification.setOnCheckedChangeListener { _, isChecked ->
realm.beginTransaction()
controller!!.showNotification = isChecked
realm.commitTransaction()
}
updateColorPalette(controller!!.color)
findViewById<View>(R.id.container).setOnClickListener({ finish() })
}
/**
* Update ui to match color set.
*
* @param color the color to use as base.
*/
fun updateColorPalette(color: Int) {
btnColor.background.setColorFilter(color, PorterDuff.Mode.MULTIPLY)
}
override fun onPause() {
super.onPause()
realm.beginTransaction()
controller!!.name = txtName.text.toString()
realm.commitTransaction()
finish()
}
override fun finish() {
super.finish()
overridePendingTransition(0, 0)
}
override fun setColor(color: Int) {
realm.beginTransaction()
controller!!.color = color
realm.commitTransaction()
btnColor.background.setColorFilter(color, PorterDuff.Mode.MULTIPLY)
}
companion object {
val ARG_ID = "ARG_ID"
}
}
| epl-1.0 | c134b5881703c63602e5ee7a533562e7 | 28.30303 | 88 | 0.674595 | 4.795041 | false | false | false | false |
Nilhcem/xebia-android-hp-kotlin | app/src/main/kotlin/com/nilhcem/henripotier/core/ui/recyclerview/AutofitRecyclerView.kt | 1 | 1142 | package com.nilhcem.henripotier.core.ui.recyclerview
import android.content.Context
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
class AutofitRecyclerView : RecyclerView {
private var manager: GridLayoutManager
private var columnWidth = -1
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
if (attrs != null) {
val array = context.obtainStyledAttributes(attrs, intArrayOf(android.R.attr.columnWidth))
columnWidth = array.getDimensionPixelSize(0, -1)
array.recycle()
}
manager = GridLayoutManager(context, 1)
setLayoutManager(manager)
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
super.onMeasure(widthSpec, heightSpec)
if (columnWidth > 0) {
manager.setSpanCount(Math.max(1, getMeasuredWidth() / columnWidth))
}
}
}
| apache-2.0 | 3172f546b2b81cecd1543c753c7b8cf6 | 32.588235 | 106 | 0.695271 | 4.496063 | false | false | false | false |
olonho/carkot | car_srv/kotlinSrv/src/JSImport.kt | 1 | 3320 | @native
fun require(name: String): dynamic = noImpl
fun <T> encodeProtoBuf(protoMessage: T): ByteArray {
val routeBytes: ByteArray
when (protoMessage) {
is LocationResponse -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is UploadResult -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is DebugResponseMemoryStats -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is DebugRequest -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is RouteResponse -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is RouteRequest -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is RouteMetricRequest -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is TaskRequest -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is RouteDoneRequest -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is SonarResponse -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is SonarRequest -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
is SonarExploreAngleRequest -> {
val protoSize = protoMessage.getSizeNoTag()
routeBytes = ByteArray(protoSize)
val codedOutput = CodedOutputStream(routeBytes)
protoMessage.writeTo(codedOutput)
}
else -> {
println("PROTO MESSAGE DON'T ENCODE!")
routeBytes = ByteArray(0)
}
}
return routeBytes
} | mit | 70ea71c04a35c5656fcfd63f531d1789 | 34.329787 | 59 | 0.606325 | 5.068702 | false | false | false | false |
xiaojinzi123/Component | ComponentImpl/src/main/java/com/xiaojinzi/component/support/ProxyIntentAct.kt | 1 | 1909 | package com.xiaojinzi.component.support
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import com.xiaojinzi.component.ComponentActivityStack.getTopActivityExcept
import com.xiaojinzi.component.impl.Router
/**
* 此界面是一个无界面的, 当使用者通过 [ProxyIntentBuilder]
* 构建一个代理 [android.content.Intent] 之后. 此 `Intent` 可以交给
* 任何一个可以发起此 `Intent` 的地方, 比如:
* 1. 系统小部件
* 2. 消息栏
* 3. 任何 PendingIntent 使用到的地方
*/
class ProxyIntentAct : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 获取数据
val bundle = intent.extras
var launchActivity = getTopActivityExcept(this.javaClass)
val isUseSelfActivity = launchActivity == null
if (launchActivity == null) {
launchActivity = this
}
// 如果不是使用此 Activity 跳转, 那么立即销毁自己
if (!isUseSelfActivity) {
finish()
}
// 发起跳转
Router.with(launchActivity)
.proxyBundle(bundle!!)
.afterEventAction {
if (isUseSelfActivity) {
finish()
}
Unit
}
.forward()
}
companion object {
const val EXTRA_ROUTER_PROXY_INTENT = "router_proxy_intent"
const val EXTRA_ROUTER_PROXY_INTENT_URL = "router_proxy_intent_url"
const val EXTRA_ROUTER_PROXY_INTENT_BUNDLE = "router_proxy_intent_bundle"
const val EXTRA_ROUTER_PROXY_INTENT_OPTIONS = "router_proxy_intent_options"
const val EXTRA_ROUTER_PROXY_INTENT_FLAGS = "router_proxy_intent_flags"
const val EXTRA_ROUTER_PROXY_INTENT_CATEGORIES = "router_proxy_intent_categories"
}
} | apache-2.0 | a877084de30f7a30ce445918e3920b1b | 33.117647 | 89 | 0.629097 | 4.140476 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.