content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.io
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.CompressionUtil
import com.intellij.util.ConcurrencyUtil
import it.unimi.dsi.fastutil.Hash
import it.unimi.dsi.fastutil.ints.IntLinkedOpenHashSet
import it.unimi.dsi.fastutil.ints.IntSet
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap
import java.io.*
import java.nio.file.FileAlreadyExistsException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.concurrent.ExecutorService
private const val VERSION = 0
internal enum class WalOpCode(internal val code: Int) {
PUT(0),
REMOVE(1),
APPEND(2)
}
internal class PersistentEnumeratorWal<Data> @Throws(IOException::class) @JvmOverloads constructor(dataDescriptor: KeyDescriptor<Data>,
useCompression: Boolean,
file: Path,
walIoExecutor: ExecutorService,
compact: Boolean = false) : Closeable {
private val underlying = PersistentMapWal(dataDescriptor, integerExternalizer, useCompression, file, walIoExecutor, compact)
fun enumerate(data: Data, id: Int) = underlying.put(data, id)
fun flush() = underlying.flush()
override fun close() = underlying.close()
}
internal class PersistentMapWal<K, V> @Throws(IOException::class) @JvmOverloads constructor(private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>,
private val useCompression: Boolean,
private val file: Path,
private val walIoExecutor: ExecutorService /*todo ensure sequential*/,
compact: Boolean = false) : Closeable {
private val out: DataOutputStream
val version: Int = VERSION
init {
if (compact) {
tryCompact(file, keyDescriptor, valueExternalizer)?.let { compactedWal ->
FileUtil.deleteWithRenaming(file)
FileUtil.rename(compactedWal.toFile(), file.toFile())
}
}
ensureCompatible(version, useCompression, file)
out = DataOutputStream(Files.newOutputStream(file, StandardOpenOption.WRITE, StandardOpenOption.APPEND).buffered())
}
@Throws(IOException::class)
private fun ensureCompatible(expectedVersion: Int, useCompression: Boolean, file: Path) {
if (!Files.exists(file)) {
Files.createDirectories(file.parent)
DataOutputStream(Files.newOutputStream(file, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)).use {
DataInputOutputUtil.writeINT(it, expectedVersion)
it.writeBoolean(useCompression)
}
return
}
val (actualVersion, actualUsesCompression) = DataInputStream(Files.newInputStream(file, StandardOpenOption.READ)).use {
DataInputOutputUtil.readINT(it) to it.readBoolean()
}
if (actualVersion != expectedVersion) {
throw VersionUpdatedException(file, expectedVersion, actualVersion)
}
if (actualUsesCompression != useCompression) {
throw VersionUpdatedException(file, useCompression, actualUsesCompression)
}
}
private fun WalOpCode.write(outputStream: DataOutputStream): Unit = outputStream.writeByte(code)
private fun ByteArray.write(outputStream: DataOutputStream) {
if (useCompression) {
CompressionUtil.writeCompressed(outputStream, this, 0, size)
}
else {
outputStream.writeInt(size)
outputStream.write(this)
}
}
private fun AppendablePersistentMap.ValueDataAppender.writeToByteArray(): ByteArray {
val baos = UnsyncByteArrayOutputStream()
append(DataOutputStream(baos))
return baos.toByteArray()
}
@Throws(IOException::class)
fun appendData(key: K, appender: AppendablePersistentMap.ValueDataAppender) {
walIoExecutor.submit {
WalOpCode.APPEND.write(out)
keyDescriptor.save(out, key)
appender.writeToByteArray().write(out)
}
}
@Throws(IOException::class)
fun put(key: K, value: V) {
walIoExecutor.submit {
WalOpCode.PUT.write(out)
keyDescriptor.save(out, key)
writeData(value, valueExternalizer).write(out)
}
}
@Throws(IOException::class)
fun remove(key: K) {
walIoExecutor.submit {
WalOpCode.REMOVE.write(out)
keyDescriptor.save(out, key)
}
}
@Throws(IOException::class) // todo rethrow io exception
fun flush() {
walIoExecutor.submit {
out.flush()
}.get()
}
// todo rethrow io exception
@Throws(IOException::class)
override fun close() {
walIoExecutor.submit {
out.close()
}.get()
}
@Throws(IOException::class)
fun closeAndDelete() {
close()
FileUtil.deleteWithRenaming(file)
}
}
private val integerExternalizer: EnumeratorIntegerDescriptor
get() = EnumeratorIntegerDescriptor.INSTANCE
sealed class WalEvent<K, V> {
data class PutEvent<K, V>(override val key: K, val value: V): WalEvent<K, V>()
data class RemoveEvent<K, V>(override val key: K): WalEvent<K, V>()
data class AppendEvent<K, V>(override val key: K, val data: ByteArray): WalEvent<K, V>() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AppendEvent<*, *>
if (key != other.key) return false
if (!data.contentEquals(other.data)) return false
return true
}
override fun hashCode(): Int {
var result = key?.hashCode() ?: 0
result = 31 * result + data.contentHashCode()
return result
}
}
abstract val key: K
}
@Throws(IOException::class)
fun <Data> restoreMemoryEnumeratorFromWal(walFile: Path,
dataDescriptor: KeyDescriptor<Data>): List<Data> {
return restoreFromWal(walFile, dataDescriptor, integerExternalizer, object : Accumulator<Data, Int, List<Data>> {
val result = arrayListOf<Data>()
override fun get(key: Data): Int = error("get not supported")
override fun remove(key: Data) = error("remove not supported")
override fun put(key: Data, value: Int) {
assert(result.size == value)
result.add(key)
}
override fun result(): List<Data> = result
}).toList()
}
@Throws(IOException::class)
fun <Data> restorePersistentEnumeratorFromWal(walFile: Path,
outputMapFile: Path,
dataDescriptor: KeyDescriptor<Data>): PersistentEnumerator<Data> {
if (Files.exists(outputMapFile)) {
throw FileAlreadyExistsException(outputMapFile.toString())
}
return restoreFromWal(walFile, dataDescriptor, integerExternalizer, object : Accumulator<Data, Int, PersistentEnumerator<Data>> {
val result = PersistentEnumerator(outputMapFile, dataDescriptor, 1024)
override fun get(key: Data): Int = error("get not supported")
override fun remove(key: Data) = error("remove not supported")
override fun put(key: Data, value: Int) = assert(result.enumerate(key) == value)
override fun result(): PersistentEnumerator<Data> = result
})
}
@Throws(IOException::class)
fun <K, V> restorePersistentMapFromWal(walFile: Path,
outputMapFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): PersistentMap<K, V> {
if (Files.exists(outputMapFile)) {
throw FileAlreadyExistsException(outputMapFile.toString())
}
return restoreFromWal(walFile, keyDescriptor, valueExternalizer, object : Accumulator<K, V, PersistentMap<K, V>> {
val result = PersistentHashMap(outputMapFile, keyDescriptor, valueExternalizer)
override fun get(key: K): V? = result.get(key)
override fun remove(key: K) = result.remove(key)
override fun put(key: K, value: V) = result.put(key, value)
override fun result(): PersistentMap<K, V> = result
})
}
@Throws(IOException::class)
fun <K, V> restoreHashMapFromWal(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): Map<K, V> {
return restoreFromWal(walFile, keyDescriptor, valueExternalizer, object : Accumulator<K, V, Map<K, V>> {
private val map = linkedMapOf<K, V>()
override fun get(key: K): V? = map.get(key)
override fun remove(key: K) {
map.remove(key)
}
override fun put(key: K, value: V) {
map.put(key, value)
}
override fun result(): Map<K, V> = map
})
}
private fun <K, V> tryCompact(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>): Path? {
if (!Files.exists(walFile)) {
return null
}
val keyToLastEvent = Object2ObjectOpenCustomHashMap<K, IntSet>(object : Hash.Strategy<K> {
override fun equals(a: K?, b: K?): Boolean {
if (a == b) return true
if (a == null) return false
if (b == null) return false
return keyDescriptor.isEqual(a, b)
}
override fun hashCode(o: K?): Int = keyDescriptor.getHashCode(o)
})
val shouldCompact = PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use {
var eventCount = 0
for (walEvent in it.readWal()) {
when (walEvent) {
is WalEvent.AppendEvent -> keyToLastEvent.computeIfAbsent(walEvent.key) { IntLinkedOpenHashSet() }.add(eventCount)
is WalEvent.PutEvent -> keyToLastEvent.put(walEvent.key, IntLinkedOpenHashSet().also{ set -> set.add(eventCount) })
is WalEvent.RemoveEvent -> keyToLastEvent.put(walEvent.key, IntLinkedOpenHashSet())
}
keyToLastEvent.computeIfAbsent(walEvent.key) { IntLinkedOpenHashSet() }.add(eventCount)
eventCount++
}
keyToLastEvent.size * 2 < eventCount
}
if (!shouldCompact) return null
val compactedWalFile = walFile.resolveSibling("${walFile.fileName}_compacted")
PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use { walPlayer ->
PersistentMapWal(keyDescriptor, valueExternalizer, walPlayer.useCompression, compactedWalFile, ConcurrencyUtil.newSameThreadExecutorService()).use { compactedWal ->
walPlayer.readWal().forEachIndexed{index, walEvent ->
val key = walEvent.key
val events = keyToLastEvent.get(key) ?: throw IOException("No events found for key = $key")
if (events.contains(index)) {
when (walEvent) {
is WalEvent.AppendEvent -> compactedWal.appendData(key, AppendablePersistentMap.ValueDataAppender { out -> out.write(walEvent.data) })
is WalEvent.PutEvent -> compactedWal.put(key, walEvent.value)
is WalEvent.RemoveEvent -> {/*do nothing*/}
}
}
}
}
}
return compactedWalFile
}
private fun <V> readData(array: ByteArray, valueExternalizer: DataExternalizer<V>): V {
return valueExternalizer.read(DataInputStream(ByteArrayInputStream(array)))
}
private fun <V> writeData(value: V, valueExternalizer: DataExternalizer<V>): ByteArray {
val baos = UnsyncByteArrayOutputStream()
valueExternalizer.save(DataOutputStream(baos), value)
return baos.toByteArray()
}
private interface Accumulator<K, V, R> {
fun get(key: K): V?
fun remove(key: K)
fun put(key: K, value: V)
fun result(): R
}
private fun <K, V, R> restoreFromWal(walFile: Path,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>,
accumulator: Accumulator<K, V, R>): R {
return PersistentMapWalPlayer(keyDescriptor, valueExternalizer, walFile).use {
for (walEvent in it.readWal()) {
when (walEvent) {
is WalEvent.AppendEvent -> {
val previous = accumulator.get(walEvent.key)
val currentData = if (previous == null) walEvent.data else writeData(previous, valueExternalizer) + walEvent.data
accumulator.put(walEvent.key, readData(currentData, valueExternalizer))
}
is WalEvent.PutEvent -> accumulator.put(walEvent.key, walEvent.value)
is WalEvent.RemoveEvent -> accumulator.remove(walEvent.key)
}
}
accumulator.result()
}
}
class PersistentMapWalPlayer<K, V> @Throws(IOException::class) constructor(private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>,
file: Path) : Closeable {
private val input: DataInputStream
internal val useCompression: Boolean
val version: Int = VERSION
init {
if (!Files.exists(file)) {
throw FileNotFoundException(file.toString())
}
input = DataInputStream(Files.newInputStream(file).buffered())
ensureCompatible(version, input, file)
useCompression = input.readBoolean()
}
@Throws(IOException::class)
private fun ensureCompatible(expectedVersion: Int, input: DataInputStream, file: Path) {
val actualVersion = DataInputOutputUtil.readINT(input)
if (actualVersion != expectedVersion) {
throw VersionUpdatedException(file, expectedVersion, actualVersion)
}
}
fun readWal(): Sequence<WalEvent<K, V>> = generateSequence {
readNextEvent()
}
@Throws(IOException::class)
override fun close() = input.close()
@Throws(IOException::class)
private fun readNextEvent(): WalEvent<K, V>? {
val walOpCode: WalOpCode
try {
walOpCode = readNextOpCode(input)
}
catch (e: EOFException) {
return null
}
return when (walOpCode) {
WalOpCode.PUT -> WalEvent.PutEvent(keyDescriptor.read(input), readData(readByteArray(input), valueExternalizer))
WalOpCode.REMOVE -> WalEvent.RemoveEvent(keyDescriptor.read(input))
WalOpCode.APPEND -> WalEvent.AppendEvent(keyDescriptor.read(input), readByteArray(input))
}
}
private fun readByteArray(inputStream: DataInputStream): ByteArray {
if (useCompression) {
return CompressionUtil.readCompressed(inputStream)
}
else {
return ByteArray(inputStream.readInt()).also { inputStream.readFully(it) }
}
}
private fun readNextOpCode(inputStream: DataInputStream): WalOpCode =
WalOpCode.values()[inputStream.readByte().toInt()]
} | platform/util/src/com/intellij/util/io/writeAheadLog.kt | 3877001725 |
// 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.tools.projectWizard.plugins.kotlin
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.service.*
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildFileIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.RepositoryIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.withIrs
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.ModuleConfigurator
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.buildSystemType
import org.jetbrains.kotlin.tools.projectWizard.plugins.pomIR
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.*
import java.nio.file.Path
class KotlinPlugin(context: Context) : Plugin(context) {
override val path = pluginPath
companion object : PluginSettingsOwner() {
override val pluginPath = "kotlin"
private val moduleDependenciesValidator = settingValidator<List<Module>> { modules ->
val allModules = modules.withAllSubModules(includeSourcesets = true).toSet()
val allModulePaths = allModules.map(Module::path).toSet()
allModules.flatMap { module ->
module.dependencies.map { dependency ->
val isValidModule = when (dependency) {
is ModuleReference.ByPath -> dependency.path in allModulePaths
is ModuleReference.ByModule -> dependency.module in allModules
}
ValidationResult.create(isValidModule) {
KotlinNewProjectWizardBundle.message(
"plugin.kotlin.setting.modules.error.duplicated.modules",
dependency,
module.path
)
}
}
}.fold()
}
val version by property(
// todo do not hardcode kind & repository
WizardKotlinVersion(
Versions.KOTLIN,
KotlinVersionKind.M,
Repositories.KOTLIN_EAP_MAVEN_CENTRAL,
KotlinVersionProviderService.getBuildSystemPluginRepository(
KotlinVersionKind.M,
devRepository = Repositories.JETBRAINS_KOTLIN_DEV
)
)
)
val initKotlinVersions by pipelineTask(GenerationPhase.PREPARE_GENERATION) {
title = KotlinNewProjectWizardBundle.message("plugin.kotlin.downloading.kotlin.versions")
withAction {
val version = service<KotlinVersionProviderService>().getKotlinVersion(projectKind.settingValue)
KotlinPlugin.version.update { version.asSuccess() }
}
}
val projectKind by enumSetting<ProjectKind>(
KotlinNewProjectWizardBundle.message("plugin.kotlin.setting.project.kind"),
GenerationPhase.FIRST_STEP,
)
private fun List<Module>.findDuplicatesByName() =
groupingBy { it.name }.eachCount().filter { it.value > 1 }
val modules by listSetting(
KotlinNewProjectWizardBundle.message("plugin.kotlin.setting.modules"),
GenerationPhase.SECOND_STEP,
Module.parser,
) {
validate { value ->
val allModules = value.withAllSubModules()
val duplicatedModules = allModules.findDuplicatesByName()
if (duplicatedModules.isEmpty()) ValidationResult.OK
else ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"plugin.kotlin.setting.modules.error.duplicated.modules",
duplicatedModules.values.first(),
duplicatedModules.keys.first()
)
)
}
validate { value ->
value.withAllSubModules().filter { it.kind == ModuleKind.multiplatform }.map { module ->
val duplicatedModules = module.subModules.findDuplicatesByName()
if (duplicatedModules.isEmpty()) ValidationResult.OK
else ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"plugin.kotlin.setting.modules.error.duplicated.targets",
duplicatedModules.values.first(),
duplicatedModules.keys.first()
)
)
}.fold()
}
validate(moduleDependenciesValidator)
}
val createModules by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(BuildSystemPlugin.createModules)
runAfter(StructurePlugin.createProjectDir)
withAction {
BuildSystemPlugin.buildFiles.update {
val modules = modules.settingValue
val (buildFiles) = createBuildFiles(modules)
buildFiles.map { it.withIrs(RepositoryIR(DefaultRepository.MAVEN_CENTRAL)) }.asSuccess()
}
}
}
val createPluginRepositories by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(BuildSystemPlugin.createModules)
withAction {
val version = version.propertyValue
if (version.kind.isStable) return@withAction UNIT_SUCCESS
val pluginRepository = version.buildSystemPluginRepository(buildSystemType) ?: return@withAction UNIT_SUCCESS
BuildSystemPlugin.pluginRepositoreis.addValues(pluginRepository) andThen
updateBuildFiles { buildFile ->
buildFile.withIrs(RepositoryIR(version.repository)).asSuccess()
}
}
}
val createResourceDirectories by booleanSetting("Generate Resource Folders", GenerationPhase.PROJECT_GENERATION) {
defaultValue = value(true)
}
val createSourcesetDirectories by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(createModules)
withAction {
fun Path?.createKotlinAndResourceDirectories(moduleConfigurator: ModuleConfigurator): TaskResult<Unit> {
if (this == null) return UNIT_SUCCESS
return with(service<FileSystemWizardService>()) {
createDirectory(this@createKotlinAndResourceDirectories / moduleConfigurator.kotlinDirectoryName) andThen
if (createResourceDirectories.settingValue) {
createDirectory(this@createKotlinAndResourceDirectories / moduleConfigurator.resourcesDirectoryName)
} else {
UNIT_SUCCESS
}
}
}
forEachModule { moduleIR ->
moduleIR.sourcesets.mapSequenceIgnore { sourcesetIR ->
sourcesetIR.path.createKotlinAndResourceDirectories(moduleIR.originalModule.configurator)
}
}
}
}
private fun Writer.createBuildFiles(modules: List<Module>): TaskResult<List<BuildFileIR>> =
with(
ModulesToIRsConverter(
ModulesToIrConversionData(
modules,
projectPath,
StructurePlugin.name.settingValue,
version.propertyValue,
buildSystemType,
pomIR()
)
)
) { createBuildFiles() }
}
override val settings: List<PluginSetting<*, *>> =
listOf(
projectKind,
modules,
createResourceDirectories,
)
override val pipelineTasks: List<PipelineTask> =
listOf(
initKotlinVersions,
createModules,
createPluginRepositories,
createSourcesetDirectories
)
override val properties: List<Property<*>> =
listOf(version)
}
enum class ProjectKind(
@Nls override val text: String,
val supportedBuildSystems: Set<BuildSystemType>,
val shortName: String = text,
val message: String? = null,
) : DisplayableSettingItem {
Singleplatform(
KotlinNewProjectWizardBundle.message("project.kind.singleplatform"),
supportedBuildSystems = BuildSystemType.values().toSet()
),
Multiplatform(KotlinNewProjectWizardBundle.message("project.kind.multiplatform"), supportedBuildSystems = BuildSystemType.ALL_GRADLE),
Android(KotlinNewProjectWizardBundle.message("project.kind.android"), supportedBuildSystems = BuildSystemType.ALL_GRADLE),
Js(KotlinNewProjectWizardBundle.message("project.kind.kotlin.js"), supportedBuildSystems = BuildSystemType.ALL_GRADLE),
COMPOSE(
KotlinNewProjectWizardBundle.message("project.kind.compose"),
supportedBuildSystems = setOf(BuildSystemType.GradleKotlinDsl),
shortName = KotlinNewProjectWizardBundle.message("project.kind.compose.short.name"),
message = "uses Kotlin ${Versions.KOTLIN_VERSION_FOR_COMPOSE}"
)
}
fun List<Module>.withAllSubModules(includeSourcesets: Boolean = false): List<Module> = buildList {
fun handleModule(module: Module) {
+module
if (module.kind != ModuleKind.multiplatform
|| includeSourcesets && module.kind == ModuleKind.multiplatform
) {
module.subModules.forEach(::handleModule)
}
}
forEach(::handleModule)
}
| plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/kotlin/KotlinPlugin.kt | 1278199963 |
package com.github.kerubistan.kerub.utils.junix.uname
import com.github.kerubistan.kerub.host.executeOrDie
import com.github.kerubistan.kerub.model.HostCapabilities
import com.github.kerubistan.kerub.utils.junix.common.OsCommand
import org.apache.sshd.client.session.ClientSession
object UName : OsCommand {
// any unix-like OS should have an uname
override fun available(hostCapabilities: HostCapabilities?): Boolean = true
fun kernelName(session: ClientSession) = session.executeOrDie("uname -s").trim()
fun machineType(session: ClientSession) = session.executeOrDie("uname -m").trim()
fun processorType(session: ClientSession) = session.executeOrDie("uname -p").trim()
fun kernelVersion(session: ClientSession) = session.executeOrDie("uname -r").trim()
fun operatingSystem(session: ClientSession) = session.executeOrDie("uname -o").trim()
} | src/main/kotlin/com/github/kerubistan/kerub/utils/junix/uname/UName.kt | 3069819560 |
// 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.
@file:JvmName("GroovyLValueUtil")
package org.jetbrains.plugins.groovy.lang.psi.util
import com.intellij.psi.PsiType
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets.POSTFIX_UNARY_OP_SET
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.api.UnknownArgument
/**
* The expression is a rValue when it is in rValue position or it's a lValue of operator assignment.
*/
fun GrExpression.isRValue(): Boolean {
val (parent, lastParent) = skipParentsOfType<GrParenthesizedExpression>() ?: return true
return parent !is GrAssignmentExpression || lastParent != parent.lValue || parent.isOperatorAssignment
}
/**
* The expression is a lValue when it's on the left of whatever assignment.
*/
fun GrExpression.isLValue(): Boolean {
return when (val parent = parent) {
is GrTuple -> true
is GrAssignmentExpression -> this == parent.lValue
is GrUnaryExpression -> parent.operationTokenType in POSTFIX_UNARY_OP_SET
else -> false
}
}
/**
* @return non-null result iff this expression is an l-value
*/
fun GrExpression.getRValue(): Argument? {
val parent = parent
return when {
parent is GrTuple -> UnknownArgument
parent is GrAssignmentExpression && parent.lValue === this -> {
if (parent.isOperatorAssignment) {
ExpressionArgument(parent)
}
else {
parent.rValue?.let(::ExpressionArgument) ?: UnknownArgument
}
}
parent is GrUnaryExpression && parent.operationTokenType in POSTFIX_UNARY_OP_SET -> IncDecArgument(parent)
else -> null
}
}
private data class IncDecArgument(private val unary: GrUnaryExpression) : Argument {
override val type: PsiType? get() = unary.operationType
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/lValueUtil.kt | 2576884257 |
// IS_APPLICABLE: false
// IGNORE_FE10
var foo: <caret>Any = 1 + 1 | plugins/kotlin/idea/tests/testData/intentions/removeExplicitType/constantExpressionInitializerVar.kt | 818495007 |
// COMPILER_ARGUMENTS: -XXLanguage:+SealedInterfaces -XXLanguage:+AllowSealedInheritorsInDifferentFilesOfSamePackage
package sealed.otherpackage
import sealed.SealedDeclarationInterface
import sealed.SealedDeclarationClass
class D: <error descr="[SEALED_INHERITOR_IN_DIFFERENT_PACKAGE] Inheritor of sealed class or interface declared in package sealed.otherpackage but it must be in package sealed where base class is declared">SealedDeclarationInterface</error>
class DClass: <error descr="[SEALED_INHERITOR_IN_DIFFERENT_PACKAGE] Inheritor of sealed class or interface declared in package sealed.otherpackage but it must be in package sealed where base class is declared">SealedDeclarationClass</error>()
| plugins/kotlin/idea/tests/testData/checker/sealed/SealedOutsidePackageInheritors.kt | 957216369 |
// WITH_STDLIB
// PROBLEM: none
import java.util.Arrays
fun test() {
val a: Array<*>? = arrayOf(1)
val str = Arrays.<caret>toString(a)
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/collections/toStringWithNullableReceiver.kt | 947587609 |
package noParameterLambdaArgumentCallInInline
fun main(args: Array<String>) {
lookAtMe {
val c = "c"
}
}
inline fun lookAtMe(f: String.() -> Unit) {
val a = "a"
//Breakpoint!
"123".f()
val b = "b"
} | plugins/kotlin/jvm-debugger/test/testData/stepping/stepOver/noParameterExtensionLambdaArgumentCallInInline.kt | 3638761997 |
/*
* Copyright 2021 Appmattus Limited
*
* 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.appmattus.layercache.samples.sharedprefs
import android.content.Context
import androidx.lifecycle.ViewModel
import com.appmattus.layercache.Cache
import com.appmattus.layercache.asStringCache
import com.appmattus.layercache.encrypt
import com.appmattus.layercache.get
import com.appmattus.layercache.samples.data.LastRetrievedWrapper
import com.appmattus.layercache.samples.data.network.KtorDataSource
import com.appmattus.layercache.samples.domain.PersonalDetails
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.serialization.json.Json.Default.decodeFromString
import kotlinx.serialization.json.Json.Default.encodeToString
import org.orbitmvi.orbit.Container
import org.orbitmvi.orbit.ContainerHost
import org.orbitmvi.orbit.syntax.simple.intent
import org.orbitmvi.orbit.syntax.simple.reduce
import org.orbitmvi.orbit.viewmodel.container
import javax.inject.Inject
@HiltViewModel
class SharedPrefsViewModel @Inject constructor(
@ApplicationContext context: Context
) : ViewModel(), ContainerHost<SharedPrefsState, Unit> {
// Stores the name of the cache data was returned from
private val lastRetrievedWrapper = LastRetrievedWrapper()
// Network fetcher, wrapped so we can detect when get returns a value
private val ktorDataSource: Cache<Unit, PersonalDetails> = with(lastRetrievedWrapper) { KtorDataSource().wrap("Ktor network call") }
// Encrypted shared preferences cache
private val sharedPreferences = context.getSharedPreferences("encrypted", Context.MODE_PRIVATE)
private val encryptedSharedPreferencesDataSource: Cache<Unit, PersonalDetails> = with(lastRetrievedWrapper) {
sharedPreferences
// Access as a Cache<String, String>
.asStringCache()
// Wrap the cache so we can detect when get returns a value
.wrap("Shared preferences")
// Encrypt all keys and values stored in this cache
.encrypt(context)
// We are only storing one value so using a default key and mapping externally to Unit, i.e. cache becomes Cache<Unit, String>
.keyTransform<Unit> {
"personalDetails"
}
// Transform string values to PersonalDetails, i.e. cache becomes Cache<Unit, PersonalDetails>
.valueTransform(transform = {
decodeFromString(PersonalDetails.serializer(), it)
}, inverseTransform = {
encodeToString(PersonalDetails.serializer(), it)
})
}
// Combine shared preferences and ktor caches, i.e. first retrieve value from shared preferences and if not available retrieve from network
private val repository = encryptedSharedPreferencesDataSource.compose(ktorDataSource)
override val container: Container<SharedPrefsState, Unit> = container(SharedPrefsState()) {
loadPreferencesContent()
}
// Update state with personal details retrieved from the repository
fun loadPersonalDetails() = intent {
lastRetrievedWrapper.reset()
reduce {
state.copy(personalDetails = null, loadedFrom = "")
}
val personalDetails = repository.get()
reduce {
state.copy(personalDetails = personalDetails, loadedFrom = lastRetrievedWrapper.lastRetrieved ?: "")
}
loadPreferencesContent()
}
// Update the state with the current contents of shared preferences so we can demonstrate that the data is stored encrypted
private fun loadPreferencesContent() = intent {
val content = sharedPreferences.all
reduce {
state.copy(preferences = content)
}
}
// Clear all data from shared preferences and the state object
fun clear() = intent {
reduce {
state.copy(personalDetails = null, loadedFrom = "")
}
sharedPreferences.edit().clear().apply()
loadPreferencesContent()
}
}
| samples/androidApp/src/main/kotlin/com/appmattus/layercache/samples/sharedprefs/SharedPrefsViewModel.kt | 1153521800 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl
import com.intellij.facet.ui.FacetDependentToolWindow
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ext.LibraryDependentToolWindow
import com.intellij.util.xmlb.Converter
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.Property
import com.intellij.util.xmlb.annotations.Tag
import com.intellij.util.xmlb.annotations.Transient
import java.awt.Rectangle
import kotlin.math.max
import kotlin.math.min
private val LOG = logger<WindowInfoImpl>()
@Suppress("EqualsOrHashCode")
@Tag("window_info")
@Property(style = Property.Style.ATTRIBUTE)
class WindowInfoImpl : Cloneable, WindowInfo, BaseState() {
companion object {
internal const val TAG = "window_info"
const val DEFAULT_WEIGHT = 0.33f
}
@get:Attribute("active")
override var isActiveOnStart by property(false)
@get:Attribute(converter = ToolWindowAnchorConverter::class)
override var anchor by property(ToolWindowAnchor.LEFT) { it == ToolWindowAnchor.LEFT }
@get:Attribute(converter = ToolWindowAnchorConverter::class)
override var largeStripeAnchor by property(ToolWindowAnchor.LEFT) { it == ToolWindowAnchor.LEFT }
@get:Attribute("auto_hide")
override var isAutoHide by property(false)
/**
* Bounds of window in "floating" mode. It equals to `null` if floating bounds are undefined.
*/
@get:Property(flat = true, style = Property.Style.ATTRIBUTE)
override var floatingBounds by property<Rectangle?>(null) { it == null || (it.width == 0 && it.height == 0 && it.x == 0 && it.y == 0) }
/**
* This attribute persists state 'maximized' for `ToolWindowType.WINDOWED` where decoration is presented by JFrame
*/
@get:Attribute("maximized")
override var isMaximized by property(false)
/**
* ID of the tool window
*/
override var id by string()
/**
* @return type of the tool window in internal (docked or sliding) mode. Actually the tool
* window can be in floating mode, but this method has sense if you want to know what type
* tool window had when it was internal one.
*/
@get:Attribute("internal_type")
override var internalType by enum(ToolWindowType.DOCKED)
override var type by enum(ToolWindowType.DOCKED)
@get:Attribute("visible")
override var isVisible by property(false)
@get:Attribute("show_stripe_button")
override var isShowStripeButton by property(true)
@get:Attribute("visibleOnLargeStripe")
override var isVisibleOnLargeStripe by property(false)
/**
* Internal weight of tool window. "weight" means how much of internal desktop
* area the tool window is occupied. The weight has sense if the tool window is docked or
* sliding.
*/
override var weight by property(DEFAULT_WEIGHT) { max(0f, min(1f, it)) }
override var sideWeight by property(0.5f) { max(0f, min(1f, it)) }
@get:Attribute("side_tool")
override var isSplit by property(false)
@get:Attribute("content_ui", converter = ContentUiTypeConverter::class)
override var contentUiType: ToolWindowContentUiType by property(ToolWindowContentUiType.TABBED) { it == ToolWindowContentUiType.TABBED }
/**
* Defines order of tool window button inside the stripe.
*/
override var order by property(-1)
@get:Attribute("orderOnLargeStripe")
override var orderOnLargeStripe by property(-1)
@get:Transient
override var isFromPersistentSettings = true
internal set
fun copy(): WindowInfoImpl {
val info = WindowInfoImpl()
info.copyFrom(this)
info.isFromPersistentSettings = isFromPersistentSettings
return info
}
override val isDocked: Boolean
get() = type == ToolWindowType.DOCKED
internal fun normalizeAfterRead() {
setTypeAndCheck(type)
if (isVisible && id != null && !canActivateOnStart(id!!)) {
isVisible = false
}
}
internal fun setType(type: ToolWindowType) {
if (ToolWindowType.DOCKED == type || ToolWindowType.SLIDING == type) {
internalType = type
}
setTypeAndCheck(type)
}
// hardcoded to avoid single-usage-API
private fun setTypeAndCheck(value: ToolWindowType) {
type = if (ToolWindowId.PREVIEW === id && value == ToolWindowType.DOCKED) ToolWindowType.SLIDING else value
}
override fun hashCode(): Int {
return anchor.hashCode() + id!!.hashCode() + type.hashCode() + order
}
override fun toString() = "id: $id, ${super.toString()}"
}
private class ContentUiTypeConverter : Converter<ToolWindowContentUiType>() {
override fun fromString(value: String): ToolWindowContentUiType = ToolWindowContentUiType.getInstance(value)
override fun toString(value: ToolWindowContentUiType): String = value.name
}
private class ToolWindowAnchorConverter : Converter<ToolWindowAnchor>() {
override fun fromString(value: String): ToolWindowAnchor {
try {
return ToolWindowAnchor.fromText(value)
}
catch (e: IllegalArgumentException) {
if (!value.equals("none", ignoreCase = true)) {
LOG.warn(e)
}
return ToolWindowAnchor.LEFT
}
}
override fun toString(value: ToolWindowAnchor) = value.toString()
}
private fun canActivateOnStart(id: String): Boolean {
val ep = findEp(ToolWindowEP.EP_NAME.iterable, id)
?: findEp(FacetDependentToolWindow.EXTENSION_POINT_NAME.iterable, id)
?: findEp(LibraryDependentToolWindow.EXTENSION_POINT_NAME.iterable, id)
return ep == null || !ep.isDoNotActivateOnStart
}
private fun findEp(list: Iterable<ToolWindowEP>, id: String): ToolWindowEP? {
return list.firstOrNull { id == it.id }
} | platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowInfoImpl.kt | 2508287582 |
// WITH_STDLIB
fun test(list: List<Int>) {
list.<caret>filter { it > 1 }.sumOf { it }
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/sumOf.kt | 487278482 |
// WITH_STDLIB
fun String.test(s: String): Boolean {
return <caret>s.toLowerCase() == toLowerCase()
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceWithIgnoreCaseEquals/extension2.kt | 1702080273 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.ui.command.line
import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionInfo
import com.intellij.openapi.util.NlsContexts
import org.jetbrains.annotations.Nls
import javax.swing.Icon
interface CompletionTableInfo {
val emptyState: @Nls String
val dataColumnIcon: Icon?
val dataColumnName: @NlsContexts.ColumnName String
val descriptionColumnIcon: Icon?
val descriptionColumnName: @NlsContexts.ColumnName String
val completionInfo: List<TextCompletionInfo>
val tableCompletionInfo: List<TextCompletionInfo>
} | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/command/line/CompletionTableInfo.kt | 774283994 |
package co.early.fore.kt.core.time
import co.early.fore.kt.core.delegate.Fore
import co.early.fore.kt.core.logging.Logger
import java.text.DecimalFormat
val nanosFormat = DecimalFormat("#,###")
/**
* invokes the function,
* returns the result,
* then logs the time taken in a standard format
*/
inline fun <T> measureNanos(logger: Logger? = null, function: () -> T): T {
return measureNanos({ nanos ->
Fore.getLogger(logger).i("operation took: ${nanosFormat.format(nanos)} ns " +
"thread:${Thread.currentThread().id}")
}) { function.invoke() }
}
/**
* invokes the function,
* invokes timeTaken with the time taken in ns to run the function,
* returns the result or the function
*/
inline fun <T> measureNanos(timeTaken: (Long) -> Unit, function: () -> T): T {
val decoratedResult = measureNanos(function)
timeTaken(decoratedResult.second)
return decoratedResult.first
}
/**
* invokes the function,
* returns a Pair(first = result of the function, second = time taken in ns)
*/
inline fun <T> measureNanos(function: () -> T): Pair<T, Long> {
val startTime = System.nanoTime()
val result: T = function.invoke()
return result to (System.nanoTime() - startTime)
}
| fore-kt-core/src/main/java/co/early/fore/kt/core/time/Time.kt | 1677552460 |
package net.coding.program.terminal
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_terminal.*
import net.coding.program.common.ui.BackActivity
class TerminalActivity : BackActivity() {
lateinit var fixationKeys: List<View>
lateinit var lastSelectRadio: View
var ctrlPressed = false
var altPressed = false
private val colorSelect = 0xFFBBC2CA.toInt()
private val colorNormal = 0xFFFFFFFF.toInt()
private val colorSelectExt = 0xFFA7B0BD.toInt()
var showLogin = false
val clickKeyButton = View.OnClickListener {
val tag = it.tag
if (tag is KeyItem) {
when (tag) {
KeyItem.CTRL -> {
ctrlPressed = !ctrlPressed
it.setBackgroundColor(if (ctrlPressed) colorNormal else colorSelect)
}
KeyItem.ALT -> {
altPressed = !altPressed
it.setBackgroundColor(if (altPressed) colorNormal else colorSelect)
}
KeyItem.ESC -> {
showLogin = !showLogin
if (showLogin) {
var url = "http://ide.xiayule.net"
url = "http://ide.xiayule.net"
loadUrl(url)
showMiddleToast("打开登录页面")
} else {
var url = "http://ide.test:8060"
url = "http://ide.test:8060 "
loadUrl(url)
showMiddleToast("打开Terminal")
}
}
else -> {
webView.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, tag.value))
webView.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, tag.value))
}
}
}
}
fun loadUrl(url: String) {
// url = "http://192.168.0.212:8060"
// url = "http://www.baidu.com"
// url = "http://ide.xiayule.net"
webView.settings.let {
it.javaScriptEnabled = true
it.domStorageEnabled = true
it.setAppCachePath(cacheDir.absolutePath)
it.allowFileAccess = true
it.setAppCacheEnabled(true)
it.cacheMode
}
webView.loadUrl(url)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_terminal)
maskView.setOnClickListener { showKeyExt(false) }
fixationKeys = listOf(keyEsc, keyCtrl, keyAlt, keyTab, keyMore)
val fixationItems = listOf(KeyItem.ESC, KeyItem.CTRL, KeyItem.ALT, KeyItem.TAB, KeyItem.MORE)
val action: (Pair<View, KeyItem>) -> Unit = {
val view = it.first
view.setTag(it.second)
if ((view is TextView)) {
view.setText(it.second.text)
} else if ((view is ImageView)) {
view.setImageResource(it.second.icon)
}
if (view == keyMore) {
view.setOnClickListener { showKeyExt(maskView.visibility != View.VISIBLE) }
} else {
view.setOnClickListener(clickKeyButton)
}
}
fixationKeys.zip(fixationItems).forEach(action)
initKeyExt()
initWebView()
edit.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
Logger.d("CKEY ww ");
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
Logger.d("CKEY ww ");
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
Logger.d("CKEY ww ");
}
})
}
private fun initWebView() {
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
if (view != null && url != null) {
loadUrl(url)
return true
}
return false
}
}
loadUrl("http://ide.test:8060")
}
private fun initKeyExt() {
val first = listOf(KeyItem.SLASH, KeyItem.MINUS, KeyItem.VER_LINE, KeyItem.AT)
val second = listOf(KeyItem.WAVY_LINE, KeyItem.POINT, KeyItem.COLON, KeyItem.SEMICOLON)
val third = listOf(KeyItem.UP, KeyItem.DOWN, KeyItem.LEFT, KeyItem.RIGHT)
val inflater = LayoutInflater.from(this)
listOf(first, second, third).forEach { lineIt ->
val lineLayout = LinearLayout(this)
layoutExt.addView(lineLayout)
val radioButton = inflater.inflate(R.layout.key_ext_image_item, lineLayout, false)
radioButton.setBackgroundResource(R.mipmap.key_radio_normal)
lastSelectRadio = radioButton
lineLayout.addView(radioButton)
val lineButtons = arrayListOf<View>()
lineIt.forEach {
val itemView = inflater.inflate(R.layout.key_ext_item, lineLayout, false) as TextView
itemView.setTag(it)
itemView.setOnClickListener(clickKeyButton)
itemView.text = it.text
lineLayout.addView(itemView)
lineButtons.add(itemView)
}
radioButton.tag = lineButtons
radioButton.setOnClickListener {
lastSelectRadio.radioSelect(false)
lastSelectRadio = it
lastSelectRadio.radioSelect(true)
}
}
lastSelectRadio.performClick()
maskView.performClick()
}
fun showKeyExt(show: Boolean) {
val visable = if (show) View.VISIBLE else View.GONE
maskView.visibility = visable
layoutExt.visibility = visable
}
override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
Logger.d("CKEY" + event)
return super.dispatchKeyEvent(event)
}
override fun dispatchKeyShortcutEvent(event: KeyEvent?): Boolean {
Logger.d("CKEY" + event)
return super.dispatchKeyShortcutEvent(event)
}
override fun dispatchGenericMotionEvent(ev: MotionEvent?): Boolean {
Logger.d("CKEY" + ev)
return super.dispatchGenericMotionEvent(ev)
}
override fun dispatchTrackballEvent(ev: MotionEvent?): Boolean {
Logger.d("CKEY" + ev)
return super.dispatchTrackballEvent(ev)
}
fun View.radioSelect(select: Boolean) {
val radioBg = if (select) R.mipmap.key_radio_select else R.mipmap.key_radio_normal
val keyBg = if (select) colorSelectExt else colorNormal
this.setBackgroundResource(radioBg)
val tag = this.tag
if (tag is ArrayList<*>) {
layoutSwitch.removeAllViews()
val inflater = LayoutInflater.from(context)
tag.forEach {
if (it is View) {
it.setBackgroundColor(keyBg)
val keyItem = it.tag
if (keyItem is KeyItem) {
val button = inflater.inflate(R.layout.key_item_text, layoutSwitch, false)
button.setTag(keyItem)
if (button is TextView) {
button.setText(keyItem.text)
}
layoutSwitch.addView(button)
button.setOnClickListener(clickKeyButton)
}
}
}
}
}
}
| terminal-coding/src/main/java/net/coding/program/terminal/TerminalActivity.kt | 265488740 |
package ch.rmy.android.http_shortcuts.data.enums
enum class CategoryLayoutType(
val type: String,
val supportsHorizontalDragging: Boolean = false,
val legacyAlias: String? = null,
) {
LINEAR_LIST("linear_list"),
DENSE_GRID("dense_grid", supportsHorizontalDragging = true, legacyAlias = "grid"),
MEDIUM_GRID("medium_grid", supportsHorizontalDragging = true),
WIDE_GRID("wide_grid", supportsHorizontalDragging = true);
override fun toString() =
type
companion object {
fun parse(type: String?) =
values().firstOrNull { it.type == type || (it.legacyAlias != null && it.legacyAlias == type) }
?: LINEAR_LIST
}
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/enums/CategoryLayoutType.kt | 1461751862 |
// GENERATED
package com.fkorotkov.kubernetes
import io.fabric8.kubernetes.api.model.PersistentVolumeClaimVolumeSource as model_PersistentVolumeClaimVolumeSource
import io.fabric8.kubernetes.api.model.Volume as model_Volume
fun model_Volume.`persistentVolumeClaim`(block: model_PersistentVolumeClaimVolumeSource.() -> Unit = {}) {
if(this.`persistentVolumeClaim` == null) {
this.`persistentVolumeClaim` = model_PersistentVolumeClaimVolumeSource()
}
this.`persistentVolumeClaim`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/persistentVolumeClaim.kt | 734693886 |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.daemon.impl.quickfix
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil
abstract class AddModuleDirectiveFix(module: PsiJavaModule) : LocalQuickFixAndIntentionActionOnPsiElement(module) {
override fun getFamilyName() = QuickFixBundle.message("module.info.add.directive.family.name")
override fun isAvailable(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) =
startElement is PsiJavaModule && PsiUtil.isLanguageLevel9OrHigher(file) && startElement.getManager().isInProject(startElement)
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) =
invoke(project, file, editor, startElement as PsiJavaModule)
protected abstract fun invoke(project: Project, file: PsiFile, editor: Editor?, module: PsiJavaModule)
}
class AddRequiresDirectiveFix(module: PsiJavaModule, private val requiredName: String) : AddModuleDirectiveFix(module) {
override fun getText() = QuickFixBundle.message("module.info.add.requires.name", requiredName)
override fun invoke(project: Project, file: PsiFile, editor: Editor?, module: PsiJavaModule) {
if (module.requires.find { requiredName == it.moduleName } == null) {
PsiUtil.addModuleStatement(module, PsiKeyword.REQUIRES + ' ' + requiredName)
}
}
}
class AddExportsDirectiveFix(module: PsiJavaModule,
private val packageName: String,
private val targetName: String) : AddModuleDirectiveFix(module) {
override fun getText() = QuickFixBundle.message("module.info.add.exports.name", packageName)
override fun invoke(project: Project, file: PsiFile, editor: Editor?, module: PsiJavaModule) {
val existing = module.exports.find { packageName == it.packageName }
if (existing == null) {
PsiUtil.addModuleStatement(module, PsiKeyword.EXPORTS + ' ' + packageName)
}
else if (!targetName.isEmpty()) {
val targets = existing.moduleReferences.map { it.referenceText }
if (!targets.isEmpty() && targetName !in targets) {
existing.add(PsiElementFactory.SERVICE.getInstance(project).createModuleReferenceFromText(targetName))
}
}
}
}
class AddUsesDirectiveFix(module: PsiJavaModule, private val svcName: String) : AddModuleDirectiveFix(module) {
override fun getText() = QuickFixBundle.message("module.info.add.uses.name", svcName)
override fun invoke(project: Project, file: PsiFile, editor: Editor?, module: PsiJavaModule) {
if (module.uses.find { svcName == it.classReference?.qualifiedName } == null) {
PsiUtil.addModuleStatement(module, PsiKeyword.USES + ' ' + svcName)
}
}
} | java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddModuleDirectiveFix.kt | 1517910980 |
package com.github.jameshnsears.brexitsoundboard.espresso
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.pressBack
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.matcher.ViewMatchers.withContentDescription
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import androidx.test.rule.ActivityTestRule
import com.github.jameshnsears.brexitsoundboard.ActivityBrexitSoundboard
import com.github.jameshnsears.brexitsoundboard.R
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4ClassRunner::class)
class DavidTest {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(ActivityBrexitSoundboard::class.java)
@Test
fun davidTest() {
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
Thread.sleep(1000)
val appCompatImageButton = onView(
allOf(
withId(R.id.imageButtonDavid00),
withContentDescription("David Davis"),
childAtPosition(
childAtPosition(
withId(R.id.linearLayout),
3
),
0
)
)
)
appCompatImageButton.perform(scrollTo(), click())
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
Thread.sleep(1000)
pressBack()
}
private fun childAtPosition(
parentMatcher: Matcher<View>,
position: Int
): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent) &&
view == parent.getChildAt(position)
}
}
}
}
| app/src/androidTest/java/com/github/jameshnsears/brexitsoundboard/espresso/DavidTest.kt | 2774681598 |
package com.excref.kotblog.blog.api.facade.greeting.impl
import com.excref.kotblog.blog.api.facade.greeting.GreetingFacade
import com.excref.kotblog.blog.api.model.common.ResultResponse
import com.excref.kotblog.blog.api.model.greeting.request.GreetingRequest
import com.excref.kotblog.blog.api.model.greeting.response.GreetingResponse
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
/**
* @author Arthur Asatryan
* @since 6/15/17 12:23 AM
*/
@Component
class GreetingFacadeImpl : GreetingFacade {
//region Public methods
override fun greet(request: GreetingRequest): ResultResponse<GreetingResponse> {
logger.debug("Got greeting request - $request")
val name = request.name
logger.debug("Greeting to - $name")
return ResultResponse(GreetingResponse("Hello, $name!"))
}
//endregion
//region Companion object
companion object {
private val logger = LoggerFactory.getLogger(GreetingFacadeImpl::class.java)
}
//endregion
} | blog/api/facade/src/main/kotlin/com/excref/kotblog/blog/api/facade/greeting/impl/GreetingFacadeImpl.kt | 1474977883 |
package com.sksamuel.kotest.runner.junit5
import io.kotest.core.sourceRef
import io.kotest.core.spec.style.FunSpec
import io.kotest.core.spec.toDescription
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestResult
import io.kotest.core.test.TestType
import io.kotest.engine.toTestResult
import io.kotest.matchers.shouldBe
import io.kotest.runner.junit.platform.JUnitTestEngineListener
import io.kotest.runner.junit.platform.KotestEngineDescriptor
import org.junit.platform.engine.EngineExecutionListener
import org.junit.platform.engine.TestDescriptor
import org.junit.platform.engine.TestExecutionResult
import org.junit.platform.engine.UniqueId
import org.junit.platform.engine.reporting.ReportEntry
class JUnitTestRunnerListenerTests : FunSpec({
test("a bad test should fail test but not parent or spec") {
val root = KotestEngineDescriptor(
UniqueId.forEngine("kotest"),
emptyList(),
emptyList(),
emptyList(),
null,
)
val finished = mutableMapOf<String, TestExecutionResult.Status>()
val engineListener = object : EngineExecutionListener {
override fun executionFinished(testDescriptor: TestDescriptor, testExecutionResult: TestExecutionResult) {
finished[testDescriptor.displayName] = testExecutionResult.status
}
override fun reportingEntryPublished(testDescriptor: TestDescriptor?, entry: ReportEntry?) {}
override fun executionSkipped(testDescriptor: TestDescriptor?, reason: String?) {}
override fun executionStarted(testDescriptor: TestDescriptor?) {}
override fun dynamicTestRegistered(testDescriptor: TestDescriptor?) {}
}
val test1 = TestCase(
JUnitTestRunnerListenerTests::class.toDescription().appendTest("test1"),
JUnitTestRunnerListenerTests(),
{ },
sourceRef(),
TestType.Container,
parent = null,
)
val test2 = TestCase(
test1.description.appendTest("test2"),
JUnitTestRunnerListenerTests(),
{ },
sourceRef(),
TestType.Container,
parent = null,
)
val listener = JUnitTestEngineListener(engineListener, root)
listener.engineStarted(emptyList())
listener.specStarted(JUnitTestRunnerListenerTests::class)
listener.testStarted(test1)
listener.testStarted(test2)
listener.testFinished(test2, toTestResult(AssertionError("boom"), 0))
listener.testFinished(test1, TestResult.success(0))
listener.specFinished(JUnitTestRunnerListenerTests::class, null, emptyMap())
listener.engineFinished(emptyList())
finished.toMap() shouldBe mapOf(
"test2" to TestExecutionResult.Status.FAILED,
"test1" to TestExecutionResult.Status.SUCCESSFUL,
"com.sksamuel.kotest.runner.junit5.JUnitTestRunnerListenerTests" to TestExecutionResult.Status.SUCCESSFUL,
"Kotest" to TestExecutionResult.Status.SUCCESSFUL
)
}
})
| kotest-runner/kotest-runner-junit5/src/jvmTest/kotlin/com/sksamuel/kotest/runner/junit5/JUnitTestRunnerListenerTest.kt | 4023723515 |
/*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.docs.features.externalconfig.typesafeconfigurationproperties.mergingcomplextypes.list
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties("my")
class MyProperties {
val list: List<MyPojo> = ArrayList()
} | spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/mergingcomplextypes/list/MyProperties.kt | 1728318052 |
package exercises
fun sumAllParameters (vararg values: Int) = values.sum()
fun <T> sumAllGenericParameters (vararg values: T) : Double {
var soma: Double = 0.0
for (value in values) {
if (value is Int) {
soma += value
} else if (value is Double) {
soma += value
}
}
return soma + 0.01
} | Curso Dev Kotlin/src/exercises/manyParameters.kt | 4235824227 |
/*
* Copyright 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 androidx.room.solver.query.result
import androidx.room.ext.L
import androidx.room.ext.PagingTypeNames
import androidx.room.ext.typeName
import androidx.room.solver.CodeGenScope
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeSpec
import javax.lang.model.element.Modifier
class DataSourceFactoryQueryResultBinder(
val positionalDataSourceQueryResultBinder: PositionalDataSourceQueryResultBinder)
: QueryResultBinder(positionalDataSourceQueryResultBinder.listAdapter) {
@Suppress("HasPlatformType")
val typeName = positionalDataSourceQueryResultBinder.itemTypeName
override fun convertAndReturn(
roomSQLiteQueryVar: String,
canReleaseQuery: Boolean,
dbField: FieldSpec,
inTransaction: Boolean,
scope: CodeGenScope
) {
scope.builder().apply {
val pagedListProvider = TypeSpec
.anonymousClassBuilder("").apply {
superclass(ParameterizedTypeName.get(PagingTypeNames.DATA_SOURCE_FACTORY,
Integer::class.typeName(), typeName))
addMethod(createCreateMethod(
roomSQLiteQueryVar = roomSQLiteQueryVar,
dbField = dbField,
inTransaction = inTransaction,
scope = scope))
}.build()
addStatement("return $L", pagedListProvider)
}
}
private fun createCreateMethod(
roomSQLiteQueryVar: String,
dbField: FieldSpec,
inTransaction: Boolean,
scope: CodeGenScope
): MethodSpec = MethodSpec.methodBuilder("create").apply {
addAnnotation(Override::class.java)
addModifiers(Modifier.PUBLIC)
returns(positionalDataSourceQueryResultBinder.typeName)
val countedBinderScope = scope.fork()
positionalDataSourceQueryResultBinder.convertAndReturn(
roomSQLiteQueryVar = roomSQLiteQueryVar,
canReleaseQuery = true,
dbField = dbField,
inTransaction = inTransaction,
scope = countedBinderScope)
addCode(countedBinderScope.builder().build())
}.build()
}
| room/compiler/src/main/kotlin/androidx/room/solver/query/result/DataSourceFactoryQueryResultBinder.kt | 3422347216 |
package com.jtransc.gen.js
import com.jtransc.ConfigOutputFile
import com.jtransc.ConfigTargetDirectory
import com.jtransc.annotation.JTranscCustomMainList
import com.jtransc.ast.*
import com.jtransc.ast.feature.method.SwitchFeature
import com.jtransc.ds.Allocator
import com.jtransc.ds.getOrPut2
import com.jtransc.error.invalidOp
import com.jtransc.gen.GenTargetDescriptor
import com.jtransc.gen.TargetBuildTarget
import com.jtransc.gen.common.*
import com.jtransc.injector.Injector
import com.jtransc.injector.Singleton
import com.jtransc.io.ProcessResult2
import com.jtransc.log.log
import com.jtransc.sourcemaps.Sourcemaps
import com.jtransc.text.Indenter
import com.jtransc.text.Indenter.Companion
import com.jtransc.text.isLetterDigitOrUnderscore
import com.jtransc.text.quote
import com.jtransc.vfs.ExecOptions
import com.jtransc.vfs.LocalVfs
import com.jtransc.vfs.LocalVfsEnsureDirs
import com.jtransc.vfs.SyncVfsFile
import java.io.File
import java.util.*
class JsTarget() : GenTargetDescriptor() {
override val priority = 500
override val name = "js"
override val longName = "Javascript"
override val outputExtension = "js"
override val extraLibraries = listOf<String>()
override val extraClasses = listOf<String>()
override val runningAvailable: Boolean = true
override val buildTargets: List<TargetBuildTarget> = listOf(
TargetBuildTarget("js", "js", "program.js", minimizeNames = true),
TargetBuildTarget("plainJs", "js", "program.js", minimizeNames = true)
)
override fun getGenerator(injector: Injector): CommonGenerator {
val settings = injector.get<AstBuildSettings>()
val configTargetDirectory = injector.get<ConfigTargetDirectory>()
val configOutputFile = injector.get<ConfigOutputFile>()
val targetFolder = LocalVfsEnsureDirs(File("${configTargetDirectory.targetDirectory}/jtransc-js"))
injector.mapInstance(CommonGenFolders(settings.assets.map { LocalVfs(it) }))
injector.mapInstance(ConfigTargetFolder(targetFolder))
injector.mapInstance(ConfigSrcFolder(targetFolder))
injector.mapInstance(ConfigOutputFile2(targetFolder[configOutputFile.outputFileBaseName].realfile))
injector.mapImpl<IProgramTemplate, IProgramTemplate>()
return injector.get<JsGenerator>()
}
override fun getTargetByExtension(ext: String): String? = when (ext) {
"js" -> "js"
else -> null
}
}
data class ConfigJavascriptOutput(val javascriptOutput: SyncVfsFile)
fun hasSpecialChars(name: String): Boolean = !name.all(Char::isLetterDigitOrUnderscore)
@Suppress("ConvertLambdaToReference")
@Singleton
class JsGenerator(injector: Injector) : CommonGenerator(injector) {
override val SINGLE_FILE: Boolean = true
override val ADD_UTF8_BOM = true
override val GENERATE_LINE_NUMBERS = false
override val methodFeatures = super.methodFeatures + setOf(SwitchFeature::class.java)
override val keywords = super.keywords + setOf("name", "constructor", "prototype", "__proto__", "G", "N", "S", "SS", "IO")
override val stringPoolType = StringPool.Type.GLOBAL
override val floatHasFSuffix: Boolean = false
override fun compileAndRun(redirect: Boolean): ProcessResult2 = _compileRun(run = true, redirect = redirect)
override fun compile(): ProcessResult2 = _compileRun(run = false, redirect = false)
private fun commonAccess(name: String, field: Boolean): String = if (hasSpecialChars(name)) "[${name.quote()}]" else ".$name"
override fun staticAccess(name: String, field: Boolean): String = commonAccess(name, field)
override fun instanceAccess(name: String, field: Boolean): String = commonAccess(name, field)
val jsOutputFile by lazy { injector.get<ConfigJavascriptOutput>().javascriptOutput }
fun _compileRun(run: Boolean, redirect: Boolean): ProcessResult2 {
log.info("Generated javascript at..." + jsOutputFile.realpathOS)
if (run) {
val result = CommonGenCliCommands.runProgramCmd(
program,
target = "js",
default = listOf("node", "{{ outputFile }}"),
template = this,
options = ExecOptions(passthru = redirect)
)
return ProcessResult2(result)
} else {
return ProcessResult2(0)
}
}
override fun run(redirect: Boolean): ProcessResult2 = ProcessResult2(0)
@Suppress("UNCHECKED_CAST")
override fun writeClasses(output: SyncVfsFile) {
val concatFilesTrans = copyFiles(output)
val classesIndenter = arrayListOf<Indenter>()
classesIndenter += genSingleFileClassesWithoutAppends(output)
val SHOW_SIZE_REPORT = true
if (SHOW_SIZE_REPORT) {
for ((clazz, text) in indenterPerClass.toList().map { it.first to it.second.toString() }.sortedBy { it.second.length }) {
log.info("CLASS SIZE: ${clazz.fqname} : ${text.length}")
}
}
val mainClassFq = program.entrypoint
val mainClass = mainClassFq.targetClassFqName
//val mainMethod = program[mainClassFq].getMethod("main", AstType.build { METHOD(VOID, ARRAY(STRING)) }.desc)!!.jsName
val mainMethod = "main"
entryPointClass = FqName(mainClassFq.fqname + "_EntryPoint")
entryPointFilePath = entryPointClass.targetFilePath
val entryPointFqName = entryPointClass.targetGeneratedFqName
val entryPointSimpleName = entryPointClass.targetSimpleName
val entryPointPackage = entryPointFqName.packagePath
val customMain = program.allAnnotationsList.getTypedList(JTranscCustomMainList::value).firstOrNull { it.target == "js" }?.value
log("Using ... " + if (customMain != null) "customMain" else "plainMain")
setExtraData(mapOf(
"entryPointPackage" to entryPointPackage,
"entryPointSimpleName" to entryPointSimpleName,
"mainClass" to mainClass,
"mainClass2" to mainClassFq.fqname,
"mainMethod" to mainMethod
))
val strs = Indenter {
val strs = getGlobalStrings()
val maxId = strs.maxBy { it.id }?.id ?: 0
line("SS = new Array($maxId);")
for (e in strs) line("SS[${e.id}] = ${e.str.quote()};")
}
val out = Indenter {
if (settings.debug) line("//# sourceMappingURL=$outputFileBaseName.map")
line(concatFilesTrans.prepend)
line(strs.toString())
for (indent in classesIndenter) line(indent)
val mainClassClass = program[mainClassFq]
line("__createJavaArrays();")
line("__buildStrings();")
line("N.linit();")
line(genStaticConstructorsSorted())
//line(buildStaticInit(mainClassFq))
val mainMethod2 = mainClassClass[AstMethodRef(mainClassFq, "main", AstType.METHOD(AstType.VOID, listOf(ARRAY(AstType.STRING))))]
val mainCall = buildMethod(mainMethod2, static = true)
line("try {")
indent {
line("$mainCall(N.strArray(N.args()));")
}
line("} catch (e) {")
indent {
line("console.error(e);")
line("console.error(e.stack);")
}
line("}")
line(concatFilesTrans.append)
}
val sources = Allocator<String>()
val mappings = hashMapOf<Int, Sourcemaps.MappingItem>()
val source = out.toString { sb, line, data ->
if (settings.debug && data is AstStm.LINE) {
//println("MARKER: ${sb.length}, $line, $data, ${clazz.source}")
mappings[line] = Sourcemaps.MappingItem(
sourceIndex = sources.allocateOnce(data.file),
sourceLine = data.line,
sourceColumn = 0,
targetColumn = 0
)
//clazzName.internalFqname + ".java"
}
}
val sourceMap = if (settings.debug) Sourcemaps.encodeFile(sources.array, mappings) else null
// Generate source
//println("outputFileBaseName:$outputFileBaseName")
output[outputFileBaseName] = byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) + source.toByteArray(Charsets.UTF_8)
if (sourceMap != null) output[outputFileBaseName + ".map"] = sourceMap
injector.mapInstance(ConfigJavascriptOutput(output[outputFile]))
}
override fun genStmTryCatch(stm: AstStm.TRY_CATCH) = indent {
line("try") {
line(stm.trystm.genStm())
}
line("catch (J__i__exception__)") {
//line("J__exception__ = J__i__exception__.native || J__i__exception__;")
line("J__exception__ = J__i__exception__.javaThrowable || J__i__exception__;")
line(stm.catch.genStm())
}
}
override fun genStmRethrow(stm: AstStm.RETHROW, last: Boolean) = indent { line("throw J__i__exception__;") }
override fun genBodyLocals(locals: List<AstLocal>) = indent {
if (locals.isNotEmpty()) {
val vars = locals.map { local -> "${local.targetName} = ${local.type.nativeDefaultString}" }.joinToString(", ")
line("var $vars;")
}
}
override val AstLocal.decl: String get() = "var ${this.targetName} = ${this.type.nativeDefaultString};"
override fun genBodyTrapsPrefix() = indent { line("var J__exception__ = null;") }
override fun genBodyStaticInitPrefix(clazzRef: AstType.REF, reasons: ArrayList<String>) = indent {
line(buildStaticInit(clazzRef.name))
}
override fun N_AGET_T(arrayType: AstType.ARRAY, elementType: AstType, array: String, index: String) = "($array.data[$index])"
override fun N_ASET_T(arrayType: AstType.ARRAY, elementType: AstType, array: String, index: String, value: String) = "$array.data[$index] = $value;"
override fun N_is(a: String, b: AstType.Reference): String {
return when (b) {
is AstType.REF -> {
val clazz = program[b]!!
if (clazz.isInterface) {
"N.isClassId($a, ${clazz.classId})"
} else {
"($a instanceof ${b.targetName})"
}
}
else -> {
super.N_is(a, b)
}
}
}
override fun N_is(a: String, b: String) = "N.is($a, $b)"
override fun N_z2i(str: String) = "N.z2i($str)"
override fun N_i(str: String) = "(($str)|0)"
override fun N_i2z(str: String) = "(($str)!=0)"
override fun N_i2b(str: String) = "(($str)<<24>>24)" // shifts use 32-bit integers
override fun N_i2c(str: String) = "(($str)&0xFFFF)"
override fun N_i2s(str: String) = "(($str)<<16>>16)" // shifts use 32-bit integers
override fun N_f2i(str: String) = "(($str)|0)"
override fun N_i2i(str: String) = N_i(str)
override fun N_i2j(str: String) = "N.i2j($str)"
override fun N_i2f(str: String) = "Math.fround(+($str))"
override fun N_i2d(str: String) = "+($str)"
override fun N_f2f(str: String) = "Math.fround($str)"
override fun N_f2d(str: String) = "($str)"
override fun N_d2f(str: String) = "Math.fround(+($str))"
override fun N_d2i(str: String) = "(($str)|0)"
override fun N_d2d(str: String) = "+($str)"
override fun N_j2i(str: String) = "N.j2i($str)"
override fun N_j2j(str: String) = str
override fun N_j2f(str: String) = "Math.fround(N.j2d($str))"
override fun N_j2d(str: String) = "N.j2d($str)"
override fun N_getFunction(str: String) = "N.getFunction($str)"
override fun N_c(str: String, from: AstType, to: AstType) = "($str)"
override fun N_ineg(str: String) = "-($str)"
override fun N_iinv(str: String) = "~($str)"
override fun N_fneg(str: String) = "-($str)"
override fun N_dneg(str: String) = "-($str)"
override fun N_znot(str: String) = "!($str)"
override fun N_imul(l: String, r: String): String = "Math.imul($l, $r)"
override val String.escapeString: String get() = "S[" + allocString(context.clazz.name, this) + "]"
override fun genExprCallBaseSuper(e2: AstExpr.CALL_SUPER, clazz: AstType.REF, refMethodClass: AstClass, method: AstMethodRef, methodAccess: String, args: List<String>): String {
val superMethod = refMethodClass[method.withoutClass] ?: invalidOp("Can't find super for method : $method")
val base = superMethod.containingClass.name.targetName + ".prototype"
val argsString = (listOf(e2.obj.genExpr()) + args).joinToString(", ")
return "$base$methodAccess.call($argsString)"
}
private fun AstMethod.getJsNativeBodies(): Map<String, Indenter> = this.getNativeBodies(target = "js")
override fun genClass(clazz: AstClass): List<ClassResult> {
setCurrentClass(clazz)
val isAbstract = (clazz.classType == AstClassType.ABSTRACT)
refs._usedDependencies.clear()
if (!clazz.extending?.fqname.isNullOrEmpty()) refs.add(AstType.REF(clazz.extending!!))
for (impl in clazz.implementing) refs.add(AstType.REF(impl))
val classCodeIndenter = Indenter {
if (isAbstract) line("// ABSTRACT")
val classBase = clazz.name.targetName
val memberBaseStatic = classBase
val memberBaseInstance = "$classBase.prototype"
fun getMemberBase(isStatic: Boolean) = if (isStatic) memberBaseStatic else memberBaseInstance
val parentClassBase = if (clazz.extending != null) clazz.extending!!.targetName else "java_lang_Object_base";
val staticFields = clazz.fields.filter { it.isStatic }
//val instanceFields = clazz.fields.filter { !it.isStatic }
val allInstanceFields = (listOf(clazz) + clazz.parentClassList).flatMap { it.fields }.filter { !it.isStatic }
fun lateInitField(a: Any?) = (a is String)
val allInstanceFieldsThis = allInstanceFields.filter { lateInitField(it) }
val allInstanceFieldsProto = allInstanceFields.filter { !lateInitField(it) }
line("function $classBase()") {
for (field in allInstanceFieldsThis) {
val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName
line("this${instanceAccess(nativeMemberName, field = true)} = ${field.escapedConstantValue};")
}
}
line("$classBase.prototype = Object.create($parentClassBase.prototype);")
line("$classBase.prototype.constructor = $classBase;")
for (field in allInstanceFieldsProto) {
val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName
line("$classBase.prototype${instanceAccess(nativeMemberName, field = true)} = ${field.escapedConstantValue};")
}
// @TODO: Move to genSIMethodBody
//if (staticFields.isNotEmpty() || clazz.staticConstructor != null) {
// line("$classBase.SI = function()", after2 = ";") {
// line("$classBase.SI = N.EMPTY_FUNCTION;")
// for (field in staticFields) {
// val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName
// line("${getMemberBase(field.isStatic)}${accessStr(nativeMemberName)} = ${field.escapedConstantValue};")
// }
// if (clazz.staticConstructor != null) {
// line("$classBase${getTargetMethodAccess(clazz.staticConstructor!!, true)}();")
// }
// }
//} else {
// line("$classBase.SI = N.EMPTY_FUNCTION;")
//}
//line("$classBase.SI = N.EMPTY_FUNCTION;")
if (staticFields.isNotEmpty() || clazz.staticConstructor != null) {
line("$classBase.SI = function()", after2 = ";") {
//line("$classBase.SI = N.EMPTY_FUNCTION;")
for (field in staticFields) {
val nativeMemberName = if (field.targetName == field.name) field.name else field.targetName
line("${getMemberBase(field.isStatic)}${instanceAccess(nativeMemberName, field = true)} = ${field.escapedConstantValue};")
}
if (clazz.staticConstructor != null) {
line("$classBase${getTargetMethodAccess(clazz.staticConstructor!!, true)}();")
}
}
} else {
line("$classBase.SI = function(){};")
}
val relatedTypesIds = (clazz.getAllRelatedTypes() + listOf(JAVA_LANG_OBJECT_CLASS)).toSet().map { it.classId }
line("$classBase.prototype.__JT__CLASS_ID = $classBase.__JT__CLASS_ID = ${clazz.classId};")
line("$classBase.prototype.__JT__CLASS_IDS = $classBase.__JT__CLASS_IDS = [${relatedTypesIds.joinToString(",")}];")
//renderFields(clazz.fields);
fun writeMethod(method: AstMethod): Indenter {
setCurrentMethod(method)
return Indenter {
refs.add(method.methodType)
val margs = method.methodType.args.map { it.name }
//val defaultMethodName = if (method.isInstanceInit) "${method.ref.classRef.fqname}${method.name}${method.desc}" else "${method.name}${method.desc}"
//val methodName = if (method.targetName == defaultMethodName) null else method.targetName
val nativeMemberName = buildMethod(method, false, includeDot = false)
val prefix = "${getMemberBase(method.isStatic)}${instanceAccess(nativeMemberName, field = false)}"
val rbody = if (method.body != null) method.body else if (method.bodyRef != null) program[method.bodyRef!!]?.body else null
fun renderBranch(actualBody: Indenter?) = Indenter {
if (actualBody != null) {
line("$prefix = function(${margs.joinToString(", ")})", after2 = ";") {
line(actualBody)
if (method.methodVoidReturnThis) line("return this;")
}
} else {
line("$prefix = function() { N.methodWithoutBody('${clazz.name}.${method.name}') };")
}
}
fun renderBranches() = Indenter {
try {
val nativeBodies = method.getJsNativeBodies()
var javaBodyCacheDone: Boolean = false
var javaBodyCache: Indenter? = null
fun javaBody(): Indenter? {
if (!javaBodyCacheDone) {
javaBodyCacheDone = true
javaBodyCache = rbody?.genBodyWithFeatures(method)
}
return javaBodyCache
}
//val javaBody by lazy { }
// @TODO: Do not hardcode this!
if (nativeBodies.isEmpty() && javaBody() == null) {
line(renderBranch(null))
} else {
if (nativeBodies.isNotEmpty()) {
val default = if ("" in nativeBodies) nativeBodies[""]!! else javaBody() ?: Indenter.EMPTY
val options = nativeBodies.filter { it.key != "" }.map { it.key to it.value } + listOf("" to default)
if (options.size == 1) {
line(renderBranch(default))
} else {
for (opt in options.withIndex()) {
if (opt.index != options.size - 1) {
val iftype = if (opt.index == 0) "if" else "else if"
line("$iftype (${opt.value.first})") { line(renderBranch(opt.value.second)) }
} else {
line("else") { line(renderBranch(opt.value.second)) }
}
}
}
//line(nativeBodies ?: javaBody ?: Indenter.EMPTY)
} else {
line(renderBranch(javaBody()))
}
}
} catch (e: Throwable) {
log.printStackTrace(e)
log.warn("WARNING GenJsGen.writeMethod:" + e.message)
line("// Errored method: ${clazz.name}.${method.name} :: ${method.desc} :: ${e.message};")
line(renderBranch(null))
}
}
line(renderBranches())
}
}
for (method in clazz.methods.filter { it.isClassOrInstanceInit }) line(writeMethod(method))
for (method in clazz.methods.filter { !it.isClassOrInstanceInit }) line(writeMethod(method))
}
return listOf(ClassResult(SubClass(clazz, MemberTypes.ALL), classCodeIndenter))
}
override fun genStmSetArrayLiterals(stm: AstStm.SET_ARRAY_LITERALS) = Indenter {
line("${stm.array.genExpr()}.setArraySlice(${stm.startIndex}, [${stm.values.map { it.genExpr() }.joinToString(", ")}]);")
}
override fun buildStaticInit(clazzName: FqName): String? = null
override val FqName.targetName: String get() = classNames.getOrPut2(this) { if (minimize) allocClassName() else this.fqname.replace('.', '_') }
override fun cleanMethodName(name: String): String = name
override val AstType.localDeclType: String get() = "var"
override fun genStmThrow(stm: AstStm.THROW, last: Boolean) = Indenter("throw new WrappedError(${stm.exception.genExpr()});")
override fun genExprCastChecked(e: String, from: AstType.Reference, to: AstType.Reference): String {
return "N.checkCast($e, ${to.targetNameRef})"
}
} | jtransc-gen-js/src/com/jtransc/gen/js/JsTarget.kt | 1562626014 |
package com.jaynewstrom.jsonDelight.runtime.internal
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.jaynewstrom.jsonDelight.runtime.JsonDeserializer
import com.jaynewstrom.jsonDelight.runtime.JsonDeserializerFactory
import com.jaynewstrom.jsonDelight.runtime.JsonRegistrable
import com.jaynewstrom.jsonDelight.runtime.JsonSerializer
import com.jaynewstrom.jsonDelight.runtime.JsonSerializerFactory
import java.io.IOException
object ShortJsonAdapter : JsonSerializer<Short>, JsonDeserializer<Short>, JsonRegistrable {
@Throws(IOException::class)
override fun serialize(value: Short, jg: JsonGenerator, serializerFactory: JsonSerializerFactory) = jg.writeNumber(value)
@Throws(IOException::class)
override fun deserialize(jp: JsonParser, deserializerFactory: JsonDeserializerFactory): Short = jp.shortValue
override fun modelClass(): Class<*> = Short::class.java
}
| plugin/runtime/src/main/java/com/jaynewstrom/jsonDelight/runtime/internal/ShortJsonAdapter.kt | 774902217 |
package org.sanpra.checklist.activity
import android.content.Intent
import android.graphics.drawable.Drawable
import android.view.ActionProvider
import android.view.ContextMenu
import android.view.MenuItem
import android.view.SubMenu
import android.view.View
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.apache.commons.collections4.Closure
import org.apache.commons.collections4.IterableUtils
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.sanpra.checklist.R
import org.sanpra.checklist.dbhelper.ChecklistItem
@RunWith(AndroidJUnit4::class)
class ItemsListFragmentTests : BaseTests() {
@Test
fun testDeleteCheckedItemsMenuOption() {
val prefilledItems = ArrayList<ChecklistItem>()
prefilledItems.add(ChecklistItem().apply {
id = 1
description = "Hello world"
isChecked = false
})
prefilledItems.add(ChecklistItem().apply {
id = 2
description = "Testing"
isChecked = true
})
prefilledItems.add(ChecklistItem().apply {
id = 3
description = "Yet again"
isChecked = false
})
mockItemsController.addItems(prefilledItems)
val fragmentScenario = launchFragment(ItemsListFragment::class.java, R.style.AppTheme_ActionBar)
fragmentScenario.onFragment {
it.onOptionsItemSelected(MockMenuItem(R.id.menu_delcheckeditems))
}
Thread.sleep(1000)
val itemCheckStatusClosure = ItemCheckStatusClosure()
IterableUtils.forEach(mockItemsController.listItems(), itemCheckStatusClosure)
Assert.assertFalse(itemCheckStatusClosure.isAnyChecked)
}
}
private class ItemCheckStatusClosure : Closure<ChecklistItem> {
var isAnyChecked : Boolean = false
private set
override fun execute(input: ChecklistItem) {
if(input.isChecked) isAnyChecked = true
}
}
private class MockMenuItem(private val itemId : Int) : MenuItem {
override fun expandActionView(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun hasSubMenu(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMenuInfo(): ContextMenu.ContextMenuInfo {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getItemId(): Int = itemId
override fun getAlphabeticShortcut(): Char {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setEnabled(enabled: Boolean): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTitle(title: CharSequence?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTitle(title: Int): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setChecked(checked: Boolean): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getActionView(): View {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTitle(): CharSequence {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getOrder(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setOnActionExpandListener(listener: MenuItem.OnActionExpandListener?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getIntent(): Intent {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setVisible(visible: Boolean): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isEnabled() = true
override fun isCheckable()= false
override fun setShowAsAction(actionEnum: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getGroupId(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setActionProvider(actionProvider: ActionProvider?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTitleCondensed(title: CharSequence?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getNumericShortcut(): Char {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isActionViewExpanded(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun collapseActionView(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isVisible(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setNumericShortcut(numericChar: Char): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setActionView(view: View?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setActionView(resId: Int): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setAlphabeticShortcut(alphaChar: Char): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setIcon(icon: Drawable?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setIcon(iconRes: Int): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isChecked(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setIntent(intent: Intent?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setShortcut(numericChar: Char, alphaChar: Char): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getIcon(): Drawable {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setShowAsActionFlags(actionEnum: Int): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setOnMenuItemClickListener(menuItemClickListener: MenuItem.OnMenuItemClickListener?): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getActionProvider(): ActionProvider {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setCheckable(checkable: Boolean): MenuItem {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSubMenu(): SubMenu {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTitleCondensed(): CharSequence {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
} | app/src/androidTest/java/org/sanpra/checklist/activity/ItemsListFragmentTests.kt | 1426078116 |
package com.github.willjgriff.skeleton.ui.utils
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
/**
* Created by Will on 15/01/2017.
*/
fun convertDpToPixel(dp: Float, context: Context): Float {
val resources = context.resources
val metrics = resources.displayMetrics
return dp * (metrics.densityDpi / 160f);
}
fun convertPixelsToDp(px: Float, context: Context): Float {
val resources = context.resources
val metrics = resources.displayMetrics
return px / (metrics.densityDpi / 160f)
}
fun hideSoftKeyboard(view: View, context: Context) {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE)
if (inputMethodManager is InputMethodManager) {
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
}
| app/src/main/java/com/github/willjgriff/skeleton/ui/utils/UiUtils.kt | 2937518408 |
package zak0.github.calendarcountdown.widget
import android.content.Intent
import android.widget.RemoteViewsService
class CountdownAppWidgetRemoteViewsService : RemoteViewsService() {
override fun onGetViewFactory(intent: Intent): RemoteViewsFactory = CountdownAppWidgetRemoteViewsFactory(applicationContext)
} | app/src/main/java/zak0/github/calendarcountdown/widget/CountdownAppWidgetRemoteViewsService.kt | 4175959543 |
/*
* 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.search.domain.usecase
import jp.hazuki.yuzubrowser.bookmark.repository.BookmarkManager
import jp.hazuki.yuzubrowser.history.repository.BrowserHistoryManager
import jp.hazuki.yuzubrowser.search.domain.ISearchUrlRepository
import jp.hazuki.yuzubrowser.search.domain.ISuggestRepository
import jp.hazuki.yuzubrowser.search.model.SearchSuggestModel
import jp.hazuki.yuzubrowser.search.model.provider.SearchSuggestProviders
import jp.hazuki.yuzubrowser.ui.utils.isUrl
import java.util.*
internal class SearchViewUseCase(
private val bookmarkManager: BookmarkManager,
private val historyManager: BrowserHistoryManager,
private val suggestRepository: ISuggestRepository,
private val searchUrlRepository: ISearchUrlRepository
) {
var suggestType = 0
fun getSearchQuery(query: String): List<SearchSuggestModel> {
return suggestRepository.getSearchQuery(suggestType, query)
}
fun getHistoryQuery(query: String): List<SearchSuggestModel> {
if (query.isEmpty()) {
return listOf()
}
val histories = historyManager.search(query, 0, 5)
val list = ArrayList<SearchSuggestModel>(histories.size)
histories.forEach {
list.add(SearchSuggestModel.HistoryModel(it.title ?: "", it.url ?: ""))
}
return list
}
fun getBookmarkQuery(query: String): List<SearchSuggestModel> {
if (query.isEmpty()) {
return listOf()
}
val bookmarks = bookmarkManager.search(query)
val list = ArrayList<SearchSuggestModel>(if (bookmarks.size >= 5) 5 else bookmarks.size)
bookmarks.asSequence().take(5).forEach {
list.add(SearchSuggestModel.HistoryModel(it.title!!, it.url))
}
return list
}
fun saveQuery(query: String) {
if (query.isNotEmpty() && !query.isUrl() && suggestType != SUGGEST_TYPE_NONE) {
suggestRepository.insert(suggestType, query)
}
}
fun deleteQuery(query: String) {
suggestRepository.delete(suggestType, query)
}
fun loadSuggestProviders(): SearchSuggestProviders {
return SearchSuggestProviders(searchUrlRepository.load())
}
fun saveSuggestProviders(providers: SearchSuggestProviders) {
searchUrlRepository.save(providers.toSettings())
}
companion object {
private const val SUGGEST_TYPE_NONE = 3
}
}
| module/search/src/main/java/jp/hazuki/yuzubrowser/search/domain/usecase/SearchViewUseCase.kt | 438441887 |
/*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.event
import com.fasterxml.jackson.annotation.JsonIgnore
import com.netflix.spinnaker.clouddriver.event.exceptions.UninitializedEventException
/**
* WARNING: Do not use this base class with Lombok events, you will have a bad time! Only use in Kotlin classes.
* For some reason, Lombok / Jackson can't find methods to deserialize, so the Java classes have to implement the
* interface directly. I'm not sure if this is a result of writing in Kotlin, or an issue in Lombok and/or Jackson.
*/
abstract class AbstractSpinnakerEvent : SpinnakerEvent {
/**
* Not a lateinit to make Java/Lombok & Jackson compatibility a little easier, although behavior is exactly the same.
*/
@JsonIgnore
private var metadata: EventMetadata? = null
override fun getMetadata(): EventMetadata {
return metadata ?: throw UninitializedEventException()
}
override fun setMetadata(eventMetadata: EventMetadata) {
metadata = eventMetadata
}
}
| clouddriver-event/src/main/kotlin/com/netflix/spinnaker/clouddriver/event/AbstractSpinnakerEvent.kt | 328868108 |
/*
* Copyright 2018 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.moderation.bukkit.ticket
import com.rpkit.moderation.bukkit.event.ticket.RPKBukkitTicketCloseEvent
import com.rpkit.players.bukkit.profile.RPKProfile
import org.bukkit.Bukkit
import org.bukkit.Location
import java.time.LocalDateTime
class RPKTicketImpl(
override var id: Int = 0,
override val reason: String,
override val issuer: RPKProfile,
override var resolver: RPKProfile?,
override val location: Location?,
override val openDate: LocalDateTime,
override var closeDate: LocalDateTime?,
override var isClosed: Boolean
): RPKTicket {
constructor(reason: String, issuer: RPKProfile, location: Location): this(
0,
reason,
issuer,
null,
location,
LocalDateTime.now(),
null,
false
)
override fun close(resolver: RPKProfile) {
val event = RPKBukkitTicketCloseEvent(resolver, this)
Bukkit.getServer().pluginManager.callEvent(event)
if (event.isCancelled) return
isClosed = true
this.resolver = event.profile
closeDate = LocalDateTime.now()
}
} | bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/ticket/RPKTicketImpl.kt | 1226412527 |
/*
* 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.abp
import android.os.Bundle
import dagger.hilt.android.AndroidEntryPoint
import jp.hazuki.yuzubrowser.adblock.R
import jp.hazuki.yuzubrowser.ui.app.ThemeActivity
@AndroidEntryPoint
class AbpActivity : ThemeActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_base)
supportFragmentManager.beginTransaction()
.replace(R.id.container, AbpFragment())
.commit()
}
}
| module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/abp/AbpActivity.kt | 3798119168 |
package com.petrulak.cleankotlin.domain.interactor
import com.petrulak.cleankotlin.domain.executor.SchedulerProvider
import com.petrulak.cleankotlin.domain.interactor.definition.GetWeatherRemotelyUseCase
import com.petrulak.cleankotlin.domain.model.Weather
import com.petrulak.cleankotlin.domain.repository.WeatherRepository
import io.reactivex.Single
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class GetWeatherRemotelyUseCaseImpl
@Inject
constructor(
private val schedulerProvider: SchedulerProvider,
private val repository: WeatherRepository
) : GetWeatherRemotelyUseCase {
private fun buildUseCase(city: String): Single<Weather> {
return when (city.isEmpty()) {
true -> Single.error(IllegalArgumentException("Wrong parameters"))
false -> repository.getWeatherForCityRemotely(city)
}
}
override fun execute(city: String): Single<Weather> {
return buildUseCase(city).subscribeOn(schedulerProvider.io()).observeOn(schedulerProvider.ui())
}
}
| domain/src/main/java/com/petrulak/cleankotlin/domain/interactor/GetWeatherRemotelyUseCaseImpl.kt | 2713318239 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.dsl.kotlin.model
import org.apache.camel.CamelContext
import org.apache.camel.Component
class ComponentsConfiguration(val context: CamelContext) {
inline fun <reified T : Component> component(name: String, block: T.() -> Unit) : T {
var target = context.getComponent(name, true, false)
var bind = false
if (target != null && !T::class.java.isInstance(target)) {
throw IllegalArgumentException("Type mismatch, expected: ${T::class.java}, got: ${target.javaClass}")
}
// if the component is not found, let's create a new one. This is
// equivalent to create a new named component, useful to create
// multiple instances of the same component but with different setup
if (target == null) {
target = context.injector.newInstance(T::class.java)
bind = true
}
block.invoke(target as T)
if (bind) {
context.registry.bind(name, T::class.java, target)
}
return target
}
} | dsl/camel-kotlin-dsl/src/main/kotlin/org/apache/camel/dsl/kotlin/model/ComponentsConfiguration.kt | 1470656045 |
package fr.free.nrw.commons.utils
import fr.free.nrw.commons.utils.StringSortingUtils.sortBySimilarity
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.Collections.sort
class StringSortingUtilsTest {
@Test
fun testSortingNumbersBySimilarity() {
val actualList = listOf("1234567", "4567", "12345", "123", "1234")
val expectedList = listOf("1234", "12345", "123", "1234567", "4567")
sort(actualList, sortBySimilarity("1234"))
assertEquals(expectedList, actualList)
}
@Test
fun testSortingTextBySimilarity() {
val actualList = listOf("The quick brown fox",
"quick brown fox",
"The",
"The quick ",
"The fox",
"brown fox",
"fox")
val expectedList = listOf("The",
"The fox",
"The quick ",
"The quick brown fox",
"quick brown fox",
"brown fox",
"fox")
sort(actualList, sortBySimilarity("The"))
assertEquals(expectedList, actualList)
}
} | app/src/test/kotlin/fr/free/nrw/commons/utils/StringSortingUtilsTest.kt | 130970984 |
package com.google.firebase.appdistributionquickstart.kotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.appdistribution.FirebaseAppDistribution
import com.google.firebase.appdistribution.FirebaseAppDistributionException
import com.google.firebase.appdistribution.ktx.appDistribution
import com.google.firebase.appdistributionquickstart.databinding.ActivityMainBinding
import com.google.firebase.ktx.Firebase
class KotlinMainActivity : AppCompatActivity() {
private lateinit var firebaseAppDistribution: FirebaseAppDistribution
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAppDistribution = Firebase.appDistribution
}
override fun onResume() {
super.onResume()
firebaseAppDistribution.updateIfNewReleaseAvailable()
.addOnProgressListener { updateProgress ->
// (Optional) Implement custom progress updates in addition to
// automatic NotificationManager updates.
}
.addOnFailureListener { e ->
if (e is FirebaseAppDistributionException) {
// Handle exception.
}
}
}
companion object {
private const val TAG = "AppDistribution-Quickstart"
}
}
| appdistribution/app/src/main/java/com/google/firebase/appdistributionquickstart/kotlin/KotlinMainActivity.kt | 1626968807 |
/*******************************************************************************
* Copyright 2010 Alexandros Schillings
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.alt236.underthehood.commandrunner
import android.content.res.Resources
import android.os.Build
import android.util.Log
import uk.co.alt236.underthehood.commandrunner.groups.*
import uk.co.alt236.underthehood.commandrunner.model.Result
import java.util.concurrent.Callable
internal class ExecuteCallable(res: Resources) : Callable<Result> {
private val commandRunner = Cli()
private val hardwareCommands = HardwareCommands(res)
private val ipRouteCommands = IpRouteCommands(res)
private val netstatCommands = NetstatCommands(res)
private val otherCommands = OtherCommands(res)
private val procCommands = ProcCommands(res)
private val psCommands = PsCommands(res)
private val sysPropCommands = SysPropCommands(res)
private var isRooted = false
override fun call(): Result {
Log.d(TAG, "^ ExecuteThread: Thread Started")
isRooted = commandRunner.checkIfSu()
return try {
return collectResult(isRooted)
} catch (e: Exception) {
Log.e(TAG, "^ ExecuteThread: exception " + e.message)
Result.ERROR
}
}
private fun collectResult(isRooted: Boolean): Result {
val result = Result()
result.isRooted = isRooted
result.timestamp = System.currentTimeMillis()
result.deviceinfo = getDeviceInfo()
result.hardwareData = (hardwareCommands.execute(isRooted))
result.ipRouteData = (ipRouteCommands.execute(isRooted))
result.netstatData = (netstatCommands.execute(isRooted))
result.otherData = (otherCommands.execute(isRooted))
result.procData = (procCommands.execute(isRooted))
result.psData = (psCommands.execute(isRooted))
result.sysPropData = (sysPropCommands.execute(isRooted))
Log.d(TAG, "^ ExecuteThread: Returning result")
return result
}
private fun getDeviceInfo(): String {
return Build.MANUFACTURER + " " + Build.PRODUCT + " " + Build.DEVICE + ", API: ${Build.VERSION.SDK_INT}".trim()
}
companion object {
private val TAG = this::class.java.simpleName
}
} | command_runner/src/main/java/uk/co/alt236/underthehood/commandrunner/ExecuteCallable.kt | 3435330026 |
package be.doji.productivity.trambuapp.styles
import javafx.scene.layout.BackgroundPosition
import javafx.scene.text.FontPosture
import javafx.scene.text.FontWeight
import tornadofx.Stylesheet
import tornadofx.c
import tornadofx.cssclass
class DefaultTrambuStyle : Stylesheet() {
companion object {
val todo by cssclass()
val done by cssclass()
val alert by cssclass()
val separatorLabel by cssclass()
val warningLabel by cssclass()
val default by cssclass()
val buttonBold by cssclass()
val activityOverlay by cssclass()
val mainColor = c("#505050")
val defaultTextColor = c("#ffffff")
}
init {
root {
baseColor = mainColor
backgroundColor += c("transparent")
textFill = defaultTextColor
backgroundImage += this.javaClass.classLoader.getResource("images/repeating-pattern-rocks-opace.png").toURI()
backgroundPosition += BackgroundPosition.CENTER
}
todo {
skin = com.sun.javafx.scene.control.skin.TitledPaneSkin::class
textFill = defaultTextColor
backgroundColor += c("#3598c1")
baseColor = c("#3598c1")
separatorLabel {
textFill = c("#820d98")
}
}
activityOverlay {
baseColor = mainColor
backgroundColor += c("#8598a6")
baseColor = c("#8598a6")
}
done {
skin = com.sun.javafx.scene.control.skin.TitledPaneSkin::class
textFill = defaultTextColor
backgroundColor += c("#383f38")
baseColor = c("#383f38")
title { fontStyle = FontPosture.ITALIC }
}
alert {
skin = com.sun.javafx.scene.control.skin.TitledPaneSkin::class
textFill = defaultTextColor
backgroundColor += c("#a8431a")
baseColor = c("#a8431a")
}
separatorLabel {
textFill = c("orange")
}
warningLabel {
textFill = c("#a8431a")
}
default {
baseColor = mainColor
backgroundColor += c(mainColor.toString(), 0.65)
}
splitPane {
backgroundColor += c(mainColor.toString(), 0.65)
}
scrollPane {
backgroundColor += c("transparent")
baseColor = c("transparent")
content {
backgroundColor += c("transparent")
}
}
accordion {
backgroundColor += c("transparent")
titledPane {
content {
backgroundColor += c("transparent")
}
}
}
}
} | trambu-app/src/main/kotlin/be/doji/productivity/trambuapp/styles/DefaultTrambuStyle.kt | 715715843 |
package com.github.davinkevin.podcastserver.entity
import com.fasterxml.jackson.annotation.JsonCreator
enum class Status {
NOT_DOWNLOADED,
STARTED,
PAUSED,
DELETED,
STOPPED,
FAILED,
FINISH;
companion object {
private val values = setOf(*values())
@JsonCreator
@JvmStatic
fun of(v: String): Status {
return values
.firstOrNull { s -> s.toString() == v }
?: throw IllegalArgumentException("No enum constant Status.$v")
}
}
}
| backend/src/main/kotlin/com/github/davinkevin/podcastserver/entity/Status.kt | 1143454756 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
@file:Suppress("JAVA_MODULE_DOES_NOT_DEPEND_ON_MODULE")
package com.almasb.fxgl.dsl.components
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.`is`
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
/**
* @author Almas Baimagambetov ([email protected])
*/
class ActivatorComponentTest {
private lateinit var activator: ActivatorComponent
@Test
fun `ActivatorComponent can be activated and deactivated`() {
activator = ActivatorComponent(true, 3)
assertTrue(activator.canBeDeactivated)
assertThat(activator.numTimesCanBeActivated, `is`(3))
assertFalse(activator.isActivated)
assertFalse(activator.valueProperty().value)
// activated 1
activator.activate()
assertTrue(activator.isActivated)
assertTrue(activator.valueProperty().value)
activator.deactivate()
assertFalse(activator.isActivated)
assertFalse(activator.valueProperty().value)
// activated 2
activator.press()
assertTrue(activator.isActivated)
assertTrue(activator.valueProperty().value)
activator.press()
assertFalse(activator.isActivated)
assertFalse(activator.valueProperty().value)
// activated 3
activator.activate()
assertTrue(activator.isActivated)
assertTrue(activator.valueProperty().value)
activator.deactivate()
assertFalse(activator.isActivated)
assertFalse(activator.valueProperty().value)
// should not activate again
activator.activate()
assertFalse(activator.isActivated)
assertFalse(activator.valueProperty().value)
}
} | fxgl/src/test/kotlin/com/almasb/fxgl/dsl/components/ActivatorComponentTest.kt | 3250639881 |
package net.yuzumone.bergamio.di
import dagger.Component
import net.yuzumone.bergamio.MainApp
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(AppModule::class))
interface AppComponent {
fun inject(application: MainApp)
fun plus(module: ActivityModule): ActivityComponent
} | app/src/main/kotlin/net/yuzumone/bergamio/di/AppComponent.kt | 3568558717 |
/*
* Copyright 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dessertrelease.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.dessertrelease.R
import com.example.dessertrelease.data.local.LocalDessertReleaseData
import com.example.dessertrelease.ui.theme.DessertReleaseTheme
/*
* Screen level composable
*/
@Composable
fun DessertReleaseApp(
modifier: Modifier = Modifier,
dessertReleaseViewModel: DessertReleaseViewModel = viewModel(
factory = DessertReleaseViewModel.Factory
)
) {
DessertReleaseApp(
uiState = dessertReleaseViewModel.uiState.collectAsState().value,
selectLayout = dessertReleaseViewModel::selectLayout,
modifier = modifier
)
}
@Composable
private fun DessertReleaseApp(
uiState: DessertReleaseUiState,
selectLayout: (Boolean) -> Unit,
modifier: Modifier = Modifier
) {
val isLinearLayout = uiState.isLinearLayout
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.top_bar_name)) },
actions = {
IconButton(
onClick = {
selectLayout(!isLinearLayout)
}
) {
Icon(
painter = painterResource(uiState.toggleIcon),
contentDescription = stringResource(uiState.toggleContentDescription),
tint = MaterialTheme.colors.onPrimary
)
}
}
)
}
) { innerPadding ->
if (isLinearLayout) {
DessertReleaseLinearLayout(modifier.padding(innerPadding))
} else {
DessertReleaseGridLayout(modifier.padding(innerPadding))
}
}
}
@Composable
fun DessertReleaseLinearLayout(modifier: Modifier = Modifier) {
LazyColumn(
modifier = modifier.fillMaxWidth(),
contentPadding = PaddingValues(vertical = 16.dp, horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(
items = LocalDessertReleaseData.dessertReleases.toList(),
key = { dessert -> dessert }
) { dessert ->
Card(
backgroundColor = MaterialTheme.colors.primary,
shape = MaterialTheme.shapes.small
) {
Text(
text = dessert,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
textAlign = TextAlign.Center
)
}
}
}
}
@Composable
fun DessertReleaseGridLayout(modifier: Modifier = Modifier) {
LazyVerticalGrid(
modifier = modifier,
columns = GridCells.Fixed(3),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
items(
items = LocalDessertReleaseData.dessertReleases,
key = { dessert -> dessert }
) { dessert ->
Card(
backgroundColor = MaterialTheme.colors.primary,
modifier = Modifier.height(110.dp),
shape = MaterialTheme.shapes.medium
) {
Text(
text = dessert,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxHeight()
.wrapContentHeight(Alignment.CenterVertically)
.padding(8.dp),
textAlign = TextAlign.Center
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DessertReleaseLinearLayoutPreview() {
DessertReleaseTheme {
DessertReleaseLinearLayout()
}
}
@Preview(showBackground = true)
@Composable
fun DessertReleaseGridLayoutPreview() {
DessertReleaseTheme {
DessertReleaseGridLayout()
}
}
@Preview
@Composable
fun DessertReleaseAppPreview() {
DessertReleaseTheme {
DessertReleaseApp(
uiState = DessertReleaseUiState(),
selectLayout = {}
)
}
}
| app/src/main/java/com/example/dessertrelease/ui/DessertReleaseApp.kt | 4214498336 |
package fr.free.nrw.commons.utils
import android.database.Cursor
import androidx.lifecycle.LiveData
import androidx.paging.DataSource
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import androidx.room.InvalidationTracker
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.paging.LimitOffsetDataSource
import com.nhaarman.mockitokotlin2.whenever
import org.mockito.Mockito.mock
fun <T> List<T>.asPagedList(config: PagedList.Config? = null): LiveData<PagedList<T>> {
val defaultConfig = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(size)
.setMaxSize(size + 2)
.setPrefetchDistance(1)
.build()
return LivePagedListBuilder<Int, T>(
createMockDataSourceFactory(this),
config ?: defaultConfig
).build()
}
/**
* Provides a mocked instance of the data source factory
*/
fun <T> createMockDataSourceFactory(itemList: List<T>): DataSource.Factory<Int, T> =
object : DataSource.Factory<Int, T>() {
override fun create(): DataSource<Int, T> = MockLimitDataSource(itemList)
}
/**
* Provides a mocked Room SQL query
*/
private fun mockQuery(): RoomSQLiteQuery {
val query = mock(RoomSQLiteQuery::class.java);
whenever(query.sql).thenReturn("");
return query;
}
/**
* Provides a mocked Room DB
*/
private fun mockDb(): RoomDatabase {
val roomDatabase = mock(RoomDatabase::class.java);
val invalidationTracker = mock(InvalidationTracker::class.java)
whenever(roomDatabase.invalidationTracker).thenReturn(invalidationTracker);
return roomDatabase;
}
/**
* Class that defines the mocked data source
*/
class MockLimitDataSource<T>(private val itemList: List<T>) :
LimitOffsetDataSource<T>(mockDb(), mockQuery(), false, "") {
override fun convertRows(cursor: Cursor): MutableList<T> {
return itemList.toMutableList()
}
override fun countItems(): Int = itemList.count()
override fun isInvalid(): Boolean = false
override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<T>) {
}
override fun loadRange(startPosition: Int, loadCount: Int): MutableList<T> {
return itemList.subList(startPosition, startPosition + loadCount).toMutableList()
}
override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<T>) {
callback.onResult(itemList, 0)
}
} | app/src/test/kotlin/fr/free/nrw/commons/utils/PagedListMock.kt | 1987190306 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package chattime.common
object Info
{
const val version = "0.2.0"
const val fullVersion = "ChatTime v$version"
const val url = "https://github.com/Juuxel/ChatTime"
}
| src/main/kotlin/chattime/common/Info.kt | 1837171239 |
package siosio.jsr352.jsl
interface Element {
fun build(): String
}
| src/main/kotlin/siosio/jsr352/jsl/Element.kt | 1904414920 |
package org.luxons.sevenwonders.ui.components.game
import kotlinx.css.*
import kotlinx.css.properties.borderTop
import kotlinx.css.properties.boxShadow
import kotlinx.html.DIV
import org.luxons.sevenwonders.model.boards.Production
import org.luxons.sevenwonders.model.resources.CountedResource
import org.luxons.sevenwonders.model.resources.ResourceType
import react.RBuilder
import react.dom.key
import styled.StyledDOMBuilder
import styled.css
import styled.styledDiv
import styled.styledSpan
fun RBuilder.productionBar(gold: Int, production: Production) {
styledDiv {
css {
productionBarStyle()
}
goldIndicator(gold)
fixedResources(production.fixedResources)
alternativeResources(production.alternativeResources)
}
}
private fun RBuilder.fixedResources(resources: List<CountedResource>) {
styledDiv {
css {
margin = "auto"
display = Display.flex
}
resources.forEach {
resourceWithCount(resourceType = it.type, count = it.count, imgSize = 3.rem) {
attrs { key = it.type.toString() }
css { marginLeft = 1.rem }
}
}
}
}
private fun RBuilder.alternativeResources(resources: List<Set<ResourceType>>) {
styledDiv {
css {
margin = "auto"
display = Display.flex
}
resources.forEachIndexed { index, res ->
resourceChoice(types = res) {
attrs {
key = index.toString()
}
}
}
}
}
private fun RBuilder.resourceChoice(types: Set<ResourceType>, block: StyledDOMBuilder<DIV>.() -> Unit = {}) {
styledDiv {
css {
marginLeft = (1.5).rem
}
block()
for ((i, t) in types.withIndex()) {
resourceImage(resourceType = t, size = 3.rem) {
attrs { this.key = t.toString() }
}
if (i < types.indices.last) {
styledSpan {
css { choiceSeparatorStyle() }
+"/"
}
}
}
}
}
private fun CSSBuilder.productionBarStyle() {
alignItems = Align.center
background = "linear-gradient(#eaeaea, #888 7%)"
bottom = 0.px
borderTop(width = 1.px, color = Color("#8b8b8b"), style = BorderStyle.solid)
boxShadow(blurRadius = 15.px, color = Color("#747474"))
display = Display.flex
height = (3.5).rem
width = 100.vw
position = Position.fixed
zIndex = 99
}
private fun CSSBuilder.choiceSeparatorStyle() {
fontSize = 2.rem
verticalAlign = VerticalAlign.middle
margin(all = 5.px)
color = Color("#c29929")
declarations["text-shadow"] = "0 0 1px black"
}
| sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/game/ProductionBar.kt | 3547886795 |
package chase
import formula.TRUE
class TopDownSelector<out S : Sequent>(private val sequents: List<S>) : Selector<S> {
override fun iterator(): Iterator<S> = sequents.iterator()
override fun duplicate(): Selector<S> = this // because it always starts from the top, it's stateless and can be shared
}
class FairSelector<S : Sequent>(val sequents: Array<S>) : Selector<S> {
private var index = 0
inner class FairIterator(private val start: Int) : Iterator<S> {
var stop = false
override fun hasNext(): Boolean = !sequents.isEmpty() && (index != start || !stop)
override fun next(): S {
if (!hasNext())
throw NoSuchElementException()
stop = true
val sequent = sequents[index]
index = (index + 1) % sequents.size
return sequent
}
}
override fun iterator(): Iterator<S> = FairIterator(index)
private constructor(selector: FairSelector<S>) : this(selector.sequents) { // the array of sequents can be shared
this.index = index // the index cannot
}
override fun duplicate(): Selector<S> = FairSelector(this)
}
class OptimalSelector<out S : Sequent> : Selector<S> {
inner class OneTimeIterator : Iterator<S> {
override fun hasNext(): Boolean = index < allSequents.first.size
override fun next(): S {
if (!hasNext())
throw NoSuchElementException()
return allSequents.first[index++]
}
}
private val allSequents: Pair<List<S>, List<S>>
private val selector: Selector<S>
private var index: Int
private val iterator: Iterator<S>
constructor(sequents: List<S>, selectorFunction: (sequents: List<S>) -> Selector<S>) {
this.allSequents = sequents.partition { it.body == TRUE && it.head.freeVars.isEmpty() && it.head.freeVars.isEmpty() }
this.selector = selectorFunction(this.allSequents.second)
this.iterator = OneTimeIterator()
index = 0
}
private constructor(selector: OptimalSelector<S>) {
this.allSequents = selector.allSequents
this.selector = selector.selector.duplicate()
this.iterator = OneTimeIterator()
this.index = selector.index
}
override fun iterator(): Iterator<S> = if (iterator.hasNext()) iterator else selector.iterator()
override fun duplicate(): Selector<S> = OptimalSelector(this)
} | src/main/java/chase/Selectors.kt | 2338403061 |
package net.perfectdreams.loritta.morenitta.commands.vanilla.action
import net.perfectdreams.loritta.morenitta.LorittaBot
import java.awt.Color
class HugCommand(loritta: LorittaBot): ActionCommand(loritta, listOf("hug", "abraço", "abraçar", "abraco", "abracar")) {
override fun create(): ActionCommandDSL = action {
emoji = "\uD83D\uDC99"
color = Color(255, 235, 59)
response { locale, sender, target ->
locale["commands.command.hug.response", sender.asMention, target.asMention]
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/action/HugCommand.kt | 4042887615 |
package org.owntracks.android.geocoding
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.PRIORITY_LOW
import androidx.core.app.NotificationManagerCompat
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.*
import org.owntracks.android.R
import org.owntracks.android.model.messages.MessageLocation
import org.owntracks.android.services.BackgroundService
import org.owntracks.android.support.Preferences
import org.owntracks.android.ui.map.MapActivity
import org.threeten.bp.Instant
import org.threeten.bp.ZoneOffset.UTC
import org.threeten.bp.format.DateTimeFormatter
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class GeocoderProvider @Inject constructor(
@ApplicationContext private val context: Context,
private val preferences: Preferences
) {
private val ioDispatcher = Dispatchers.IO
private var lastRateLimitedNotificationTime: Instant? = null
private var notificationManager: NotificationManagerCompat
private var geocoder: Geocoder = GeocoderNone()
private var job: Job? = null
private fun setGeocoderProvider(context: Context, preferences: Preferences) {
Timber.i("Setting geocoding provider to ${preferences.reverseGeocodeProvider}")
job = GlobalScope.launch {
withContext(ioDispatcher) {
geocoder = when (preferences.reverseGeocodeProvider) {
Preferences.REVERSE_GEOCODE_PROVIDER_OPENCAGE -> OpenCageGeocoder(
preferences.openCageGeocoderApiKey
)
Preferences.REVERSE_GEOCODE_PROVIDER_DEVICE -> DeviceGeocoder(context)
else -> GeocoderNone()
}
}
}
}
private suspend fun geocoderResolve(messageLocation: MessageLocation): GeocodeResult {
return withContext(ioDispatcher) {
job?.run { join() }
return@withContext geocoder.reverse(messageLocation.latitude, messageLocation.longitude)
}
}
suspend fun resolve(messageLocation: MessageLocation) {
if (messageLocation.hasGeocode) {
return
}
Timber.d("Resolving geocode for $messageLocation")
val result = geocoderResolve(messageLocation)
messageLocation.geocode = geocodeResultToText(result)
maybeCreateErrorNotification(result)
}
private fun maybeCreateErrorNotification(result: GeocodeResult) {
if (result is GeocodeResult.Formatted || result is GeocodeResult.Empty || !preferences.notificationGeocoderErrors) {
notificationManager.cancel(GEOCODE_ERROR_NOTIFICATION_TAG, 0)
return
}
val errorNotificationText = when (result) {
is GeocodeResult.Fault.Error -> context.getString(
R.string.geocoderError,
result.message
)
is GeocodeResult.Fault.ExceptionError -> context.getString(R.string.geocoderExceptionError)
is GeocodeResult.Fault.Disabled -> context.getString(R.string.geocoderDisabled)
is GeocodeResult.Fault.IPAddressRejected -> context.getString(R.string.geocoderIPAddressRejected)
is GeocodeResult.Fault.RateLimited -> context.getString(
R.string.geocoderRateLimited,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(UTC).format(result.until)
)
is GeocodeResult.Fault.Unavailable -> context.getString(R.string.geocoderUnavailable)
else -> ""
}
val until = when (result) {
is GeocodeResult.Fault -> result.until
else -> Instant.MIN
}
if (until == lastRateLimitedNotificationTime) {
return
} else {
lastRateLimitedNotificationTime = until
}
val activityLaunchIntent = Intent(this.context, MapActivity::class.java)
activityLaunchIntent.action = "android.intent.action.MAIN"
activityLaunchIntent.addCategory("android.intent.category.LAUNCHER")
activityLaunchIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
val notification = NotificationCompat.Builder(context, ERROR_NOTIFICATION_CHANNEL_ID)
.setContentTitle(context.getString(R.string.geocoderProblemNotificationTitle))
.setContentText(errorNotificationText)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_owntracks_80)
.setStyle(NotificationCompat.BigTextStyle().bigText(errorNotificationText))
.setContentIntent(
PendingIntent.getActivity(
context,
0,
activityLaunchIntent,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT else PendingIntent.FLAG_UPDATE_CURRENT
)
)
.setPriority(PRIORITY_LOW)
.setSilent(true)
.build()
notificationManager.notify(GEOCODE_ERROR_NOTIFICATION_TAG, 0, notification)
}
private fun geocodeResultToText(result: GeocodeResult) =
when (result) {
is GeocodeResult.Formatted -> result.text
else -> null
}
fun resolve(messageLocation: MessageLocation, backgroundService: BackgroundService) {
if (messageLocation.hasGeocode) {
backgroundService.onGeocodingProviderResult(messageLocation)
return
}
MainScope().launch {
val result = geocoderResolve(messageLocation)
messageLocation.geocode = geocodeResultToText(result)
backgroundService.onGeocodingProviderResult(messageLocation)
maybeCreateErrorNotification(result)
}
}
init {
setGeocoderProvider(context, preferences)
preferences.registerOnPreferenceChangedListener(object :
SharedPreferences.OnSharedPreferenceChangeListener {
override fun onSharedPreferenceChanged(
sharedPreferences: SharedPreferences?,
key: String?
) {
if (key == preferences.getPreferenceKey(R.string.preferenceKeyReverseGeocodeProvider) || key == preferences.getPreferenceKey(
R.string.preferenceKeyOpencageGeocoderApiKey
)
) {
setGeocoderProvider(context, preferences)
}
}
})
notificationManager = NotificationManagerCompat.from(context)
}
companion object {
const val ERROR_NOTIFICATION_CHANNEL_ID = "Errors"
const val GEOCODE_ERROR_NOTIFICATION_TAG = "GeocoderError"
}
}
| project/app/src/main/java/org/owntracks/android/geocoding/GeocoderProvider.kt | 3073131445 |
/*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.ui
import android.accounts.Account
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import com.etesync.syncadapter.App
import com.etesync.syncadapter.R
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.syncadapter.model.JournalEntity
import com.etesync.syncadapter.resource.LocalCalendar
import com.etesync.syncadapter.resource.LocalTaskList
class EditCollectionActivity : CreateCollectionActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTitle(R.string.edit_collection)
when (info.enumType) {
CollectionInfo.Type.CALENDAR -> {
val colorSquare = findViewById<View>(R.id.color)
colorSquare.setBackgroundColor(info.color ?: LocalCalendar.defaultColor)
}
CollectionInfo.Type.TASKS -> {
val colorSquare = findViewById<View>(R.id.color)
colorSquare.setBackgroundColor(info.color ?: LocalTaskList.defaultColor)
}
CollectionInfo.Type.ADDRESS_BOOK -> {
}
}
val edit = findViewById<View>(R.id.display_name) as EditText
edit.setText(info.displayName)
val desc = findViewById<View>(R.id.description) as EditText
desc.setText(info.description)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_edit_collection, menu)
return true
}
override fun onDestroy() {
super.onDestroy()
if (parent is Refreshable) {
(parent as Refreshable).refresh()
}
}
fun onDeleteCollection(item: MenuItem) {
val data = (application as App).data
val journalCount = data.count(JournalEntity::class.java).where(JournalEntity.SERVICE_MODEL.eq(info.getServiceEntity(data))).get().value()
if (journalCount < 2) {
AlertDialog.Builder(this)
.setIcon(R.drawable.ic_error_dark)
.setTitle(R.string.account_delete_collection_last_title)
.setMessage(R.string.account_delete_collection_last_text)
.setPositiveButton(android.R.string.ok, null)
.show()
} else {
DeleteCollectionFragment.ConfirmDeleteCollectionFragment.newInstance(account, info).show(supportFragmentManager, null)
}
}
companion object {
fun newIntent(context: Context, account: Account, info: CollectionInfo): Intent {
val intent = Intent(context, EditCollectionActivity::class.java)
intent.putExtra(CreateCollectionActivity.EXTRA_ACCOUNT, account)
intent.putExtra(CreateCollectionActivity.EXTRA_COLLECTION_INFO, info)
return intent
}
}
}
| app/src/main/java/com/etesync/syncadapter/ui/EditCollectionActivity.kt | 3772411004 |
class Solution {
fun anagramMappings(A: IntArray, B: IntArray): IntArray {
val res = IntArray(A.size)
val map = HashMap<Int, Int>()
B.forEachIndexed { index, i -> map[i] = index }
for (i in A.indices)
res[i] = map[A[i]]!!
return res
}
} | leetcode/kotlin/ex_760.kt | 2951190343 |
package com.f3401pal.csm.dagger
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope | app/src/main/kotlin/com/f3401pal/csm/dagger/Scopes.kt | 2119623898 |
package com.wayfair.brickkit.brick
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.databinding.Bindable
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.mockito.kotlin.mock
import org.mockito.kotlin.spy
import org.mockito.kotlin.verify
import com.wayfair.brickkit.OpenForTesting
import com.wayfair.brickkit.padding.BrickPadding
import com.wayfair.brickkit.size.BrickSize
import com.wayfair.brickkit.test.BR
import com.wayfair.brickkit.test.R
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
@RunWith(AndroidJUnit4::class)
class ViewModelBrickTest {
@Test
fun testSingleViewModel_Test() {
val textDataModel = TextDataModel(TEXT)
val textViewModel = spy(TextViewModel(textDataModel))
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, textViewModel)
.build()
viewModelBrick.onBindData(
viewModelBrick.createViewHolder(
LayoutInflater.from(ApplicationProvider.getApplicationContext()).inflate(
viewModelBrick.layout,
LinearLayout(ApplicationProvider.getApplicationContext()),
false
)
)
)
verify(viewModelBrick.getViewModel(BR.viewModel) as TextViewModel).text
}
@Test
fun testEquals_dataModelsAreEqual() {
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, TextViewModel(TextDataModel(TEXT)))
.build()
val viewModelBrick2 = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, TextViewModel(TextDataModel(TEXT)))
.build()
assertTrue(viewModelBrick == viewModelBrick2)
}
@Test
fun testEquals_dataModelsAreNotEqual() {
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, TextViewModel(TextDataModel(TEXT)))
.build()
val viewModelBrick2 = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, TextViewModel(TextDataModel(TEXT_2)))
.build()
assertFalse(viewModelBrick == viewModelBrick2)
}
@Test
fun testEquals_dataModelsAreEqualDifferentOrder() {
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, TextViewModel(TextDataModel(TEXT)))
.addViewModel(BR.text, TextViewModel(TextDataModel(TEXT_2)))
.build()
val viewModelBrick2 = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.text, TextViewModel(TextDataModel(TEXT_2)))
.addViewModel(BR.viewModel, TextViewModel(TextDataModel(TEXT)))
.build()
assertTrue(viewModelBrick == viewModelBrick2)
}
@Test
fun testEquals_viewModelsAreDifferentTypes() {
assertFalse(ViewModelBrick.Builder(R.layout.text_brick_vm).build() == mock<BaseBrick>())
}
@Test
fun testAddViewModel() {
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, TextViewModel(TextDataModel(TEXT)))
.build()
viewModelBrick.addViewModel(BR.text, TextViewModel(TextDataModel(TEXT_2)))
assertEquals(2, viewModelBrick.viewModels.size())
}
@Test
fun testIsDataReady_emptyViewModels() {
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.build()
assertFalse(viewModelBrick.isDataReady)
}
@Test
fun testIsDataReady_firstNotReady() {
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, TextViewModel(TextDataModel("")))
.addViewModel(BR.text, TextViewModel(TextDataModel(TEXT)))
.build()
assertFalse(viewModelBrick.isDataReady)
}
@Test
fun testIsDataReady_lastNotReady() {
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.text, TextViewModel(TextDataModel(TEXT)))
.addViewModel(BR.viewModel, TextViewModel(TextDataModel("")))
.build()
assertFalse(viewModelBrick.isDataReady)
}
@Test
fun testIsDataReady_ready() {
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.text, TextViewModel(TextDataModel(TEXT)))
.addViewModel(BR.viewModel, TextViewModel(TextDataModel(TEXT)))
.build()
assertTrue(viewModelBrick.isDataReady)
}
@Test
fun testBuilder_setPlaceholder() {
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, TextViewModel(TextDataModel("")))
.setPlaceholder(R.layout.text_brick_vm_placeholder)
.build()
assertEquals(R.layout.text_brick_vm_placeholder, viewModelBrick.placeholderLayout)
}
@Test
fun testBuilder_setPadding() {
val padding = mock<BrickPadding>()
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.setPadding(padding)
.build()
assertEquals(padding, viewModelBrick.padding)
}
@Test
fun testBuilder_setSpanSize() {
val spanSize = mock<BrickSize>()
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.setSpanSize(spanSize)
.build()
assertEquals(spanSize, viewModelBrick.spanSize)
}
@Test
fun testBuilder_addViewModel() {
val viewModel = mock<ViewModel<DataModel>>()
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, viewModel)
.build()
assertEquals(viewModel, viewModelBrick.viewModels[BR.viewModel])
}
@Test
fun testBuilder_addNullViewModel() {
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, null)
.build()
assertNull(viewModelBrick.viewModels[BR.viewModel])
}
@Test
fun testOnChange() {
val dataModel = TextDataModel(TEXT)
val viewModel = TextViewModel(dataModel)
val viewModelBrick = ViewModelBrick.Builder(R.layout.text_brick_vm)
.addViewModel(BR.viewModel, viewModel)
.setPlaceholder(R.layout.text_brick_vm_placeholder)
.build()
val countDownLatch = CountDownLatch(1)
viewModel.addUpdateListener(
object : ViewModel.ViewModelUpdateListener {
override fun onChange() {
countDownLatch.countDown()
}
}
)
assertFalse(viewModelBrick.isHidden)
dataModel.text = ""
countDownLatch.await()
assertTrue(viewModelBrick.isHidden)
}
@OpenForTesting
class TextViewModel(dataModel: TextDataModel) : ViewModel<TextDataModel>(dataModel) {
@get:Bindable
val text: String
get() = dataModel.text
override fun equals(other: Any?): Boolean = other is TextViewModel && dataModel.text == other.dataModel.text
override fun hashCode(): Int = 1
}
class TextDataModel(initialText: String) : DataModel() {
var text: String = initialText
set(value) {
field = value
notifyChange()
}
override val isReady: Boolean
get() = text.isNotEmpty()
}
companion object {
private const val TEXT = "Test Text..."
private const val TEXT_2 = "Not Test Text..."
}
}
| BrickKit/bricks/src/androidTest/java/com/wayfair/brickkit/brick/ViewModelBrickTest.kt | 2912061390 |
package org.miaowo.miaowo.handler
import android.app.Activity
import android.support.annotation.MenuRes
import android.support.annotation.StringRes
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import org.miaowo.miaowo.R
import org.miaowo.miaowo.base.ListAdapter
import org.miaowo.miaowo.other.BaseListTouchListener
class ListHandler(activity: Activity) {
private val mActivity = activity
fun setTitle(title: String, @MenuRes menuRes: Int? = null, menuClickListener: (MenuItem) -> Boolean = {false}) {
val bar = mActivity.findViewById<Toolbar>(R.id.toolBar)
bar.apply {
setTitle(title)
setOnMenuItemClickListener { menuClickListener.invoke(it) }
}
}
fun setTitle(@StringRes title: Int, @MenuRes menuRes: Int? = null, menuClickListener: (MenuItem) -> Boolean = {false}) {
setTitle(mActivity.getString(title), menuRes, menuClickListener)
}
fun <T> setList(manager: RecyclerView.LayoutManager, adapter: ListAdapter<T>, data: List<T>? = null, click: BaseListTouchListener? = null) {
val list = mActivity.findViewById<RecyclerView>(R.id.list)
list.apply {
this.layoutManager = manager
this.adapter = adapter
}
if (click != null) { list.addOnItemTouchListener(click) }
if (data != null) { adapter.update(data) }
}
} | app/src/main/java/org/miaowo/miaowo/handler/ListHandler.kt | 1166117793 |
package com.me.harris.androidanimations._36_fun_kt
import android.os.Trace
/**
* Created by Harris on 2017/5/24.
*/
inline fun <T> trace(sectionName: String, body: () -> T) :T {
Trace.beginSection(sectionName)
try {
return body()
}finally {
Trace.endSection()
}
} | app/src/main/java/com/me/harris/androidanimations/_36_fun_kt/Trace.kt | 1244996325 |
/**
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.codelabs.productimagesearch
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.codelabs.productimagesearch.api.ProductSearchAPIClient
import com.google.codelabs.productimagesearch.databinding.ActivityProductSearchBinding
import com.google.codelabs.productimagesearch.api.ProductSearchResult
class ProductSearchActivity : AppCompatActivity() {
companion object {
const val TAG = "ProductSearchActivity"
const val CROPPED_IMAGE_FILE_NAME = "MLKitCroppedFile_"
const val REQUEST_TARGET_IMAGE_PATH = "REQUEST_TARGET_IMAGE_PATH"
}
private lateinit var viewBinding: ActivityProductSearchBinding
private lateinit var apiClient: ProductSearchAPIClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewBinding = ActivityProductSearchBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
initViews()
// Receive the query image and show it on the screen
intent.getStringExtra(REQUEST_TARGET_IMAGE_PATH)?.let { absolutePath ->
viewBinding.ivQueryImage.setImageBitmap(BitmapFactory.decodeFile(absolutePath))
}
// Initialize an API client for Vision API Product Search
apiClient = ProductSearchAPIClient(this)
}
private fun initViews() {
// Setup RecyclerView
with(viewBinding.recyclerView) {
setHasFixedSize(true)
adapter = ProductSearchAdapter()
layoutManager =
LinearLayoutManager(
this@ProductSearchActivity,
LinearLayoutManager.VERTICAL,
false
)
}
// Events
viewBinding.btnSearch.setOnClickListener {
// Display progress
viewBinding.progressBar.visibility = View.VISIBLE
(viewBinding.ivQueryImage.drawable as? BitmapDrawable)?.bitmap?.let {
searchByImage(it)
}
}
}
/**
* Use Product Search API to search with the given query image
*/
private fun searchByImage(queryImage: Bitmap) {
apiClient.annotateImage(queryImage)
.addOnSuccessListener { showSearchResult(it) }
.addOnFailureListener { error ->
Log.e(TAG, "Error calling Vision API Product Search.", error)
showErrorResponse(error.localizedMessage)
}
}
/**
* Show search result.
*/
private fun showSearchResult(result: List<ProductSearchResult>) {
viewBinding.progressBar.visibility = View.GONE
// Update the recycler view to display the search result.
(viewBinding.recyclerView.adapter as? ProductSearchAdapter)?.submitList(
result
)
}
/**
* Show Error Response
*/
private fun showErrorResponse(message: String?) {
viewBinding.progressBar.visibility = View.GONE
// Show the error when calling API.
Toast.makeText(this, "Error: $message", Toast.LENGTH_SHORT).show()
}
}
/**
* Adapter RecyclerView
*/
class ProductSearchAdapter :
ListAdapter<ProductSearchResult, ProductSearchAdapter.ProductViewHolder>(diffCallback) {
companion object {
val diffCallback = object : DiffUtil.ItemCallback<ProductSearchResult>() {
override fun areItemsTheSame(
oldItem: ProductSearchResult,
newItem: ProductSearchResult
) = oldItem.imageId == newItem.imageId && oldItem.imageUri == newItem.imageUri
override fun areContentsTheSame(
oldItem: ProductSearchResult,
newItem: ProductSearchResult
) = oldItem == newItem
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ProductViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_product, parent, false)
)
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
holder.bind(getItem(position))
}
/**
* ViewHolder to hold the data inside
*/
class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
/**
* Bind data to views
*/
@SuppressLint("SetTextI18n")
fun bind(product: ProductSearchResult) {
with(itemView) {
findViewById<TextView>(R.id.tvProductName).text = "Name: ${product.name}"
findViewById<TextView>(R.id.tvProductScore).text = "Similarity score: ${product.score}"
findViewById<TextView>(R.id.tvProductLabel).text = "Labels: ${product.label}"
// Show the image using Glide
Glide.with(itemView).load(product.imageUri).into(findViewById(R.id.ivProduct))
}
}
}
}
| product-search/codelab2/android/final/app/src/main/java/com/google/codelabs/productimagesearch/ProductSearchActivity.kt | 3905042298 |
package com.ghstudios.android.features.items.detail
import androidx.lifecycle.Observer
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.ListFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import com.ghstudios.android.AssetLoader
import com.ghstudios.android.data.classes.Gathering
import com.ghstudios.android.mhgendatabase.R
import com.ghstudios.android.ClickListeners.LocationClickListener
import com.ghstudios.android.SectionArrayAdapter
/**
* Fragment used to display locations where you can gather a specific item
*/
class ItemLocationFragment : ListFragment() {
/**
* Returns the viewmodel of this subfragment, anchored to the parent activity
*/
private val viewModel by lazy {
ViewModelProvider(activity!!).get(ItemDetailViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_generic_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// todo: Refactor this class not to use a cursor. Returning a cursor from a viewmodel can be a source of bugs
viewModel.gatherData.observe(viewLifecycleOwner, Observer { data ->
if (data != null) {
val adapter = GatheringListCursorAdapter(this.context!!, data)
listAdapter = adapter
}
})
}
/**
* Internal adapter to render the list of item gather locations
*/
private class GatheringListCursorAdapter(
context: Context,
gatheringData: List<Gathering>
) : SectionArrayAdapter<Gathering>(context, gatheringData, R.layout.listview_generic_header) {
override fun getGroupName(item: Gathering): String {
return item.rank + " " + item.location?.name
}
override fun newView(context: Context, item: Gathering, parent: ViewGroup): View {
// Use a layout inflater to get a row view
val inflater = LayoutInflater.from(context)
return inflater.inflate(R.layout.fragment_item_location_listitem,
parent, false)
}
override fun bindView(view: View, context: Context, gathering: Gathering) {
val itemLayout = view.findViewById<View>(R.id.listitem)
val mapTextView = view.findViewById<TextView>(R.id.map)
val methodTextView = view.findViewById<TextView>(R.id.method)
val rateTextView = view.findViewById<TextView>(R.id.rate)
val amountTextView = view.findViewById<TextView>(R.id.amount)
mapTextView.text = gathering.area
methodTextView.text = AssetLoader.localizeGatherNodeFull(gathering)
rateTextView.text = gathering.rate.toInt().toString() + "%"
amountTextView.text = "x" + gathering.quantity
itemLayout.tag = gathering.location!!.id
itemLayout.setOnClickListener(LocationClickListener(context,
gathering.location!!.id))
}
}
}
| app/src/main/java/com/ghstudios/android/features/items/detail/ItemLocationFragment.kt | 3464761112 |
package com.github.christophpickl.kpotpourri.http4k.integration_tests
import com.github.christophpickl.kpotpourri.http4k.BaseUrlConfig
import com.github.christophpickl.kpotpourri.http4k.HttpProtocol
import com.github.christophpickl.kpotpourri.http4k.buildHttp4k
import com.github.christophpickl.kpotpourri.http4k.get
import com.github.christophpickl.kpotpourri.wiremock4k.DEFAULT_WIREMOCK4K_PORT
import com.github.christophpickl.kpotpourri.wiremock4k.WIREMOCK4K_HOSTNAME
import com.github.christophpickl.kpotpourri.wiremock4k.request.verifyGetRequest
abstract class BaseUrlIT(restClient: HttpImplProducer) : Http4kWiremockTest(restClient) {
fun `Given Http4k without baseUrl, When request, Then URL was called`() {
givenGetMockEndpointUrl()
buildHttp4k {
baseUrlDisabled()
}
.get<Any>(mockWiremockUrlAndEndpointUrl)
verifyGetRequest(mockEndpointUrl)
}
fun `Given Http4k with baseUrl as string, When request, Then URL was called`() {
givenGetMockEndpointUrl()
buildHttp4k {
baseUrlBy(wiremockBaseUrl)
}.get<Any>(mockEndpointUrl)
verifyGetRequest(mockEndpointUrl)
}
fun `Given Http4k with baseUrl as config, When request, Then URL was called`() {
givenGetMockEndpointUrl()
buildHttp4k {
baseUrlBy(BaseUrlConfig(
protocol = HttpProtocol.Http,
hostName = WIREMOCK4K_HOSTNAME,
port = DEFAULT_WIREMOCK4K_PORT
))
}
.get<Any>(mockEndpointUrl)
verifyGetRequest(mockEndpointUrl)
}
}
| http4k/src/test/kotlin/com/github/christophpickl/kpotpourri/http4k/integration_tests/BaseUrlIT.kt | 1054304244 |
package cn.luo.yuan.maze.model.goods.types
import cn.luo.yuan.maze.model.goods.Goods
import cn.luo.yuan.maze.utils.Field
/**
* Created by luoyuan on 2017/9/4.
*/
class Evolution: Goods() {
companion object {
private const val serialVersionUID: Long = Field.SERVER_VERSION
}
override var desc: String = "可以让伊布在亲密度不满的情况下也可以进化"
override var name: String ="进化石"
override var price: Long = 1000000L
override fun canLocalSell(): Boolean {
return false
}
} | dataModel/src/cn/luo/yuan/maze/model/goods/types/Evolution.kt | 2940245820 |
/**
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.5.1-pre.0
* Contact: [email protected]
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import com.squareup.moshi.Json
/**
*
*
* @param propertyClass
* @param timestamp
* @param path
* @param propertySize
*/
data class DiskSpaceMonitorDescriptorDiskSpace (
@Json(name = "_class")
val propertyClass: kotlin.String? = null,
@Json(name = "timestamp")
val timestamp: kotlin.Int? = null,
@Json(name = "path")
val path: kotlin.String? = null,
@Json(name = "size")
val propertySize: kotlin.Int? = null
)
| clients/kotlin/generated/src/main/kotlin/org/openapitools/client/models/DiskSpaceMonitorDescriptorDiskSpace.kt | 3736021137 |
/*
* Copyright @ 2018 - Present, 8x8 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 org.jitsi.nlj.transform.node.incoming
import org.jitsi.nlj.PacketInfo
import org.jitsi.nlj.stats.NodeStatsBlock
import org.jitsi.nlj.transform.node.TransformerNode
import org.jitsi.rtp.rtp.RtpPacket
import org.jitsi.utils.LRUCache
import java.util.TreeMap
/**
* A node which drops packets with SSRC and sequence number pairs identical to ones
* that have previously been seen.
*
* (Since SRTP also has anti-replay protection, the normal case where duplicates
* will occur is after the [RtxHandler], since duplicate packets are sent over RTX for probing.)
*/
class DuplicateTermination() : TransformerNode("Duplicate termination") {
private val replayContexts: MutableMap<Long, MutableSet<Int>> = TreeMap()
private var numDuplicatePacketsDropped = 0
override fun transform(packetInfo: PacketInfo): PacketInfo? {
val rtpPacket = packetInfo.packetAs<RtpPacket>()
val replayContext = replayContexts.computeIfAbsent(rtpPacket.ssrc) {
LRUCache.lruSet(1500, true)
}
if (!replayContext.add(rtpPacket.sequenceNumber)) {
numDuplicatePacketsDropped++
return null
}
return packetInfo
}
override fun getNodeStats(): NodeStatsBlock = super.getNodeStats().apply {
addNumber("num_duplicate_packets_dropped", numDuplicatePacketsDropped)
}
override fun trace(f: () -> Unit) = f.invoke()
}
| jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/node/incoming/DuplicateTermination.kt | 3067636263 |
package org.meganekkovr.ovrjni
class OVRApp private constructor(private val appPtr: Long) {
fun recenterYaw(showBlack: Boolean) {
recenterYaw(appPtr, showBlack)
}
fun showSystemUI(type: Int) {
showSystemUI(appPtr, type)
}
fun setClockLevels(cpuLevel: Int, gpuLevel: Int) {
setClockLevels(appPtr, cpuLevel, gpuLevel)
}
private external fun recenterYaw(appPtr: Long, showBlack: Boolean)
private external fun showSystemUI(appPtr: Long, type: Int)
private external fun setClockLevels(appPtr: Long, cpuLevel: Int, gpuLevel: Int)
companion object {
//-----------------------------------------------------------------
// System Activity Commands
//-----------------------------------------------------------------
const val SYSTEM_UI_GLOBAL_MENU = 0
const val SYSTEM_UI_CONFIRM_QUIT_MENU = 1
const val SYSTEM_UI_KEYBOARD_MENU = 2
const val SYSTEM_UI_FILE_DIALOG_MENU = 3
@JvmStatic
lateinit var instance: OVRApp
@Synchronized
@JvmStatic
internal fun init(appPtr: Long) {
instance = OVRApp(appPtr)
}
}
}
| library/src/main/java/org/meganekkovr/ovrjni/OVRApp.kt | 2332632017 |
package com.koenv.adventofcode
import com.koenv.adventofcode.Day5.toHexString
import java.security.MessageDigest
object Day14 {
val md5 = MessageDigest.getInstance("MD5")
fun findIndexOfOneTimePadKey(salt: String, padKey: Int, part2: Boolean): Int {
val hashes = hashMapOf<Int, CharArray>()
val keys = arrayListOf<CharArray>()
var i = 0
while (keys.size < padKey) {
val digest: CharArray
if (i in hashes) {
digest = hashes[i]!!
} else {
digest = generateHash(salt, i, part2)
hashes[i] = digest
}
check@ for (j in 2..digest.size - 1) {
if (digest[j] == digest[j - 1] && digest[j] == digest[j - 2]) {
for (k in i + 1..i + 1000) {
val hash: CharArray
if (k in hashes) {
hash = hashes[k]!!
} else {
hash = generateHash(salt, k, part2)
hashes[k] = hash
}
for (l in 4..hash.size - 1) {
if (digest[j] == hash[l] && hash[l] == hash[l - 1] && hash[l] == hash[l - 2]
&& hash[l] == hash[l - 3] && hash[l] == hash[l - 4]) {
keys.add(digest)
break@check
}
}
}
break@check // only consider the first one
}
}
i++
}
return i - 1
}
private fun generateHash(salt: String, i: Int, part2: Boolean): CharArray {
var hashes = 1
if (part2) {
hashes = 2017
}
var digest = salt + i
for (j in 1..hashes) {
digest = md5.digest(digest.toByteArray()).toHexString().toLowerCase()
}
return digest.toCharArray()
}
} | 2016/src/main/kotlin/com/koenv/adventofcode/Day14.kt | 1244159941 |
package com.fastaccess.ui.modules.editor
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.transition.TransitionManager
import androidx.fragment.app.FragmentManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.GONE
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ListView
import butterknife.BindView
import butterknife.OnClick
import com.evernote.android.state.State
import com.fastaccess.R
import com.fastaccess.data.dao.EditReviewCommentModel
import com.fastaccess.data.dao.model.Comment
import com.fastaccess.helper.*
import com.fastaccess.provider.emoji.Emoji
import com.fastaccess.provider.markdown.MarkDownProvider
import com.fastaccess.ui.base.BaseActivity
import com.fastaccess.ui.widgets.FontTextView
import com.fastaccess.ui.widgets.dialog.MessageDialogView
import com.fastaccess.ui.widgets.markdown.MarkDownLayout
import com.fastaccess.ui.widgets.markdown.MarkdownEditText
import java.util.*
/**
* Created by Kosh on 27 Nov 2016, 1:32 AM
*/
class EditorActivity : BaseActivity<EditorMvp.View, EditorPresenter>(), EditorMvp.View {
private var participants: ArrayList<String>? = null
private val sentFromFastHub: String by lazy {
"\n\n_" + getString(
R.string.sent_from_fasthub, AppHelper.getDeviceName(), "",
"[" + getString(R.string.app_name) + "](https://play.google.com/store/apps/details?id=com.fastaccess.github)"
) + "_"
}
@BindView(R.id.replyQuote) lateinit var replyQuote: LinearLayout
@BindView(R.id.replyQuoteText) lateinit var quote: FontTextView
@BindView(R.id.markDownLayout) lateinit var markDownLayout: MarkDownLayout
@BindView(R.id.editText) lateinit var editText: MarkdownEditText
@BindView(R.id.list_divider) lateinit var listDivider: View
@BindView(R.id.parentView) lateinit var parentView: View
@BindView(R.id.autocomplete) lateinit var mention: ListView
@State @BundleConstant.ExtraType var extraType: String? = null
@State var itemId: String? = null
@State var login: String? = null
@State var issueNumber: Int = 0
@State var commentId: Long = 0
@State var sha: String? = null
@State var reviewComment: EditReviewCommentModel? = null
override fun layout(): Int = R.layout.editor_layout
override fun isTransparent(): Boolean = false
override fun canBack(): Boolean = true
override fun isSecured(): Boolean = false
override fun providePresenter(): EditorPresenter = EditorPresenter()
@OnClick(R.id.replyQuoteText) internal fun onToggleQuote() {
TransitionManager.beginDelayedTransition((parentView as ViewGroup))
if (quote.maxLines == 3) {
quote.maxLines = Integer.MAX_VALUE
} else {
quote.maxLines = 3
}
quote.setCompoundDrawablesWithIntrinsicBounds(
0, 0,
if (quote.maxLines == 3) R.drawable.ic_arrow_drop_down
else R.drawable.ic_arrow_drop_up, 0
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
markDownLayout.markdownListener = this
setToolbarIcon(R.drawable.ic_clear)
if (savedInstanceState == null) {
onCreate()
}
invalidateOptionsMenu()
editText.initListView(mention, listDivider, participants)
editText.requestFocus()
}
override fun onSendResultAndFinish(commentModel: Comment, isNew: Boolean) {
hideProgress()
val intent = Intent()
intent.putExtras(
Bundler.start()
.put(BundleConstant.ITEM, commentModel)
.put(BundleConstant.EXTRA, isNew)
.end()
)
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onSendMarkDownResult() {
val intent = Intent()
intent.putExtras(Bundler.start().put(BundleConstant.EXTRA, editText.savedText).end())
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onSendReviewResultAndFinish(comment: EditReviewCommentModel, isNew: Boolean) {
hideProgress()
val intent = Intent()
intent.putExtras(
Bundler.start()
.put(BundleConstant.ITEM, comment)
.put(BundleConstant.EXTRA, isNew)
.end()
)
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.done_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.submit) {
if (PrefGetter.isSentViaEnabled()) {
val temp = editText.savedText.toString()
if (!temp.contains(sentFromFastHub)) {
editText.savedText = editText.savedText.toString() + sentFromFastHub
}
}
presenter.onHandleSubmission(editText.savedText, extraType, itemId, commentId, login, issueNumber, sha, reviewComment)
return true
}
return super.onOptionsItemSelected(item)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
if (menu.findItem(R.id.submit) != null) {
menu.findItem(R.id.submit).isEnabled = true
}
if (BundleConstant.ExtraType.FOR_RESULT_EXTRA.equals(extraType, ignoreCase = true)) {
menu.findItem(R.id.submit).setIcon(R.drawable.ic_done)
}
return super.onPrepareOptionsMenu(menu)
}
override fun showProgress(@StringRes resId: Int) {
super.showProgress(resId)
invalidateOptionsMenu()
}
override fun hideProgress() {
invalidateOptionsMenu()
super.hideProgress()
}
override fun onBackPressed() {
if (!InputHelper.isEmpty(editText)) {
ViewHelper.hideKeyboard(editText)
MessageDialogView.newInstance(
getString(R.string.close), getString(R.string.unsaved_data_warning),
Bundler.start()
.put("primary_extra", getString(R.string.discard))
.put("secondary_extra", getString(R.string.cancel))
.put(BundleConstant.EXTRA, true)
.end()
)
.show(supportFragmentManager, MessageDialogView.TAG)
return
}
super.onBackPressed()
}
override fun onMessageDialogActionClicked(isOk: Boolean, bundle: Bundle?) {
super.onMessageDialogActionClicked(isOk, bundle)
if (isOk && bundle != null) {
finish()
}
}
override fun onAppendLink(title: String?, link: String?, isLink: Boolean) {
markDownLayout.onAppendLink(title, link, isLink)
}
override fun getEditText(): EditText = editText
override fun getSavedText(): CharSequence? = editText.savedText
override fun fragmentManager(): FragmentManager = supportFragmentManager
@SuppressLint("SetTextI18n")
override fun onEmojiAdded(emoji: Emoji?) {
markDownLayout.onEmojiAdded(emoji)
}
private fun onCreate() {
val intent = intent
if (intent != null && intent.extras != null) {
val bundle = intent.extras
extraType = bundle?.getString(BundleConstant.EXTRA_TYPE)
reviewComment = bundle?.getParcelable(BundleConstant.REVIEW_EXTRA)
itemId = bundle?.getString(BundleConstant.ID)
login = bundle?.getString(BundleConstant.EXTRA_TWO)
if (extraType.equals(BundleConstant.ExtraType.EDIT_COMMIT_COMMENT_EXTRA, ignoreCase = true)
|| extraType.equals(BundleConstant.ExtraType.NEW_COMMIT_COMMENT_EXTRA, ignoreCase = true)
) {
sha = bundle?.getString(BundleConstant.EXTRA_THREE)
} else {
issueNumber = bundle?.getInt(BundleConstant.EXTRA_THREE) ?: -1
}
commentId = bundle?.getLong(BundleConstant.EXTRA_FOUR) ?: -1
val textToUpdate = bundle?.getString(BundleConstant.EXTRA)
if (!InputHelper.isEmpty(textToUpdate)) {
editText.setText(String.format("%s ", textToUpdate))
editText.setSelection(InputHelper.toString(editText).length)
}
if (bundle?.getString("message", "").isNullOrEmpty()) {
replyQuote.visibility = GONE
} else {
MarkDownProvider.setMdText(quote, bundle?.getString("message", ""))
}
participants = bundle?.getStringArrayList("participants")
}
}
} | app/src/main/java/com/fastaccess/ui/modules/editor/EditorActivity.kt | 3626419949 |
/*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.connection
import java.io.IOException
import java.net.ProtocolException
import java.net.SocketException
import okhttp3.EventListener
import okhttp3.Headers
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.internal.http.ExchangeCodec
import okhttp3.internal.http.RealResponseBody
import okhttp3.internal.ws.RealWebSocket
import okio.Buffer
import okio.ForwardingSink
import okio.ForwardingSource
import okio.Sink
import okio.Source
import okio.buffer
/**
* Transmits a single HTTP request and a response pair. This layers connection management and events
* on [ExchangeCodec], which handles the actual I/O.
*/
class Exchange(
internal val call: RealCall,
internal val eventListener: EventListener,
internal val finder: ExchangeFinder,
private val codec: ExchangeCodec
) {
/** True if the request body need not complete before the response body starts. */
internal var isDuplex: Boolean = false
private set
/** True if there was an exception on the connection to the peer. */
internal var hasFailure: Boolean = false
private set
internal val connection: RealConnection
get() = codec.carrier as? RealConnection ?: error("no connection for CONNECT tunnels")
internal val isCoalescedConnection: Boolean
get() = finder.routePlanner.address.url.host != codec.carrier.route.address.url.host
@Throws(IOException::class)
fun writeRequestHeaders(request: Request) {
try {
eventListener.requestHeadersStart(call)
codec.writeRequestHeaders(request)
eventListener.requestHeadersEnd(call, request)
} catch (e: IOException) {
eventListener.requestFailed(call, e)
trackFailure(e)
throw e
}
}
@Throws(IOException::class)
fun createRequestBody(request: Request, duplex: Boolean): Sink {
this.isDuplex = duplex
val contentLength = request.body!!.contentLength()
eventListener.requestBodyStart(call)
val rawRequestBody = codec.createRequestBody(request, contentLength)
return RequestBodySink(rawRequestBody, contentLength)
}
@Throws(IOException::class)
fun flushRequest() {
try {
codec.flushRequest()
} catch (e: IOException) {
eventListener.requestFailed(call, e)
trackFailure(e)
throw e
}
}
@Throws(IOException::class)
fun finishRequest() {
try {
codec.finishRequest()
} catch (e: IOException) {
eventListener.requestFailed(call, e)
trackFailure(e)
throw e
}
}
fun responseHeadersStart() {
eventListener.responseHeadersStart(call)
}
@Throws(IOException::class)
fun readResponseHeaders(expectContinue: Boolean): Response.Builder? {
try {
val result = codec.readResponseHeaders(expectContinue)
result?.initExchange(this)
return result
} catch (e: IOException) {
eventListener.responseFailed(call, e)
trackFailure(e)
throw e
}
}
fun responseHeadersEnd(response: Response) {
eventListener.responseHeadersEnd(call, response)
}
@Throws(IOException::class)
fun openResponseBody(response: Response): ResponseBody {
try {
val contentType = response.header("Content-Type")
val contentLength = codec.reportedContentLength(response)
val rawSource = codec.openResponseBodySource(response)
val source = ResponseBodySource(rawSource, contentLength)
return RealResponseBody(contentType, contentLength, source.buffer())
} catch (e: IOException) {
eventListener.responseFailed(call, e)
trackFailure(e)
throw e
}
}
@Throws(IOException::class)
fun trailers(): Headers = codec.trailers()
@Throws(SocketException::class)
fun newWebSocketStreams(): RealWebSocket.Streams {
call.timeoutEarlyExit()
return (codec.carrier as RealConnection).newWebSocketStreams(this)
}
fun webSocketUpgradeFailed() {
bodyComplete(-1L, responseDone = true, requestDone = true, e = null)
}
fun noNewExchangesOnConnection() {
codec.carrier.noNewExchanges()
}
fun cancel() {
codec.cancel()
}
/**
* Revoke this exchange's access to streams. This is necessary when a follow-up request is
* required but the preceding exchange hasn't completed yet.
*/
fun detachWithViolence() {
codec.cancel()
call.messageDone(this, requestDone = true, responseDone = true, e = null)
}
private fun trackFailure(e: IOException) {
hasFailure = true
codec.carrier.trackFailure(call, e)
}
fun <E : IOException?> bodyComplete(
bytesRead: Long,
responseDone: Boolean,
requestDone: Boolean,
e: E
): E {
if (e != null) {
trackFailure(e)
}
if (requestDone) {
if (e != null) {
eventListener.requestFailed(call, e)
} else {
eventListener.requestBodyEnd(call, bytesRead)
}
}
if (responseDone) {
if (e != null) {
eventListener.responseFailed(call, e)
} else {
eventListener.responseBodyEnd(call, bytesRead)
}
}
return call.messageDone(this, requestDone, responseDone, e)
}
fun noRequestBody() {
call.messageDone(this, requestDone = true, responseDone = false, e = null)
}
/** A request body that fires events when it completes. */
private inner class RequestBodySink(
delegate: Sink,
/** The exact number of bytes to be written, or -1L if that is unknown. */
private val contentLength: Long
) : ForwardingSink(delegate) {
private var completed = false
private var bytesReceived = 0L
private var closed = false
@Throws(IOException::class)
override fun write(source: Buffer, byteCount: Long) {
check(!closed) { "closed" }
if (contentLength != -1L && bytesReceived + byteCount > contentLength) {
throw ProtocolException(
"expected $contentLength bytes but received ${bytesReceived + byteCount}")
}
try {
super.write(source, byteCount)
this.bytesReceived += byteCount
} catch (e: IOException) {
throw complete(e)
}
}
@Throws(IOException::class)
override fun flush() {
try {
super.flush()
} catch (e: IOException) {
throw complete(e)
}
}
@Throws(IOException::class)
override fun close() {
if (closed) return
closed = true
if (contentLength != -1L && bytesReceived != contentLength) {
throw ProtocolException("unexpected end of stream")
}
try {
super.close()
complete(null)
} catch (e: IOException) {
throw complete(e)
}
}
private fun <E : IOException?> complete(e: E): E {
if (completed) return e
completed = true
return bodyComplete(bytesReceived, responseDone = false, requestDone = true, e = e)
}
}
/** A response body that fires events when it completes. */
internal inner class ResponseBodySource(
delegate: Source,
private val contentLength: Long
) : ForwardingSource(delegate) {
private var bytesReceived = 0L
private var invokeStartEvent = true
private var completed = false
private var closed = false
init {
if (contentLength == 0L) {
complete(null)
}
}
@Throws(IOException::class)
override fun read(sink: Buffer, byteCount: Long): Long {
check(!closed) { "closed" }
try {
val read = delegate.read(sink, byteCount)
if (invokeStartEvent) {
invokeStartEvent = false
eventListener.responseBodyStart(call)
}
if (read == -1L) {
complete(null)
return -1L
}
val newBytesReceived = bytesReceived + read
if (contentLength != -1L && newBytesReceived > contentLength) {
throw ProtocolException("expected $contentLength bytes but received $newBytesReceived")
}
bytesReceived = newBytesReceived
if (newBytesReceived == contentLength) {
complete(null)
}
return read
} catch (e: IOException) {
throw complete(e)
}
}
@Throws(IOException::class)
override fun close() {
if (closed) return
closed = true
try {
super.close()
complete(null)
} catch (e: IOException) {
throw complete(e)
}
}
fun <E : IOException?> complete(e: E): E {
if (completed) return e
completed = true
// If the body is closed without reading any bytes send a responseBodyStart() now.
if (e == null && invokeStartEvent) {
invokeStartEvent = false
eventListener.responseBodyStart(call)
}
return bodyComplete(bytesReceived, responseDone = true, requestDone = false, e = e)
}
}
}
| okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/Exchange.kt | 2260766283 |
package leakcanary
import android.database.sqlite.SQLiteDatabase
import androidx.test.platform.app.InstrumentationRegistry
import leakcanary.internal.activity.db.LeaksDbHelper
import leakcanary.internal.activity.db.ScopedLeaksDb
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
class DatabaseRule(private val updateDb: (SQLiteDatabase) -> Unit = {}) : TestRule {
override fun apply(
base: Statement,
description: Description
): Statement {
return object : Statement() {
override fun evaluate() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
context.deleteDatabase(LeaksDbHelper.DATABASE_NAME)
ScopedLeaksDb.writableDatabase(context, updateDb)
base.evaluate()
context.deleteDatabase(LeaksDbHelper.DATABASE_NAME)
}
}
}
}
| leakcanary-android-core/src/androidTest/java/leakcanary/DatabaseRule.kt | 617945342 |
/*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.main.launch
import androidx.fragment.app.Fragment
import jp.toastkid.lib.tab.TabUiFragment
/**
* @author toastkidjp
*/
class ElseCaseUseCase(
private val tabIsEmpty: () -> Boolean,
private val openNewTab: () -> Unit,
private val findCurrentFragment: () -> Fragment?,
private val replaceToCurrentTab: (Boolean) -> Unit
) {
operator fun invoke() {
if (tabIsEmpty()) {
openNewTab()
return
}
// Add for re-creating activity.
val currentFragment = findCurrentFragment()
if (currentFragment is TabUiFragment || currentFragment == null) {
replaceToCurrentTab(false)
}
}
} | app/src/main/java/jp/toastkid/yobidashi/main/launch/ElseCaseUseCase.kt | 2920238568 |
package karballo
import karballo.bitboard.AttacksInfo
import karballo.bitboard.BitboardUtils
import karballo.util.JvmPlatformUtils
import karballo.util.Utils
import org.junit.Assert.assertEquals
import org.junit.Test
class AttacksInfoTest {
constructor() {
Utils.instance = JvmPlatformUtils()
}
@Test
fun testPinnedBishop() {
val b = Board()
b.fen = "3k4/3r4/8/3B4/2P5/8/8/3K4 b - - 1 1"
println(b)
val ai = AttacksInfo()
ai.build(b)
println(BitboardUtils.toString(ai.bishopAttacks[0]))
assertEquals(0, ai.bishopAttacks[0])
}
@Test
fun testPinnedRook() {
val b = Board()
b.fen = "3k4/3r4/8/3R4/2P5/8/8/3K4 b - - 1 1"
println(b)
val ai = AttacksInfo()
ai.build(b)
println(BitboardUtils.toString(ai.rookAttacks[0]))
assertEquals(5, BitboardUtils.popCount(ai.rookAttacks[0]).toLong())
}
@Test
fun testPinnedPawn() {
val b = Board()
b.fen = "3k4/8/2b5/3P4/8/8/8/7K b - - 1 1"
println(b)
val ai = AttacksInfo()
ai.build(b)
println(BitboardUtils.toString(ai.pawnAttacks[0]))
assertEquals(1, BitboardUtils.popCount(ai.pawnAttacks[0]).toLong())
}
} | karballo-jvm/src/test/kotlin/karballo/AttacksInfoTest.kt | 521462544 |
package net.dinkla.raytracer.samplers
import net.dinkla.raytracer.math.Point2D
import net.dinkla.raytracer.math.Point3D
import org.junit.jupiter.api.Test
class SamplerTest {
internal val NUM = 1000
internal var s = Sampler(PureRandom(), 100, 10)
@Test
@Throws(Exception::class)
fun testSampleUnitSquare() {
}
@Test
@Throws(Exception::class)
fun testSampleUnitDisk() {
// s.mapSamplesToUnitDisk();
// for (int i=0; i<NUM; i++) {
// Point2D p = s.sampleUnitDisk();
// assertTrue(0 <= p.x);
// assertTrue(p.x < 1);
// assertTrue(0 <= p.y);
// assertTrue(p.y < 1);
// assertTrue(p.x + p.y < 1.42);
// }
}
@Test
@Throws(Exception::class)
fun testSampleHemisphere() {
}
@Test
@Throws(Exception::class)
fun testSampleSphere() {
// s.mapSamplesToSphere();
// for (int i=0; i<NUM; i++) {
// Point3D p = s.sampleSphere();
// assertTrue(-1 < p.x);
// assertTrue(p.x < 1);
// assertTrue(-1 < p.y);
// assertTrue(p.y < 1);
// assertTrue(0 <= p.z);
// assertTrue(p.z < 1);
// }
}
@Test
@Throws(Exception::class)
fun testSampleOneSet() {
}
}
| src/test/kotlin/net/dinkla/raytracer/samplers/SamplerTest.kt | 397007790 |
package com.example.android.eyebody.management.food
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
/**
* Created by ytw11 on 2017-11-19.
*/
class ActionReceiver : BroadcastReceiver() {
var menu:String=""
override fun onReceive(context:Context , intent:Intent) {
val dbHelper = DbHelper(context, "bill.db", null, 1)
val menu = intent.getStringExtra("menu")
val time=intent.getStringExtra("time")
val price=intent.getIntExtra("price",0)
when (menu) {
"meal" -> mealClicked(context)
"beverage" -> beverageClicked(context)
"dessert" -> dessertClicked(context)
"cancel" ->cancelClicked(context)
}
putValuesInDb(dbHelper,time,menu,price)
}
private fun mealClicked(context: Context) {
menu="meal"
Toast.makeText(context,menu, LENGTH_SHORT).show()
}
private fun beverageClicked(context: Context) {
menu="beverage"
Toast.makeText(context,menu, LENGTH_SHORT).show()
}
private fun dessertClicked(context: Context){
menu="dessert"
Toast.makeText(context,menu, LENGTH_SHORT).show()
}
private fun cancelClicked(context:Context){
menu="cancel"
Toast.makeText(context,menu, LENGTH_SHORT).show()
}
private fun putValuesInDb(dbHelper: DbHelper, time:String, menu:String, price:Int){
if(menu!="cancel"){
dbHelper.insert(time,menu,price)
}
}
} | EyeBody2/app/src/main/java/com/example/android/eyebody/management/food/ActionReceiver.kt | 376890921 |
package eu.kanade.tachiyomi.ui.base.controller
import android.app.Activity
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.annotation.StringRes
import androidx.appcompat.widget.SearchView
import androidx.viewbinding.ViewBinding
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import reactivecircus.flowbinding.appcompat.QueryTextEvent
import reactivecircus.flowbinding.appcompat.queryTextEvents
/**
* Implementation of the NucleusController that has a built-in ViewSearch
*/
abstract class SearchableNucleusController<VB : ViewBinding, P : BasePresenter<*>>
(bundle: Bundle? = null) : NucleusController<VB, P>(bundle) {
enum class SearchViewState { LOADING, LOADED, COLLAPSING, FOCUSED }
/**
* Used to bypass the initial searchView being set to empty string after an onResume
*/
private var currentSearchViewState: SearchViewState = SearchViewState.LOADING
/**
* Store the query text that has not been submitted to reassign it after an onResume, UI-only
*/
protected var nonSubmittedQuery: String = ""
/**
* To be called by classes that extend this subclass in onCreateOptionsMenu
*/
protected fun createOptionsMenu(
menu: Menu,
inflater: MenuInflater,
menuId: Int,
searchItemId: Int,
@StringRes queryHint: Int? = null,
restoreCurrentQuery: Boolean = true
) {
// Inflate menu
inflater.inflate(menuId, menu)
// Initialize search option.
val searchItem = menu.findItem(searchItemId)
val searchView = searchItem.actionView as SearchView
searchItem.fixExpand(onExpand = { invalidateMenuOnExpand() })
searchView.maxWidth = Int.MAX_VALUE
searchView.queryTextEvents()
.onEach {
val newText = it.queryText.toString()
if (newText.isNotBlank() or acceptEmptyQuery()) {
if (it is QueryTextEvent.QuerySubmitted) {
// Abstract function for implementation
// Run it first in case the old query data is needed (like BrowseSourceController)
onSearchViewQueryTextSubmit(newText)
presenter.query = newText
nonSubmittedQuery = ""
} else if ((it is QueryTextEvent.QueryChanged) && (presenter.query != newText)) {
nonSubmittedQuery = newText
// Abstract function for implementation
onSearchViewQueryTextChange(newText)
}
}
// clear the collapsing flag
setCurrentSearchViewState(SearchViewState.LOADED, SearchViewState.COLLAPSING)
}
.launchIn(viewScope)
val query = presenter.query
// Restoring a query the user had not submitted
if (nonSubmittedQuery.isNotBlank() and (nonSubmittedQuery != query)) {
searchItem.expandActionView()
searchView.setQuery(nonSubmittedQuery, false)
onSearchViewQueryTextChange(nonSubmittedQuery)
} else {
if (queryHint != null) {
searchView.queryHint = applicationContext?.getString(queryHint)
}
if (restoreCurrentQuery) {
// Restoring a query the user had submitted
if (query.isNotBlank()) {
searchItem.expandActionView()
searchView.setQuery(query, true)
searchView.clearFocus()
onSearchViewQueryTextChange(query)
onSearchViewQueryTextSubmit(query)
}
}
}
// Workaround for weird behavior where searchView gets empty text change despite
// query being set already, prevents the query from being cleared
binding.root.post {
setCurrentSearchViewState(SearchViewState.LOADED, SearchViewState.LOADING)
}
searchView.setOnQueryTextFocusChangeListener { _, hasFocus ->
if (hasFocus) {
setCurrentSearchViewState(SearchViewState.FOCUSED)
} else {
setCurrentSearchViewState(SearchViewState.LOADED, SearchViewState.FOCUSED)
}
}
searchItem.setOnActionExpandListener(
object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
onSearchMenuItemActionExpand(item)
return true
}
override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
val localSearchView = searchItem.actionView as SearchView
// if it is blank the flow event won't trigger so we would stay in a COLLAPSING state
if (localSearchView.toString().isNotBlank()) {
setCurrentSearchViewState(SearchViewState.COLLAPSING)
}
onSearchMenuItemActionCollapse(item)
return true
}
}
)
}
override fun onActivityResumed(activity: Activity) {
super.onActivityResumed(activity)
// Until everything is up and running don't accept empty queries
setCurrentSearchViewState(SearchViewState.LOADING)
}
private fun acceptEmptyQuery(): Boolean {
return when (currentSearchViewState) {
SearchViewState.COLLAPSING, SearchViewState.FOCUSED -> true
else -> false
}
}
private fun setCurrentSearchViewState(to: SearchViewState, from: SearchViewState? = null) {
// When loading ignore all requests other than loaded
if ((currentSearchViewState == SearchViewState.LOADING) && (to != SearchViewState.LOADED)) {
return
}
// Prevent changing back to an unwanted state when using async flows (ie onFocus event doing
// COLLAPSING -> LOADED)
if ((from != null) && (currentSearchViewState != from)) {
return
}
currentSearchViewState = to
}
/**
* Called by the SearchView since since the implementation of these can vary in subclasses
* Not abstract as they are optional
*/
protected open fun onSearchViewQueryTextChange(newText: String?) {
}
protected open fun onSearchViewQueryTextSubmit(query: String?) {
}
protected open fun onSearchMenuItemActionExpand(item: MenuItem?) {
}
protected open fun onSearchMenuItemActionCollapse(item: MenuItem?) {
}
/**
* During the conversion to SearchableNucleusController (after which I plan to merge its code
* into BaseController) this addresses an issue where the searchView.onTextFocus event is not
* triggered
*/
override fun invalidateMenuOnExpand(): Boolean {
return if (expandActionViewFromInteraction) {
activity?.invalidateOptionsMenu()
setCurrentSearchViewState(SearchViewState.FOCUSED) // we are technically focused here
false
} else {
true
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/SearchableNucleusController.kt | 981902756 |
package com.arellomobile.mvp.sample.kotlin
import com.arellomobile.mvp.MvpView
import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType
/**
* Date: 03.03.2016
* Time: 11:34
* @author Yuri Shmakov
*/
@StateStrategyType(AddToEndSingleStrategy::class)
interface DialogView : MvpView {
fun showDialog()
fun hideDialog()
} | sample-kotlin/src/main/kotlin/com/arellomobile/mvp/sample/kotlin/DialogView.kt | 2809223110 |
package io.sensefly.dynamodbtos3.commandline
import com.beust.jcommander.Parameter
import com.beust.jcommander.Parameters
import io.sensefly.dynamodbtos3.RestoreTable
import java.net.URI
@Parameters(commandDescription = "Restore DynamoDB table from json file hosted on S3.")
class RestoreCommand {
@Parameter(names = ["-t", "--table"], description = "Table to restore.", required = true, order = 0)
var table: String = ""
@Parameter(names = ["-s", "--source"], description = "S3 URI to a JSON backup file (s3://my-bucket/folder/my-table.json).", required = true, order = 1)
var source: URI? = null
@Parameter(names = ["-w", "--write-percentage"], description = "Write capacity percentage.", order = 3)
var writePercentage: Double = RestoreTable.DEFAULT_WRITE_PERCENTAGE
} | src/main/kotlin/io/sensefly/dynamodbtos3/commandline/RestoreCommand.kt | 2501992449 |
/*
* Copyright 2016, 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.zhuinden.simplestackexamplemvvm.data
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import java.util.*
/**
* Immutable model class for a Task.
*/
@Parcelize
data class Task(
val id: String?,
val title: String?,
val description: String?,
val completed: Boolean,
) : Parcelable {
val titleForList: String
get() = if (!title.isNullOrEmpty()) {
title
} else {
description
} ?: ""
val isCompleted: Boolean
get() = completed
val isActive: Boolean
get() = !completed
val isEmpty: Boolean
get() = title.isNullOrEmpty() && description.isNullOrEmpty()
companion object {
fun createNewActiveTask(title: String?, description: String?): Task {
return createTaskWithId(title, description, UUID.randomUUID().toString(), false)
}
fun createActiveTaskWithId(title: String?, description: String?, id: String?): Task {
return createTaskWithId(title, description, id, false)
}
fun createTaskWithId(title: String?, description: String?, id: String?, completed: Boolean): Task {
return Task(
id = id,
title = title,
description = description,
completed = completed
)
}
}
} | samples/advanced-samples/mvvm-sample/src/main/java/com/zhuinden/simplestackexamplemvvm/data/Task.kt | 3225836606 |
package com.eden.orchid.impl.compilers.sass
import com.caseyjbrooks.clog.Clog
import com.eden.common.util.EdenUtils
import com.eden.orchid.api.compilers.OrchidCompiler
import io.bit3.jsass.Compiler
import io.bit3.jsass.Options
import java.net.URI
import java.util.regex.Pattern
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SassCompiler
@Inject
constructor(
private val importer: SassImporter
) : OrchidCompiler(800) {
private val previousContextRegex = Pattern.compile("^//\\s*?CONTEXT=(.*?)$", Pattern.MULTILINE)
enum class CompilerSyntax(val ext: String) {
SASS("sass"), SCSS("scss"), UNSPECIFIED("")
}
override fun getSourceExtensions(): Array<String> {
return arrayOf(CompilerSyntax.SCSS.ext, CompilerSyntax.SASS.ext)
}
override fun getOutputExtension(): String {
return "css"
}
override fun compile(extension: String, input: String, data: Map<String, Any>): String {
val options = Options()
options.importers.add(importer)
var sourceContext = ""
val m = previousContextRegex.matcher(input)
if (m.find()) {
sourceContext = m.group(1)
}
if (extension == CompilerSyntax.SASS.ext) {
options.setIsIndentedSyntaxSrc(true)
} else {
options.setIsIndentedSyntaxSrc(false)
}
try {
return if (EdenUtils.isEmpty(sourceContext)) {
Compiler().compileString(input, options).css
} else {
Compiler().compileString(input, URI(sourceContext), URI(sourceContext), options).css
}
} catch (e: Exception) {
Clog.e("error compiling .{} content: {}", e, extension, e.message)
return ""
}
}
}
| OrchidCore/src/main/kotlin/com/eden/orchid/impl/compilers/sass/SassCompiler.kt | 1912811167 |
package com.example.view
import com.example.Styles
import tornadofx.*
class MainView : View("Hello TornadoFX") {
override val root = hbox {
label(title) {
addClass(Styles.heading)
}
}
}
| template-projects/tornadofx-gradle-project/src/main/kotlin/com/example/view/MainView.kt | 1970930588 |
/*
* Copyright (c) 2012-2017 Frederic Julian
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import net.fred.taskgame.services.AlarmRestoreOnRebootService
class BootCompleteReceiver : BroadcastReceiver() {
override fun onReceive(ctx: Context, intent: Intent) {
if (Intent.ACTION_BOOT_COMPLETED == intent.action) {
val service = Intent(ctx, AlarmRestoreOnRebootService::class.java)
ctx.startService(service)
}
}
}
| TaskGame/src/main/java/net/fred/taskgame/receivers/BootCompleteReceiver.kt | 3566557300 |
package uk.co.ourfriendirony.medianotifier.clients.rawg.game.search
import com.fasterxml.jackson.annotation.*
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder("id", "name", "slug")
class GameSearchGenre {
@get:JsonProperty("id")
@set:JsonProperty("id")
@JsonProperty("id")
var id: Int? = null
@get:JsonProperty("name")
@set:JsonProperty("name")
@JsonProperty("name")
var name: String? = null
@get:JsonProperty("slug")
@set:JsonProperty("slug")
@JsonProperty("slug")
var slug: String? = null
} | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/rawg/game/search/GameSearchGenre.kt | 1431679177 |
package com.github.shynixn.blockballtools.logic.service
import com.github.shynixn.blockballtools.contract.SonaTypeService
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
class ReleaseServiceImpl : SonaTypeService {
/**
* Searches the repository for the latest download link. Throws
* a [IllegalArgumentException] if not found.
*/
override fun findDownloadUrl(repository: String): String {
val downloadUrl =
"https://oss.sonatype.org/content/repositories/public/com/github/shynixn/blockball/blockball-bukkit-plugin/VERSION/blockball-bukkit-plugin-VERSION.jar"
val id = findId(repository)
val resultDownloadUrl = downloadUrl.replace("VERSION", id)
return resultDownloadUrl
}
/**
* Searches the repository for the latest id. Throws
* a [IllegalArgumentException] if not found.
*/
override fun findId(repositor: String): String {
val tableItem = Jsoup.connect(repositor).get().body().getElementsByTag("table")[0]
var latestId = "0.0.0"
for (item in (tableItem.childNodes()[1] as Element).children()) {
if (item.tagName() == "tr") {
val nameColumn = item.children()[0]
if (nameColumn.children().size > 0) {
val value = nameColumn.children()[0].html().replace("/", "")
if (value.toCharArray()[0].toString().toIntOrNull() != null && !value.endsWith("-SNAPSHOT")) {
val newNumbers = value.split("-")[0].split(".")
val oldNumbers = latestId.split("-")[0].split(".")
if (newNumbers[0].toInt() > oldNumbers[0].toInt()) {
latestId = value
}
if (newNumbers[0].toInt() == oldNumbers[0].toInt() && newNumbers[1].toInt() > oldNumbers[1].toInt()) {
latestId = value
}
if (newNumbers[0].toInt() == oldNumbers[0].toInt() && newNumbers[1].toInt() == oldNumbers[1].toInt() && newNumbers[2].toInt() > oldNumbers[2].toInt()) {
latestId = value
}
}
}
}
}
return latestId
}
} | blockball-tools/src/main/kotlin/com/github/shynixn/blockballtools/logic/service/ReleaseServiceImpl.kt | 2231669087 |
package com.commit451.gitlab.api
import android.content.Intent
import android.widget.Toast
import com.commit451.gitlab.App
import com.commit451.gitlab.R
import com.commit451.gitlab.activity.LoginActivity
import com.commit451.gitlab.data.Prefs
import com.commit451.gitlab.model.Account
import com.commit451.gitlab.util.ThreadUtil
import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
import timber.log.Timber
import java.io.IOException
/**
* If it detects a 401, redirect the user to the login screen, clearing activity the stack.
* Kinda a weird global way of forcing the user to the login screen if their auth has expired
*/
class OpenSignInAuthenticator(private val account: Account) : Authenticator {
@Throws(IOException::class)
override fun authenticate(route: Route?, response: Response): Request? {
val url = response.request.url
var cleanUrl = url.toString().toLowerCase()
cleanUrl = cleanUrl.substring(cleanUrl.indexOf(':'))
var cleanServerUrl = account.serverUrl.toString().toLowerCase()
cleanServerUrl = cleanServerUrl.substring(cleanServerUrl.indexOf(':'))
//Ensure that we only check urls of the gitlab instance
if (cleanUrl.startsWith(cleanServerUrl)) {
//Special case for if someone just put in their username or password wrong
if ("session" != url.pathSegments[url.pathSegments.size - 1]) {
//Off the background thread
Timber.wtf(RuntimeException("Got a 401 and showing sign in for url: " + response.request.url))
ThreadUtil.postOnMainThread(Runnable {
//Remove the account, so that the user can sign in again
Prefs.removeAccount(account)
Toast.makeText(App.get(), R.string.error_401, Toast.LENGTH_LONG)
.show()
val intent = LoginActivity.newIntent(App.get())
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
App.get().startActivity(intent)
})
}
}
return null
}
}
| app/src/main/java/com/commit451/gitlab/api/OpenSignInAuthenticator.kt | 2571696254 |
package com.charlag.promind.core.apps
import android.content.Context
import android.content.pm.PackageManager
import com.charlag.promind.util.toBitmap
/**
* Created by charlag on 12/06/2017.
*/
internal class AppsSourceImpl(context: Context) : AppsSource {
private val packageManager = context.packageManager
override fun listAllApps(): List<AppsSource.AppData> =
packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
.filter { !it.packageName.startsWith("com.android") }
.fold(listOf()) { l, app ->
val title = packageManager.getApplicationLabel(app)?.toString() ?:
return@fold l
val icon = packageManager.getApplicationIcon(app)
l + AppsSource.AppData(title, app.packageName, icon.toBitmap())
}
} | app/src/main/java/com/charlag/promind/core/apps/AppsSourceImpl.kt | 369954116 |
package io.noties.markwon.app.utils
import android.content.Context
import io.noties.markwon.app.sample.Sample
import io.noties.markwon.sample.annotations.MarkwonArtifact
import java.io.InputStream
val MarkwonArtifact.displayName: String
get() = "@${artifactName()}"
val String.tagDisplayName: String
get() = "#$this"
private const val SAMPLE_PREFIX = "io.noties.markwon.app."
fun Sample.readCode(context: Context): Sample.Code {
val assets = context.assets
// keep sample and nested directories
val path = javaClassName
.removePrefix(SAMPLE_PREFIX)
.replace('.', '/')
fun obtain(path: String): InputStream? {
return try {
assets.open(path)
} catch (t: Throwable) {
null
}
}
// now, we have 2 possibilities -> Kotlin or Java
var language: Sample.Language = Sample.Language.KOTLIN
var stream = obtain("$path.kt")
if (stream == null) {
language = Sample.Language.JAVA
stream = obtain("$path.java")
}
if (stream == null) {
throw IllegalStateException("Cannot obtain sample file at path: $path")
}
val code = stream.readStringAndClose()
return Sample.Code(language, code)
}
fun loadReadMe(context: Context): String {
val stream = context.assets.open("README.md")
return stream.readStringAndClose()
} | app-sample/src/main/java/io/noties/markwon/app/utils/SampleUtilsKt.kt | 1763781038 |
// Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.flex.intentions
import com.intellij.BundleBase
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import java.lang.ref.Reference
import java.lang.ref.SoftReference
import java.util.*
class FlexIntentionsBundle : BundleBase() {
companion object {
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String {
return BundleBase.message(bundle, key, *params)
}
private var ourBundle: Reference<ResourceBundle>? = null
@NonNls
internal const val BUNDLE = "com.vladsch.md.nav.flex.localization.intentions"
internal val bundle: ResourceBundle
get() {
var bundle = com.intellij.reference.SoftReference.dereference(ourBundle)
if (bundle == null) {
bundle = ResourceBundle.getBundle(BUNDLE)
ourBundle = SoftReference(bundle)
}
return bundle as ResourceBundle
}
}
}
| src/main/java/com/vladsch/md/nav/flex/intentions/FlexIntentionsBundle.kt | 3975043810 |
package io.noties.markwon.app.samples.image
import androidx.recyclerview.widget.LinearLayoutManager
import coil.Coil
import coil.request.Disposable
import coil.request.ImageRequest
import coil.transform.RoundedCornersTransformation
import io.noties.markwon.Markwon
import io.noties.markwon.app.R
import io.noties.markwon.app.sample.ui.MarkwonRecyclerViewSample
import io.noties.markwon.image.AsyncDrawable
import io.noties.markwon.image.coil.CoilImagesPlugin
import io.noties.markwon.recycler.MarkwonAdapter
import io.noties.markwon.sample.annotations.MarkwonArtifact
import io.noties.markwon.sample.annotations.MarkwonSampleInfo
import io.noties.markwon.sample.annotations.Tag
@MarkwonSampleInfo(
id = "20200803132053",
title = "Coil inside RecyclerView",
description = "Display images via Coil plugin in `RecyclerView`",
artifacts = [MarkwonArtifact.IMAGE_COIL, MarkwonArtifact.RECYCLER],
tags = [Tag.rendering, Tag.recyclerView, Tag.image]
)
class CoilRecyclerViewSample : MarkwonRecyclerViewSample() {
override fun render() {
val md = """
# H1
## H2
### H3
#### H4
##### H5
> a quote
+ one
- two
* three
1. one
1. two
1. three
---
# Images

""".trimIndent()
val markwon = Markwon.builder(context)
.usePlugin(CoilImagesPlugin.create(
object : CoilImagesPlugin.CoilStore {
override fun load(drawable: AsyncDrawable): ImageRequest {
return ImageRequest.Builder(context)
.transformations(
RoundedCornersTransformation(14F)
)
.data(drawable.destination)
.placeholder(R.drawable.ic_image_gray_24dp)
.build()
}
override fun cancel(disposable: Disposable) {
disposable.dispose()
}
},
Coil.imageLoader(context)))
.build()
val adapter = MarkwonAdapter.createTextViewIsRoot(R.layout.adapter_node)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = adapter
adapter.setMarkdown(markwon, md)
adapter.notifyDataSetChanged()
}
} | app-sample/src/main/java/io/noties/markwon/app/samples/image/CoilRecyclerViewSample.kt | 645751114 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.template
import com.intellij.openapi.actionSystem.IdeActions
import org.intellij.lang.annotations.Language
import org.rust.lang.RsTestBase
class RsLiveTemplatesTest : RsTestBase() {
override val dataPath = "org/rust/ide/template/fixtures"
fun testStructField() = expandSnippet("""
struct S {
f/*caret*/
}
""", """
struct S {
foo: u32,
}
""")
fun testPrint() = expandSnippet("""
fn main() {
p/*caret*/
}
""", """
fn main() {
println!("");
}
""")
fun testAttribute() = noSnippet("""
#[macro/*caret*/]
extern crate std;
fn main() { }
""")
fun testComment() = noSnippet("""
fn main() {
// p/*caret*/
}
""")
fun testDocComment() = noSnippet("""
/// p/*caret*/
fn f() {}
""")
fun testStringLiteral() = noSnippet("""
fn main() {
let _ = "p/*caret*/";
}
""")
fun testRawStringLiteral() = noSnippet("""
fn main() {
let _ = r##"p/*caret*/"##;
}
""")
fun testByteStringLiteral() = noSnippet("""
fn main() {
let _ = b"p/*caret*/";
}
""")
fun testFieldExpression() = noSnippet("""
fn main() {
let _ = foo.p/*caret*/
}
""")
fun testMethodExpression() = noSnippet("""
fn main() {
let _ = foo.p/*caret*/()
}
""")
fun testPath() = noSnippet("""
fn main() {
let _ = foo::p/*caret*/
}
""")
val indent = " "
fun `test module level context available in file`() = expandSnippet("""
tfn/*caret*/
""", """
#[test]
fn /*caret*/() {
$indent
}
""")
fun `test module level context not available in function`() = noSnippet("""
fn foo() {
x.tfn/*caret*/
}
""")
fun `test main is available in file`() = expandSnippet("""
main/*caret*/
""", """
fn main() {
$indent/*caret*/
}
""")
private fun expandSnippet(@Language("Rust") before: String, @Language("Rust") after: String) =
checkByText(before.trimIndent(), after.trimIndent()) {
myFixture.performEditorAction(IdeActions.ACTION_EXPAND_LIVE_TEMPLATE_BY_TAB)
}
private fun noSnippet(@Language("Rust") code: String) = expandSnippet(code, code)
}
| src/test/kotlin/org/rust/ide/template/RsLiveTemplatesTest.kt | 3342052122 |
package com.github.dirkraft.cartograph
import java.sql.Connection
import java.sql.Statement
internal fun <R> Connection.execute(
sql: String, args: Collection<Any> = emptyList<Any>(), result: Statement.() -> R): R {
if (args.isEmpty()) {
val st = createStatement()
st.execute(sql)
return result(st)
} else {
// I don't know about this. This ensures some jdbc drivers to set up the statement to return generated keys
// (e.g. postgresql JDBC driver). It is highly convenient to work this way by default so it gets to go here.
val isInsOrUpd = sql.trim().substring(0, 6).toLowerCase().let { it == "insert" || it == "update" }
val ps = if (isInsOrUpd) {
prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
} else {
prepareStatement(sql)
}
ps.mapIn(args)
ps.execute()
return result(ps)
}
} | cartograph/src/main/kotlin/com/github/dirkraft/cartograph/connection_ext.kt | 4094759711 |
/*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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
* HOLDER 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 no.nordicsemi.android.service
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | lib_service/src/test/java/no/nordicsemi/android/service/ExampleUnitTest.kt | 1206719904 |
package net.tlalka.fiszki.model.dto.json
import com.google.gson.annotations.SerializedName
import net.tlalka.fiszki.model.types.LevelType
class LessonDto {
@SerializedName("name")
var name: WordDto = WordDto()
@SerializedName("level")
var level: LevelType = LevelType.BEGINNER
@SerializedName("words")
var words: List<WordDto> = ArrayList()
}
| app/src/main/kotlin/net/tlalka/fiszki/model/dto/json/LessonDto.kt | 226591966 |
package org.http4k.security.openid
import dev.forkhandles.result4k.Result
import dev.forkhandles.result4k.Success
import org.http4k.security.Nonce
import org.http4k.security.OAuthCallbackError
interface IdTokenConsumer {
fun nonceFromIdToken(idToken: IdToken): Nonce?
fun consumeFromAuthorizationResponse(idToken: IdToken): Result<Unit, OAuthCallbackError.InvalidIdToken>
fun consumeFromAccessTokenResponse(idToken: IdToken): Result<Unit, OAuthCallbackError.InvalidIdToken>
companion object {
val NoOp = object : IdTokenConsumer {
override fun nonceFromIdToken(idToken: IdToken): Nonce? = null
override fun consumeFromAccessTokenResponse(idToken: IdToken) = Success(Unit)
override fun consumeFromAuthorizationResponse(idToken: IdToken) = Success(Unit)
}
}
}
| http4k-security/oauth/src/main/kotlin/org/http4k/security/openid/IdTokenConsumer.kt | 4124274278 |
package org.http4k.core
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.jupiter.api.Test
import java.util.UUID
class RequestContextTest {
@Test
fun `can set and get a typed value from a RequestContext`() {
val requestContext = RequestContext(UUID.randomUUID())
requestContext["foo"] = 123
assertThat(requestContext.get<Int>("foo"), equalTo(123))
}
@Test
fun `updating a value to null removes it`() {
val requestContext = RequestContext(UUID.randomUUID())
requestContext["foo"] = 123
requestContext["foo"] = null
assertThat(requestContext["foo"], absent<Int>())
}
@Test
fun `returns null when missing`() {
assertThat(RequestContext(UUID.randomUUID())["foo"], absent<Int>())
}
}
| http4k-core/src/test/kotlin/org/http4k/core/RequestContextTest.kt | 834578110 |
/*
* 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
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import com.github.android.removeduplicates.BuildConfig
import com.github.android.removeduplicates.R
/**
* Main spinner items.
*
* @author moshe.w
*/
enum class MainSpinnerItem(
val type: DuplicateItemType,
@StringRes val label: Int,
@DrawableRes val icon: Int,
val isVisible: Boolean = true
) {
ALARMS(DuplicateItemType.ALARM, R.string.item_alarms, R.drawable.ic_alarm),
BOOKMARKS(DuplicateItemType.BOOKMARK, R.string.item_bookmarks, R.drawable.ic_bookmark),
CALENDARS(DuplicateItemType.CALENDAR, R.string.item_calendar, R.drawable.ic_event),
CALL_LOGS(
DuplicateItemType.CALL_LOG,
R.string.item_call_log,
R.drawable.ic_call,
BuildConfig.FEATURE_CALL_LOGS
),
CONTACTS(DuplicateItemType.CONTACT, R.string.item_contacts, R.drawable.ic_contacts),
MESSAGES(
DuplicateItemType.MESSAGE,
R.string.item_messages,
R.drawable.ic_message,
BuildConfig.FEATURE_SMS
)
}
| duplicates-android/app/src/main/java/com/github/duplicates/MainSpinnerItem.kt | 444854903 |
package org.http4k.client
import org.http4k.core.BodyMode
import org.http4k.core.HttpHandler
import org.http4k.server.ServerConfig
import org.http4k.server.SunHttp
import org.http4k.streaming.StreamingContract
class Apache4ClientStreamingContractTest : StreamingContract() {
override fun serverConfig(): ServerConfig = SunHttp(0)
override fun createClient(): HttpHandler = Apache4Client(requestBodyMode = BodyMode.Stream, responseBodyMode = BodyMode.Stream)
}
| http4k-client/apache4/src/test/kotlin/org/http4k/client/Apache4ClientStreamingContractTest.kt | 2965938266 |
package io.github.matthewcmckenna.mileage
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("io.github.matthewcmckenna.mileage", appContext.packageName)
}
}
| app/src/androidTest/java/io/github/matthewcmckenna/mileage/ExampleInstrumentedTest.kt | 1355321581 |
package org.http4k.aws
import org.http4k.core.Request
import org.http4k.core.Uri
import org.http4k.core.toParameters
import org.http4k.filter.CanonicalPayload
import org.http4k.urlEncoded
import java.util.Locale.getDefault
internal data class AwsCanonicalRequest(val value: String, val signedHeaders: String, val payloadHash: String) {
companion object {
fun of(request: Request, payload: CanonicalPayload): AwsCanonicalRequest {
val signedHeaders = request.signedHeaders()
val canonical = request.method.name +
"\n" +
request.uri.normalisedPath() +
"\n" +
request.canonicalQueryString() +
"\n" +
request.canonicalHeaders() +
"\n\n" +
signedHeaders +
"\n" +
payload.hash
return AwsCanonicalRequest(canonical, signedHeaders, payload.hash)
}
private fun Request.signedHeaders(): String =
headers.map { it.first.lowercase(getDefault()) }.sorted().joinToString(";")
private fun Request.canonicalHeaders(): String = headers
.map { it.first.lowercase(getDefault()) to it.second?.replace("\\s+", " ")?.trim() }
.map { it.first + ":" + it.second }
.sorted()
.joinToString("\n")
private fun Request.canonicalQueryString(): String =
uri.query.toParameters()
.map { (first, second) -> first.urlEncoded() + "=" + second?.urlEncoded().orEmpty() }
.sorted()
.joinToString("&")
private fun Uri.normalisedPath() = if (path.isBlank()) "/" else path.split("/").joinToString("/") { it.urlEncoded() }
}
}
| http4k-aws/src/main/kotlin/org/http4k/aws/AwsCanonicalRequest.kt | 801839182 |
package cs.ut.jobs
import cs.ut.configuration.ConfigFetcher
import cs.ut.exceptions.Left
import cs.ut.exceptions.NirdizatiRuntimeException
import cs.ut.exceptions.Right
import cs.ut.exceptions.perform
import cs.ut.jobs.UserRightsJob.Companion.updateACL
import cs.ut.json.JSONHandler
import cs.ut.json.JSONService
import cs.ut.json.JobInformation
import cs.ut.json.TrainingConfiguration
import cs.ut.providers.Dir
import cs.ut.providers.DirectoryConfiguration
import cs.ut.util.NirdizatiTranslator
import java.io.File
import java.time.Instant
import java.util.Date
class SimulationJob(
val configuration: TrainingConfiguration,
val logFile: File,
val owner: String,
id: String = ""
) : Job(id) {
private var process: Process? = null
private val configNode by ConfigFetcher("userPreferences")
val date: Date by lazy { Date.from(Instant.parse(startTime)) }
override fun preProcess() {
log.debug("Generating training parameters for job $this")
configuration.info = JobInformation(owner, logFile.absolutePath, startTime)
JSONHandler().writeToFile(configuration, id, Dir.TRAIN_DIR).apply {
updateACL(this)
}
}
override fun execute() {
val python: String = DirectoryConfiguration.dirPath(Dir.PYTHON)
val parameters = mutableListOf<String>()
if (configNode.isEnabled()) {
parameters.add("sudo")
parameters.add("-u")
parameters.add(configNode.valueWithIdentifier("userName").value)
}
parameters.add(python)
parameters.add(TRAIN_PY)
parameters.add(id)
val execRes = perform {
val pb = ProcessBuilder(parameters)
pb.inheritIO()
pb.directory(File(DirectoryConfiguration.dirPath(Dir.CORE_DIR)))
val env = pb.environment()
env["PYTHONPATH"] = DirectoryConfiguration.dirPath(Dir.SCRIPT_DIR)
log.debug("Script call: ${pb.command()}")
process = pb.start()
log.debug("Waiting for process completion")
process!!.waitFor()
log.debug("Script finished running...")
val file = File(DirectoryConfiguration.dirPath(Dir.PKL_DIR)).listFiles().firstOrNull { it.name.contains(this.id) }
log.debug(file)
if (file?.exists() == false) {
status = JobStatus.FAILED
throw NirdizatiRuntimeException("Script failed to write model to disk, job failed")
} else {
log.debug("Script exited successfully")
process?.destroy()
}
}
when (execRes) {
is Right -> log.debug("Operation completed successfully")
is Left -> throw NirdizatiRuntimeException("Script execution failed", execRes.error)
}
}
override fun postExecute() {
val config = JSONService.getTrainingConfig(id)
when (config) {
is Right -> this.configuration.evaluation = config.result.evaluation
is Left -> log.debug("Error occurred when fetching evaluation result", config.error)
}
}
override fun beforeInterrupt() {
log.debug("Process ${super.id} has been stopped by the user")
process?.destroy()
if (status != JobStatus.COMPLETED) {
log.debug("Job is not complete -> deleting training file")
File(DirectoryConfiguration.dirPath(Dir.TRAIN_DIR) + "$id.json").delete()
}
}
override fun onError() {
super.onError()
log.debug("Handling error for job $id")
val file = File(DirectoryConfiguration.dirPath(Dir.TRAIN_DIR) + "$id.json")
if (file.exists()) {
log.debug("File ${file.name} exists, deleting file")
val deleted = file.delete()
log.debug("File deleted successfully ? $deleted")
}
log.debug("Finished handling error for $id")
}
override fun isNotificationRequired() = true
override fun getNotificationMessage() = NirdizatiTranslator.localizeText("job.completed.simulation", this.toString())
override fun errorOccurred(): Boolean {
log.debug("Process exit value = ${process?.exitValue()}")
return process?.exitValue() != 0
}
override fun toString(): String {
return logFile.nameWithoutExtension +
"_" +
configuration.bucketing.parameter +
"_" +
configuration.encoding.parameter +
"_" +
configuration.learner.parameter +
"_" +
configuration.outcome.parameter +
".pkl"
}
private fun convertToNumber(value: String): Number =
try {
value.toInt()
} catch (e: NumberFormatException) {
value.toDouble()
}
companion object {
const val TRAIN_PY = "train.py"
}
} | src/main/kotlin/cs/ut/jobs/SimulationJob.kt | 534933917 |
package mal
import java.util.*
fun read(input: String?): MalType = read_str(input)
fun eval(_ast: MalType, _env: Env): MalType {
var ast = _ast
var env = _env
while (true) {
ast = macroexpand(ast, env)
if (ast is MalList) {
when ((ast.first() as? MalSymbol)?.value) {
"def!" -> return env.set(ast.nth(1) as MalSymbol, eval(ast.nth(2), env))
"let*" -> {
val childEnv = Env(env)
val bindings = ast.nth(1) as? ISeq ?: throw MalException("expected sequence as the first parameter to let*")
val it = bindings.seq().iterator()
while (it.hasNext()) {
val key = it.next()
if (!it.hasNext()) throw MalException("odd number of binding elements in let*")
childEnv.set(key as MalSymbol, eval(it.next(), childEnv))
}
env = childEnv
ast = ast.nth(2)
}
"fn*" -> return fn_STAR(ast, env)
"do" -> {
eval_ast(ast.slice(1, ast.count() - 1), env)
ast = ast.seq().last()
}
"if" -> {
val check = eval(ast.nth(1), env)
if (check !== NIL && check !== FALSE) {
ast = ast.nth(2)
} else if (ast.count() > 3) {
ast = ast.nth(3)
} else return NIL
}
"quote" -> return ast.nth(1)
"quasiquote" -> ast = quasiquote(ast.nth(1))
"defmacro!" -> return defmacro(ast, env)
"macroexpand" -> return macroexpand(ast.nth(1), env)
"try*" -> return try_catch(ast, env)
else -> {
val evaluated = eval_ast(ast, env) as ISeq
val firstEval = evaluated.first()
when (firstEval) {
is MalFnFunction -> {
ast = firstEval.ast
env = Env(firstEval.env, firstEval.params, evaluated.rest().seq())
}
is MalFunction -> return firstEval.apply(evaluated.rest())
else -> throw MalException("cannot execute non-function")
}
}
}
} else return eval_ast(ast, env)
}
}
fun eval_ast(ast: MalType, env: Env): MalType =
when (ast) {
is MalSymbol -> env.get(ast)
is MalList -> ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalVector -> ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a })
is MalHashMap -> ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a })
else -> ast
}
private fun fn_STAR(ast: MalList, env: Env): MalType {
val binds = ast.nth(1) as? ISeq ?: throw MalException("fn* requires a binding list as first parameter")
val params = binds.seq().filterIsInstance<MalSymbol>()
val body = ast.nth(2)
return MalFnFunction(body, params, env, { s: ISeq -> eval(body, Env(env, params, s.seq())) })
}
private fun is_pair(ast: MalType): Boolean = ast is ISeq && ast.seq().any()
private fun quasiquote(ast: MalType): MalType {
if (!is_pair(ast)) {
val quoted = MalList()
quoted.conj_BANG(MalSymbol("quote"))
quoted.conj_BANG(ast)
return quoted
}
val seq = ast as ISeq
var first = seq.first()
if ((first as? MalSymbol)?.value == "unquote") {
return seq.nth(1)
}
if (is_pair(first) && ((first as ISeq).first() as? MalSymbol)?.value == "splice-unquote") {
val spliced = MalList()
spliced.conj_BANG(MalSymbol("concat"))
spliced.conj_BANG((first as ISeq).nth(1))
spliced.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return spliced
}
val consed = MalList()
consed.conj_BANG(MalSymbol("cons"))
consed.conj_BANG(quasiquote(ast.first()))
consed.conj_BANG(quasiquote(MalList(seq.seq().drop(1).toCollection(LinkedList<MalType>()))))
return consed
}
private fun is_macro_call(ast: MalType, env: Env): Boolean {
val symbol = (ast as? MalList)?.first() as? MalSymbol ?: return false
val function = env.find(symbol) as? MalFunction ?: return false
return function.is_macro
}
private fun macroexpand(_ast: MalType, env: Env): MalType {
var ast = _ast
while (is_macro_call(ast, env)) {
val symbol = (ast as MalList).first() as MalSymbol
val function = env.find(symbol) as MalFunction
ast = function.apply(ast.rest())
}
return ast
}
private fun defmacro(ast: MalList, env: Env): MalType {
val macro = eval(ast.nth(2), env) as MalFunction
macro.is_macro = true
return env.set(ast.nth(1) as MalSymbol, macro)
}
private fun try_catch(ast: MalList, env: Env): MalType =
try {
eval(ast.nth(1), env)
} catch (e: Exception) {
val thrown = if (e is MalException) e else MalException(e.message)
val symbol = (ast.nth(2) as MalList).nth(1) as MalSymbol
val catchBody = (ast.nth(2) as MalList).nth(2)
val catchEnv = Env(env)
catchEnv.set(symbol, thrown)
eval(catchBody, catchEnv)
}
fun print(result: MalType) = pr_str(result, print_readably = true)
fun rep(input: String, env: Env): String =
print(eval(read(input), env))
fun main(args: Array<String>) {
val repl_env = Env()
ns.forEach({ it -> repl_env.set(it.key, it.value) })
repl_env.set(MalSymbol("*host-language*"), MalString("kotlin"))
repl_env.set(MalSymbol("*ARGV*"), MalList(args.drop(1).map({ it -> MalString(it) }).toCollection(LinkedList<MalType>())))
repl_env.set(MalSymbol("eval"), MalFunction({ a: ISeq -> eval(a.first(), repl_env) }))
rep("(def! not (fn* (a) (if a false true)))", repl_env)
rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))", repl_env)
rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", repl_env)
rep("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))", repl_env)
if (args.any()) {
rep("(load-file \"${args[0]}\")", repl_env)
return
}
while (true) {
val input = readline("user> ")
try {
println(rep(input, repl_env))
} catch (e: EofException) {
break
} catch (e: MalContinue) {
} catch (e: MalException) {
println("Error: " + e.message)
} catch (t: Throwable) {
println("Uncaught " + t + ": " + t.message)
t.printStackTrace()
}
}
}
| kotlin/src/mal/stepA_mal.kt | 1172943311 |
/*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.clientdetails
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.*
import android.widget.*
import androidx.appcompat.widget.PopupMenu
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.joanzapata.iconify.fonts.MaterialIcons
import com.joanzapata.iconify.widget.IconTextView
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.activity.pinpointclient.PinpointClientActivity
import com.mifos.mifosxdroid.adapters.LoanAccountsListAdapter
import com.mifos.mifosxdroid.adapters.SavingsAccountsListAdapter
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.MifosBaseFragment
import com.mifos.mifosxdroid.core.util.Toaster
import com.mifos.mifosxdroid.online.activate.ActivateFragment
import com.mifos.mifosxdroid.online.clientcharge.ClientChargeFragment
import com.mifos.mifosxdroid.online.clientidentifiers.ClientIdentifiersFragment
import com.mifos.mifosxdroid.online.datatable.DataTableFragment
import com.mifos.mifosxdroid.online.documentlist.DocumentListFragment
import com.mifos.mifosxdroid.online.loanaccount.LoanAccountFragment
import com.mifos.mifosxdroid.online.note.NoteFragment
import com.mifos.mifosxdroid.online.savingsaccount.SavingsAccountFragment
import com.mifos.mifosxdroid.online.sign.SignatureFragment
import com.mifos.mifosxdroid.online.surveylist.SurveyListFragment
import com.mifos.mifosxdroid.views.CircularImageView
import com.mifos.objects.accounts.ClientAccounts
import com.mifos.objects.accounts.savings.DepositType
import com.mifos.objects.client.Charges
import com.mifos.objects.client.Client
import com.mifos.utils.Constants
import com.mifos.utils.FragmentConstants
import com.mifos.utils.ImageLoaderUtils
import com.mifos.utils.Utils
import okhttp3.ResponseBody
import java.io.File
import java.io.FileOutputStream
import java.util.*
import javax.inject.Inject
class ClientDetailsFragment : MifosBaseFragment(), ClientDetailsMvpView {
var imgDecodableString: String? = null
private val TAG = ClientDetailsFragment::class.java.simpleName
var clientId = 0
var chargesList: MutableList<Charges> = ArrayList()
@JvmField
@BindView(R.id.tv_fullName)
var tv_fullName: TextView? = null
@JvmField
@BindView(R.id.tv_accountNumber)
var tv_accountNumber: TextView? = null
@JvmField
@BindView(R.id.tv_externalId)
var tv_externalId: TextView? = null
@JvmField
@BindView(R.id.tv_activationDate)
var tv_activationDate: TextView? = null
@JvmField
@BindView(R.id.tv_office)
var tv_office: TextView? = null
@JvmField
@BindView(R.id.tv_mobile_no)
var tvMobileNo: TextView? = null
@JvmField
@BindView(R.id.tv_group)
var tvGroup: TextView? = null
@JvmField
@BindView(R.id.iv_clientImage)
var iv_clientImage: CircularImageView? = null
@JvmField
@BindView(R.id.pb_imageProgressBar)
var pb_imageProgressBar: ProgressBar? = null
@JvmField
@BindView(R.id.row_account)
var rowAccount: TableRow? = null
@JvmField
@BindView(R.id.row_external)
var rowExternal: TableRow? = null
@JvmField
@BindView(R.id.row_activation)
var rowActivation: TableRow? = null
@JvmField
@BindView(R.id.row_office)
var rowOffice: TableRow? = null
@JvmField
@BindView(R.id.row_group)
var rowGroup: TableRow? = null
@JvmField
@BindView(R.id.row_staff)
var rowStaff: TableRow? = null
@JvmField
@BindView(R.id.row_loan)
var rowLoan: TableRow? = null
@JvmField
@BindView(R.id.tableRow_mobile_no)
var rowMobileNo: TableRow? = null
@JvmField
@BindView(R.id.ll_bottom_panel)
var llBottomPanel: LinearLayout? = null
@JvmField
@BindView(R.id.rl_client)
var rlClient: RelativeLayout? = null
@JvmField
@Inject
var mClientDetailsPresenter: ClientDetailsPresenter? = null
private lateinit var rootView: View
private var mListener: OnFragmentInteractionListener? = null
private val clientImageFile = File(Environment.getExternalStorageDirectory().toString() +
"/client_image.png")
private var accountAccordion: AccountAccordion? = null
private var isClientActive = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
if (arguments != null) {
clientId = requireArguments().getInt(Constants.CLIENT_ID)
}
setHasOptionsMenu(true)
checkPermissions()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_client_details, container, false)
ButterKnife.bind(this, rootView)
mClientDetailsPresenter!!.attachView(this)
inflateClientInformation()
return rootView
}
@OnClick(R.id.btn_activate_client)
fun onClickActivateClient() {
activateClient()
}
fun inflateClientInformation() {
mClientDetailsPresenter!!.loadClientDetailsAndClientAccounts(clientId)
}
override fun onAttach(activity: Activity) {
super.onAttach(activity)
mListener = try {
activity as OnFragmentInteractionListener
} catch (e: ClassCastException) {
throw ClassCastException(requireActivity().javaClass.simpleName + " must " +
"implement OnFragmentInteractionListener")
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
try {
// When an Image is picked
if (requestCode == UPLOAD_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK && null != data && data.data != null) {
// Get the Image from data
val selectedImage = data.data!!
val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
// Get the cursor
val cursor = requireActivity().applicationContext.contentResolver.query(
selectedImage,
filePathColumn, null, null, null)!!
// Move to first row
cursor.moveToFirst()
val columnIndex = cursor.getColumnIndex(filePathColumn[0])
imgDecodableString = cursor.getString(columnIndex)
cursor.close()
val pickedImage = BitmapFactory.decodeFile(imgDecodableString)
saveBitmap(clientImageFile, pickedImage)
uploadImage(clientImageFile)
} else if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
&& resultCode == Activity.RESULT_OK) {
uploadImage(clientImageFile)
} else {
Toaster.show(rootView, R.string.havent_picked_image,
Toast.LENGTH_LONG)
}
} catch (e: Exception) {
Toaster.show(rootView, e.toString(), Toast.LENGTH_LONG)
}
}
fun saveBitmap(file: File, mBitmap: Bitmap) {
try {
file.createNewFile()
var fOut: FileOutputStream? = null
fOut = FileOutputStream(file)
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut)
fOut.flush()
fOut.close()
} catch (exception: Exception) {
//Empty catch block to prevent crashing
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.clear()
if (isClientActive) {
menu.add(Menu.NONE, MENU_ITEM_DATA_TABLES, Menu.NONE, getString(R.string.more_info))
menu.add(Menu.NONE, MENU_ITEM_PIN_POINT, Menu.NONE, getString(R.string.pinpoint))
menu.add(Menu.NONE, MENU_ITEM_CLIENT_CHARGES, Menu.NONE, getString(R.string.charges))
menu.add(Menu.NONE, MENU_ITEM_ADD_SAVINGS_ACCOUNT, Menu.NONE, getString(R.string.savings_account))
menu.add(Menu.NONE, MENU_ITEM_ADD_LOAN_ACCOUNT, Menu.NONE,
getString(R.string.add_loan))
menu.add(Menu.NONE, MENU_ITEM_DOCUMENTS, Menu.NONE, getString(R.string.documents))
menu.add(Menu.NONE, MENU_ITEM_UPLOAD_SIGN, Menu.NONE, R.string.upload_sign)
menu.add(Menu.NONE, MENU_ITEM_IDENTIFIERS, Menu.NONE, getString(R.string.identifiers))
menu.add(Menu.NONE, MENU_ITEM_SURVEYS, Menu.NONE, getString(R.string.survey))
menu.add(Menu.NONE, MENU_ITEM_NOTE, Menu.NONE, getString(R.string.note))
}
super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
MENU_ITEM_DATA_TABLES -> loadClientDataTables()
MENU_ITEM_DOCUMENTS -> loadDocuments()
MENU_ITEM_UPLOAD_SIGN -> loadSignUpload()
MENU_ITEM_CLIENT_CHARGES -> loadClientCharges()
MENU_ITEM_ADD_SAVINGS_ACCOUNT -> addsavingsaccount()
MENU_ITEM_ADD_LOAN_ACCOUNT -> addloanaccount()
MENU_ITEM_IDENTIFIERS -> loadIdentifiers()
MENU_ITEM_PIN_POINT -> {
val i = Intent(activity, PinpointClientActivity::class.java)
i.putExtra(Constants.CLIENT_ID, clientId)
startActivity(i)
}
MENU_ITEM_SURVEYS -> loadSurveys()
MENU_ITEM_NOTE -> loadNotes()
}
return super.onOptionsItemSelected(item)
}
fun captureClientImage() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(clientImageFile))
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
}
private fun checkPermissions() {
if (ContextCompat.checkSelfPermission(requireActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
CHECK_PERMISSIONS)
}
}
fun uploadClientImage() {
// Create intent to Open Image applications like Gallery, Google Photos
val galleryIntent = Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
// Start the Intent
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(clientImageFile))
startActivityForResult(galleryIntent, UPLOAD_IMAGE_ACTIVITY_REQUEST_CODE)
}
/**
* A service to upload the image of the client.
*
* @param pngFile - PNG images supported at the moment
*/
private fun uploadImage(pngFile: File) {
mClientDetailsPresenter!!.uploadImage(clientId, pngFile)
}
override fun onDestroyView() {
super.onDestroyView()
mClientDetailsPresenter!!.detachView()
}
fun loadDocuments() {
val documentListFragment = DocumentListFragment.newInstance(Constants.ENTITY_TYPE_CLIENTS, clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, documentListFragment)
fragmentTransaction.commit()
}
fun loadNotes() {
val noteFragment = NoteFragment.newInstance(Constants.ENTITY_TYPE_CLIENTS, clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, noteFragment)
fragmentTransaction.commit()
}
fun loadClientCharges() {
val clientChargeFragment: ClientChargeFragment = ClientChargeFragment.Companion.newInstance(clientId,
chargesList)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, clientChargeFragment)
fragmentTransaction.commit()
}
fun loadIdentifiers() {
val clientIdentifiersFragment: ClientIdentifiersFragment = ClientIdentifiersFragment.Companion.newInstance(clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, clientIdentifiersFragment)
fragmentTransaction.commit()
}
fun loadSurveys() {
val surveyListFragment = SurveyListFragment.newInstance(clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, surveyListFragment)
fragmentTransaction.commit()
}
fun addsavingsaccount() {
val savingsAccountFragment = SavingsAccountFragment.newInstance(clientId, false)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, savingsAccountFragment)
fragmentTransaction.commit()
}
fun addloanaccount() {
val loanAccountFragment = LoanAccountFragment.newInstance(clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, loanAccountFragment)
fragmentTransaction.commit()
}
fun activateClient() {
val activateFragment = ActivateFragment.newInstance(clientId, Constants.ACTIVATE_CLIENT)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, activateFragment)
fragmentTransaction.commit()
}
fun loadClientDataTables() {
val loanAccountFragment = DataTableFragment.newInstance(Constants.DATA_TABLE_NAME_CLIENT, clientId)
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, loanAccountFragment)
fragmentTransaction.commit()
}
fun loadSignUpload() {
val fragment = SignatureFragment()
val bundle = Bundle()
bundle.putInt(Constants.CLIENT_ID, clientId)
fragment.arguments = bundle
val fragmentTransaction = requireActivity().supportFragmentManager
.beginTransaction()
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CLIENT_DETAILS)
fragmentTransaction.replace(R.id.container, fragment).commit()
}
override fun showProgressbar(show: Boolean) {
if (show) {
rlClient!!.visibility = View.GONE
showMifosProgressBar()
} else {
rlClient!!.visibility = View.VISIBLE
hideMifosProgressBar()
}
}
override fun showClientInformation(client: Client?) {
if (client != null) {
setToolbarTitle(getString(R.string.client) + " - " + client.displayName)
isClientActive = client.isActive
requireActivity().invalidateOptionsMenu()
if (!client.isActive) {
llBottomPanel!!.visibility = View.VISIBLE
}
tv_fullName!!.text = client.displayName
tv_accountNumber!!.text = client.accountNo
tvGroup!!.text = client.groupNames
tv_externalId!!.text = client.externalId
tvMobileNo!!.text = client.mobileNo
if (TextUtils.isEmpty(client.accountNo)) rowAccount!!.visibility = View.GONE
if (TextUtils.isEmpty(client.externalId)) rowExternal!!.visibility = View.GONE
if (TextUtils.isEmpty(client.mobileNo)) rowMobileNo!!.visibility = View.GONE
if (TextUtils.isEmpty(client.groupNames)) rowGroup!!.visibility = View.GONE
try {
val dateString = Utils.getStringOfDate(
client.activationDate)
tv_activationDate!!.text = dateString
if (TextUtils.isEmpty(dateString)) rowActivation!!.visibility = View.GONE
} catch (e: IndexOutOfBoundsException) {
Toast.makeText(activity, getString(R.string.error_client_inactive),
Toast.LENGTH_SHORT).show()
tv_activationDate!!.text = ""
}
tv_office!!.text = client.officeName
if (TextUtils.isEmpty(client.officeName)) rowOffice!!.visibility = View.GONE
if (client.isImagePresent) {
loadClientProfileImage()
} else {
iv_clientImage!!.setImageDrawable(
ResourcesCompat.getDrawable(resources, R.drawable.ic_launcher, null))
pb_imageProgressBar!!.visibility = View.GONE
}
iv_clientImage!!.setOnClickListener { view ->
val menu = PopupMenu(requireActivity(), view)
menu.menuInflater.inflate(R.menu.client_image_popup, menu
.menu)
if (!client.isImagePresent) {
menu.menu.findItem(R.id.client_image_remove).isVisible = false
}
menu.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.client_image_upload -> uploadClientImage()
R.id.client_image_capture -> captureClientImage()
R.id.client_image_remove -> mClientDetailsPresenter!!.deleteClientImage(clientId)
else -> Log.e("ClientDetailsFragment", "Unrecognized " +
"client " +
"image menu item")
}
true
}
menu.show()
}
//inflateClientsAccounts();
}
}
override fun showUploadImageSuccessfully(response: ResponseBody?, imagePath: String?) {
Toaster.show(rootView, R.string.client_image_updated)
iv_clientImage!!.setImageBitmap(BitmapFactory.decodeFile(imagePath))
}
override fun showUploadImageFailed(s: String?) {
Toaster.show(rootView, s)
loadClientProfileImage()
}
override fun showUploadImageProgressbar(b: Boolean) {
if (b) {
pb_imageProgressBar!!.visibility = View.VISIBLE
} else {
pb_imageProgressBar!!.visibility = View.GONE
}
}
fun loadClientProfileImage() {
pb_imageProgressBar!!.visibility = View.VISIBLE
ImageLoaderUtils.loadImage(activity, clientId, iv_clientImage)
pb_imageProgressBar!!.visibility = View.GONE
}
override fun showClientImageDeletedSuccessfully() {
Toaster.show(rootView, "Image deleted")
iv_clientImage!!.setImageDrawable(ContextCompat.getDrawable(requireActivity(), R.drawable.ic_launcher))
}
override fun showClientAccount(clientAccounts: ClientAccounts) {
// Proceed only when the fragment is added to the activity.
if (!isAdded) {
return
}
accountAccordion = AccountAccordion(activity)
if (clientAccounts.loanAccounts.size > 0) {
val section = AccountAccordion.Section.LOANS
val adapter = LoanAccountsListAdapter(requireActivity().applicationContext,
clientAccounts.loanAccounts)
section.connect(activity, adapter, AdapterView.OnItemClickListener { adapterView, view, i, l -> mListener!!.loadLoanAccountSummary(adapter.getItem(i).id) })
}
if (clientAccounts.nonRecurringSavingsAccounts.size > 0) {
val section = AccountAccordion.Section.SAVINGS
val adapter = SavingsAccountsListAdapter(requireActivity().applicationContext,
clientAccounts.nonRecurringSavingsAccounts)
section.connect(activity, adapter, AdapterView.OnItemClickListener { adapterView, view, i, l ->
mListener!!.loadSavingsAccountSummary(adapter.getItem(i).id,
adapter.getItem(i).depositType)
})
}
if (clientAccounts.recurringSavingsAccounts.size > 0) {
val section = AccountAccordion.Section.RECURRING
val adapter = SavingsAccountsListAdapter(requireActivity().applicationContext,
clientAccounts.recurringSavingsAccounts)
section.connect(activity, adapter, AdapterView.OnItemClickListener { adapterView, view, i, l ->
mListener!!.loadSavingsAccountSummary(adapter.getItem(i).id,
adapter.getItem(i).depositType)
})
}
}
override fun showFetchingError(s: String?) {
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show()
}
interface OnFragmentInteractionListener {
fun loadLoanAccountSummary(loanAccountNumber: Int)
fun loadSavingsAccountSummary(savingsAccountNumber: Int, accountType: DepositType?)
}
private class AccountAccordion(private val context: Activity?) {
private var currentSection: Section? = null
fun setCurrentSection(currentSection: Section?) {
// close previous section
if (this.currentSection != null) {
this.currentSection!!.close(context)
}
this.currentSection = currentSection
// open new section
if (this.currentSection != null) {
this.currentSection!!.open(context)
}
}
enum class Section(private val sectionId: Int, private val textViewStringId: Int) {
LOANS(R.id.account_accordion_section_loans, R.string.loanAccounts), SAVINGS(R.id.account_accordion_section_savings, R.string.savingAccounts), RECURRING(R.id.account_accordion_section_recurring, R.string.recurringAccount);
private var mListViewCount = 0.0
fun getTextView(context: Activity?): TextView {
return getSectionView(context).findViewById<View>(R.id.tv_toggle_accounts) as TextView
}
fun getIconView(context: Activity?): IconTextView {
return getSectionView(context).findViewById<View>(R.id.tv_toggle_accounts_icon) as IconTextView
}
fun getListView(context: Activity?): ListView {
return getSectionView(context).findViewById<View>(R.id.lv_accounts) as ListView
}
fun getCountView(context: Activity?): TextView {
return getSectionView(context).findViewById<View>(R.id.tv_count_accounts) as TextView
}
fun getSectionView(context: Activity?): View {
return context!!.findViewById(sectionId)
}
fun connect(context: Activity?, adapter: ListAdapter, onItemClickListener: AdapterView.OnItemClickListener?) {
getCountView(context).text = adapter.count.toString()
val listView = getListView(context)
listView.adapter = adapter
listView.onItemClickListener = onItemClickListener
}
fun open(context: Activity?) {
val iconView = getIconView(context)
iconView.text = "{" + LIST_CLOSED_ICON.key() + "}"
mListViewCount = java.lang.Double.valueOf(getCountView(context)
.text
.toString())
val listView = getListView(context)
resizeListView(context, listView)
listView.visibility = View.VISIBLE
}
fun close(context: Activity?) {
val iconView = getIconView(context)
iconView.text = "{" + LIST_OPEN_ICON.key() + "}"
getListView(context).visibility = View.GONE
}
private fun configureSection(context: Activity?, accordion: AccountAccordion) {
val listView = getListView(context)
val textView = getTextView(context)
val iconView = getIconView(context)
val onClickListener = View.OnClickListener {
if (this@Section == accordion.currentSection) {
accordion.setCurrentSection(null)
} else if (listView != null && listView.count > 0) {
accordion.setCurrentSection(this@Section)
}
}
if (textView != null) {
textView.setOnClickListener(onClickListener)
textView.text = context!!.getString(textViewStringId)
}
iconView?.setOnClickListener(onClickListener)
listView?.setOnTouchListener { view, motionEvent ->
view.parent.requestDisallowInterceptTouchEvent(true)
false
}
// initialize section in closed state
close(context)
}
private fun resizeListView(context: Activity?, listView: ListView) {
if (mListViewCount < 4) {
//default listview height is 200dp,which displays 4 listview items.
// This calculates the required listview height
// if listview items are less than 4
val heightInDp = mListViewCount / 4 * 200
val heightInPx = heightInDp * context!!.resources
.displayMetrics.density
val params = listView.layoutParams
params.height = heightInPx.toInt()
listView.layoutParams = params
listView.requestLayout()
}
}
companion object {
private val LIST_OPEN_ICON = MaterialIcons.md_add_circle_outline
private val LIST_CLOSED_ICON = MaterialIcons.md_remove_circle_outline
fun configure(context: Activity?, accordion: AccountAccordion) {
for (section in values()) {
section.configureSection(context, accordion)
}
}
}
}
init {
Section.configure(context, this)
}
}
companion object {
// Intent response codes. Each response code must be a unique integer.
private const val CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 2
private const val UPLOAD_IMAGE_ACTIVITY_REQUEST_CODE = 1
private const val CHECK_PERMISSIONS = 1010
const val MENU_ITEM_DATA_TABLES = 1000
const val MENU_ITEM_PIN_POINT = 1001
const val MENU_ITEM_CLIENT_CHARGES = 1003
const val MENU_ITEM_ADD_SAVINGS_ACCOUNT = 1004
const val MENU_ITEM_ADD_LOAN_ACCOUNT = 1005
const val MENU_ITEM_DOCUMENTS = 1006
const val MENU_ITEM_UPLOAD_SIGN = 1010
const val MENU_ITEM_IDENTIFIERS = 1007
const val MENU_ITEM_SURVEYS = 1008
const val MENU_ITEM_NOTE = 1009
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param clientId Client's Id
*/
fun newInstance(clientId: Int): ClientDetailsFragment {
val fragment = ClientDetailsFragment()
val args = Bundle()
args.putInt(Constants.CLIENT_ID, clientId)
fragment.arguments = args
return fragment
}
}
} | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/clientdetails/ClientDetailsFragment.kt | 2088931210 |
package cm.aptoide.pt.home.apps.list
import cm.aptoide.pt.R
import cm.aptoide.pt.home.apps.AppClick
import cm.aptoide.pt.home.apps.list.models.DownloadCardModel_
import cm.aptoide.pt.home.apps.list.models.InstalledCardModel_
import cm.aptoide.pt.home.apps.list.models.TitleModel_
import cm.aptoide.pt.home.apps.list.models.UpdateCardModel_
import cm.aptoide.pt.home.apps.model.DownloadApp
import cm.aptoide.pt.home.apps.model.InstalledApp
import cm.aptoide.pt.home.apps.model.UpdateApp
import cm.aptoide.pt.themes.ThemeManager
import com.airbnb.epoxy.Typed3EpoxyController
import rx.subjects.PublishSubject
class AppsController(val themeManager: ThemeManager) :
Typed3EpoxyController<List<UpdateApp>, List<InstalledApp>, List<DownloadApp>>() {
val appEventListener: PublishSubject<AppClick> = PublishSubject.create()
val updateAllEvent: PublishSubject<Void> = PublishSubject.create()
override fun buildModels(updates: List<UpdateApp>, installedApps: List<InstalledApp>,
downloads: List<DownloadApp>) {
TitleModel_()
.id("downloads", "header")
.title(R.string.apps_title_downloads_header)
.shouldShowButton(false)
.addIf(downloads.isNotEmpty(), this)
for (download in downloads) {
DownloadCardModel_()
.id("downloads", download.identifier)
.application(download)
.eventSubject(appEventListener)
.addTo(this)
}
// Updates
TitleModel_()
.id("updates", "header")
.title(R.string.apps_title_updates_header)
.shouldShowButton(true)
.eventSubject(updateAllEvent)
.addIf(updates.isNotEmpty(), this)
for (update in updates) {
UpdateCardModel_()
.id("updates", update.identifier)
.application(update)
.eventSubject(appEventListener)
.themeManager(themeManager)
.addTo(this)
}
// Installed
TitleModel_()
.id("installed", "header")
.title(R.string.apps_title_installed_apps_header)
.shouldShowButton(false)
.addIf(installedApps.isNotEmpty(), this)
for (installed in installedApps) {
InstalledCardModel_()
.id("installed", installed.identifier)
.application(installed)
.addTo(this)
}
}
/**
* This is overriden so that there's named arguments instead of data1, data2, data3...
*/
override fun setData(updates: List<UpdateApp>, installedApps: List<InstalledApp>,
downloads: List<DownloadApp>) {
super.setData(updates, installedApps, downloads)
}
} | app/src/main/java/cm/aptoide/pt/home/apps/list/AppsController.kt | 2348618024 |
/* Copyright 2018 Levi Bard
*
* This file is a part of Tusky.
*
* 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.
*
* Tusky 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 Tusky; if not,
* see <http://www.gnu.org/licenses>. */
package com.keylesspalace.tusky
import com.google.android.material.bottomsheet.BottomSheetBehavior
import android.text.SpannedString
import android.widget.LinearLayout
import com.keylesspalace.tusky.entity.Account
import com.keylesspalace.tusky.entity.SearchResults
import com.keylesspalace.tusky.entity.Status
import com.keylesspalace.tusky.network.MastodonApi
import okhttp3.Request
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.mockito.ArgumentMatchers
import org.mockito.Mockito
import org.mockito.Mockito.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
class BottomSheetActivityTest {
private lateinit var activity : FakeBottomSheetActivity
private lateinit var apiMock: MastodonApi
private val accountQuery = "http://mastodon.foo.bar/@User"
private val statusQuery = "http://mastodon.foo.bar/@User/345678"
private val nonMastodonQuery = "http://medium.com/@correspondent/345678"
private val emptyCallback = FakeSearchResults()
private val account = Account (
"1",
"admin",
"admin",
"Ad Min",
SpannedString(""),
"http://mastodon.foo.bar",
"",
"",
false,
0,
0,
0,
null,
false,
emptyList(),
emptyList()
)
private val accountCallback = FakeSearchResults(account)
private val status = Status(
"1",
statusQuery,
account,
null,
null,
null,
SpannedString("omgwat"),
Date(),
Collections.emptyList(),
0,
0,
false,
false,
false,
"",
Status.Visibility.PUBLIC,
listOf(),
arrayOf(),
null,
pinned = false
)
private val statusCallback = FakeSearchResults(status)
@Before
fun setup() {
apiMock = Mockito.mock(MastodonApi::class.java)
`when`(apiMock.search(eq(accountQuery), ArgumentMatchers.anyBoolean())).thenReturn(accountCallback)
`when`(apiMock.search(eq(statusQuery), ArgumentMatchers.anyBoolean())).thenReturn(statusCallback)
`when`(apiMock.search(eq(nonMastodonQuery), ArgumentMatchers.anyBoolean())).thenReturn(emptyCallback)
activity = FakeBottomSheetActivity(apiMock)
}
@RunWith(Parameterized::class)
class UrlMatchingTests(val url: String, val expectedResult: Boolean) {
companion object {
@Parameterized.Parameters(name = "match_{0}")
@JvmStatic
fun data() : Iterable<Any> {
return listOf(
arrayOf("https://mastodon.foo.bar/@User", true),
arrayOf("http://mastodon.foo.bar/@abc123", true),
arrayOf("https://mastodon.foo.bar/@user/345667890345678", true),
arrayOf("https://mastodon.foo.bar/@user/3", true),
arrayOf("https://pleroma.foo.bar/users/meh3223", true),
arrayOf("https://pleroma.foo.bar/users/2345", true),
arrayOf("https://pleroma.foo.bar/notice/9", true),
arrayOf("https://pleroma.foo.bar/notice/9345678", true),
arrayOf("https://pleroma.foo.bar/objects/abcdef-123-abcd-9876543", true),
arrayOf("https://google.com/", false),
arrayOf("https://mastodon.foo.bar/@User?foo=bar", false),
arrayOf("https://mastodon.foo.bar/@User#foo", false),
arrayOf("http://mastodon.foo.bar/@", false),
arrayOf("http://mastodon.foo.bar/@/345678", false),
arrayOf("https://mastodon.foo.bar/@user/345667890345678/", false),
arrayOf("https://mastodon.foo.bar/@user/3abce", false),
arrayOf("https://pleroma.foo.bar/users/", false),
arrayOf("https://pleroma.foo.bar/user/2345", false),
arrayOf("https://pleroma.foo.bar/notice/wat", false),
arrayOf("https://pleroma.foo.bar/notices/123456", false),
arrayOf("https://pleroma.foo.bar/object/abcdef-123-abcd-9876543", false),
arrayOf("https://pleroma.foo.bar/objects/xabcdef-123-abcd-9876543", false),
arrayOf("https://pleroma.foo.bar/objects/xabcdef-123-abcd-9876543/", false),
arrayOf("https://pleroma.foo.bar/objects/xabcdef-123-abcd_9876543", false)
)
}
}
@Test
fun test() {
Assert.assertEquals(expectedResult, looksLikeMastodonUrl(url))
}
}
@Test
fun beginEndSearch_setIsSearching_isSearchingAfterBegin() {
activity.onBeginSearch("https://mastodon.foo.bar/@User")
Assert.assertTrue(activity.isSearching())
}
@Test
fun beginEndSearch_setIsSearching_isNotSearchingAfterEnd() {
val validUrl = "https://mastodon.foo.bar/@User"
activity.onBeginSearch(validUrl)
activity.onEndSearch(validUrl)
Assert.assertFalse(activity.isSearching())
}
@Test
fun beginEndSearch_setIsSearching_doesNotCancelSearchWhenResponseFromPreviousSearchIsReceived() {
val validUrl = "https://mastodon.foo.bar/@User"
val invalidUrl = ""
activity.onBeginSearch(validUrl)
activity.onEndSearch(invalidUrl)
Assert.assertTrue(activity.isSearching())
}
@Test
fun cancelActiveSearch() {
val url = "https://mastodon.foo.bar/@User"
activity.onBeginSearch(url)
activity.cancelActiveSearch()
Assert.assertFalse(activity.isSearching())
}
@Test
fun getCancelSearchRequested_detectsURL() {
val firstUrl = "https://mastodon.foo.bar/@User"
val secondUrl = "https://mastodon.foo.bar/@meh"
activity.onBeginSearch(firstUrl)
activity.cancelActiveSearch()
activity.onBeginSearch(secondUrl)
Assert.assertTrue(activity.getCancelSearchRequested(firstUrl))
Assert.assertFalse(activity.getCancelSearchRequested(secondUrl))
}
@Test
fun search_inIdealConditions_returnsRequestedResults_forAccount() {
activity.viewUrl(accountQuery)
accountCallback.invokeCallback()
Assert.assertEquals(account.id, activity.accountId)
}
@Test
fun search_inIdealConditions_returnsRequestedResults_forStatus() {
activity.viewUrl(statusQuery)
statusCallback.invokeCallback()
Assert.assertEquals(status.id, activity.statusId)
}
@Test
fun search_inIdealConditions_returnsRequestedResults_forNonMastodonURL() {
activity.viewUrl(nonMastodonQuery)
emptyCallback.invokeCallback()
Assert.assertEquals(nonMastodonQuery, activity.link)
}
@Test
fun search_withCancellation_doesNotLoadUrl_forAccount() {
activity.viewUrl(accountQuery)
Assert.assertTrue(activity.isSearching())
activity.cancelActiveSearch()
Assert.assertFalse(activity.isSearching())
accountCallback.invokeCallback()
Assert.assertEquals(null, activity.accountId)
}
@Test
fun search_withCancellation_doesNotLoadUrl_forStatus() {
activity.viewUrl(accountQuery)
activity.cancelActiveSearch()
accountCallback.invokeCallback()
Assert.assertEquals(null, activity.accountId)
}
@Test
fun search_withCancellation_doesNotLoadUrl_forNonMastodonURL() {
activity.viewUrl(nonMastodonQuery)
activity.cancelActiveSearch()
emptyCallback.invokeCallback()
Assert.assertEquals(null, activity.searchUrl)
}
@Test
fun search_withPreviousCancellation_completes() {
// begin/cancel account search
activity.viewUrl(accountQuery)
activity.cancelActiveSearch()
// begin status search
activity.viewUrl(statusQuery)
// return response from account search
accountCallback.invokeCallback()
// ensure that status search is still ongoing
Assert.assertTrue(activity.isSearching())
statusCallback.invokeCallback()
// ensure that the result of the status search was recorded
// and the account search wasn't
Assert.assertEquals(status.id, activity.statusId)
Assert.assertEquals(null, activity.accountId)
}
class FakeSearchResults : Call<SearchResults> {
private var searchResults: SearchResults
private var callback: Callback<SearchResults>? = null
constructor() {
searchResults = SearchResults(Collections.emptyList(), Collections.emptyList(), Collections.emptyList())
}
constructor(status: Status) {
searchResults = SearchResults(Collections.emptyList(), listOf(status), Collections.emptyList())
}
constructor(account: Account) {
searchResults = SearchResults(listOf(account), Collections.emptyList(), Collections.emptyList())
}
fun invokeCallback() {
callback?.onResponse(this, Response.success(searchResults))
}
override fun enqueue(callback: Callback<SearchResults>?) {
this.callback = callback
}
override fun isExecuted(): Boolean { throw NotImplementedError() }
override fun clone(): Call<SearchResults> { throw NotImplementedError() }
override fun isCanceled(): Boolean { throw NotImplementedError() }
override fun cancel() { throw NotImplementedError() }
override fun execute(): Response<SearchResults> { throw NotImplementedError() }
override fun request(): Request { throw NotImplementedError() }
}
class FakeBottomSheetActivity(api: MastodonApi) : BottomSheetActivity() {
var statusId: String? = null
var accountId: String? = null
var link: String? = null
init {
mastodonApi = api
@Suppress("UNCHECKED_CAST")
bottomSheet = Mockito.mock(BottomSheetBehavior::class.java) as BottomSheetBehavior<LinearLayout>
callList = arrayListOf()
}
override fun openLink(url: String) {
this.link = url
}
override fun viewAccount(id: String) {
this.accountId = id
}
override fun viewThread(statusId: String, url: String?) {
this.statusId = statusId
}
}
} | app/src/test/java/com/keylesspalace/tusky/BottomSheetActivityTest.kt | 2145601558 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.