repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ursjoss/sipamato | core/core-pubmed-api/src/main/java/ch/difty/scipamato/core/pubmed/PubmedArticleResult.kt | 2 | 1720 | @file:Suppress("SpellCheckingInspection")
package ch.difty.scipamato.core.pubmed
import org.springframework.http.HttpStatus
private val errorRegex =
""".+\{"error":"([^"]*)",.+}""".toRegex(RegexOption.DOT_MATCHES_ALL)
private val reasonRegex =
""".+Reason: <strong>([^<]+)</strong>+.+""".toRegex(RegexOption.DOT_MATCHES_ALL)
/**
* Data Class providing the [PubmedArticleFacade] or an error specific message
* providing information about the problem that prevented the retrieval of the article.
*/
class PubmedArticleResult(
val pubmedArticleFacade: PubmedArticleFacade?,
httpStatus: HttpStatus?,
rawMessage: String?
) {
val errorMessage: String = evaluateMessageFrom(httpStatus, rawMessage ?: "")
private fun evaluateMessageFrom(httpStatus: HttpStatus?, rawMessage: String): String =
when {
pubmedArticleFacade != null -> ""
httpStatus == null -> rawMessage
else -> when (httpStatus) {
HttpStatus.OK -> rawMessage
HttpStatus.BAD_REQUEST -> wrap(httpStatus, errorRegex.extractFrom(rawMessage))
HttpStatus.BAD_GATEWAY -> wrap(httpStatus, reasonRegex.extractFrom(rawMessage))
else -> wrap(httpStatus, prependColumn(rawMessage))
}
}
private fun wrap(httpStatus: HttpStatus, msg: String): String = "Status ${httpStatus}$msg"
private fun prependColumn(msg: String): String = if (msg.isBlank()) "" else ": $msg"
private fun Regex.extractFrom(rawMessage: String): String =
when (val result = matchEntire(rawMessage)) {
null -> prependColumn(rawMessage)
else -> prependColumn(result.groups[1]?.value ?: "")
}
}
| gpl-3.0 | a83e11e732a360c7fd171d984fe577cc | 39 | 95 | 0.65814 | 4.479167 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/main/kotlin/com/masahirosaito/spigot/homes/commands/subcommands/player/invitecommands/PlayerInviteCommand.kt | 1 | 4427 | package com.masahirosaito.spigot.homes.commands.subcommands.player.invitecommands
import com.masahirosaito.spigot.homes.Configs.onInvite
import com.masahirosaito.spigot.homes.Homes.Companion.homes
import com.masahirosaito.spigot.homes.commands.BaseCommand
import com.masahirosaito.spigot.homes.commands.CommandUsage
import com.masahirosaito.spigot.homes.commands.subcommands.player.PlayerCommand
import com.masahirosaito.spigot.homes.exceptions.AlreadyHasInvitationException
import com.masahirosaito.spigot.homes.exceptions.NoReceivedInvitationException
import com.masahirosaito.spigot.homes.findOnlinePlayer
import com.masahirosaito.spigot.homes.nms.HomesEntity
import com.masahirosaito.spigot.homes.strings.commands.InviteCommandStrings
import com.masahirosaito.spigot.homes.strings.commands.InviteCommandStrings.ACCEPT_INVITATION_FROM
import com.masahirosaito.spigot.homes.strings.commands.InviteCommandStrings.ACCEPT_INVITATION_TO
import com.masahirosaito.spigot.homes.strings.commands.InviteCommandStrings.CANCEL_INVITATION_FROM
import com.masahirosaito.spigot.homes.strings.commands.InviteCommandStrings.CANCEL_INVITATION_TO
import com.masahirosaito.spigot.homes.strings.commands.InviteCommandStrings.USAGE_INVITE
import com.masahirosaito.spigot.homes.strings.commands.InviteCommandStrings.USAGE_INVITE_PLAYER
import com.masahirosaito.spigot.homes.strings.commands.InviteCommandStrings.USAGE_INVITE_PLAYER_NAME
import org.bukkit.entity.Player
import org.bukkit.metadata.FixedMetadataValue
import kotlin.concurrent.thread
class PlayerInviteCommand : PlayerCommand {
override var payNow: Boolean = true
private val INVITE_META = "homes.invite"
override val name: String = "invite"
override val description: String = InviteCommandStrings.DESCRIPTION()
override val permissions: List<String> = listOf()
override val usage: CommandUsage = CommandUsage(this, listOf(
"/home invite" to USAGE_INVITE(),
"/home invite <player_name>" to USAGE_INVITE_PLAYER(),
"/home invite <player_name> <home_name>" to USAGE_INVITE_PLAYER_NAME()
))
override val commands: List<BaseCommand> = listOf(
PlayerInvitePlayerCommand(this),
PlayerInvitePlayerNameCommand(this)
)
override fun fee(): Double = homes.fee.INVITE
override fun configs(): List<Boolean> = listOf(onInvite)
override fun isValidArgs(args: List<String>): Boolean = args.isEmpty()
override fun execute(player: Player, args: List<String>) {
if (!player.hasMetadata(INVITE_META)) {
throw NoReceivedInvitationException()
} else {
val th = player.getMetadata(INVITE_META).first().value() as Thread
if (th.isAlive) {
th.interrupt()
th.join()
}
}
}
fun inviteHome(homesEntity: HomesEntity, player: Player, playerName: String, message: String) {
val op = findOnlinePlayer(playerName).apply {
if (hasMetadata(INVITE_META)) {
throw AlreadyHasInvitationException(this)
}
send(this, message)
}
val th = thread(name = "$INVITE_META.${player.name}.$playerName") {
try {
Thread.sleep(30000)
val target = findOnlinePlayer(playerName)
if (target.hasMetadata(INVITE_META)) {
target.removeMetadata(INVITE_META, homes)
send(target, CANCEL_INVITATION_FROM(player.name))
send(player, CANCEL_INVITATION_TO(target.name))
}
} catch (e: InterruptedException) {
try {
val target = findOnlinePlayer(playerName)
target.teleport(homesEntity.location)
target.removeMetadata(INVITE_META, homes)
send(target, ACCEPT_INVITATION_FROM(homesEntity.offlinePlayer.name))
try {
val owner = findOnlinePlayer(homesEntity.offlinePlayer.uniqueId)
send(owner, ACCEPT_INVITATION_TO(target.name))
} catch(e: Exception) {
}
} catch (e: Exception) {
}
} catch(e: Exception) {
e.message?.let { send(player, it) }
}
}
op.setMetadata(INVITE_META, FixedMetadataValue(homes, th))
}
}
| apache-2.0 | 2b3dbc36652d58c6acea25fbf0cac2de | 46.602151 | 100 | 0.675401 | 4.625914 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/agent/runner/WindowsPathResolverWorkflowFactory.kt | 1 | 1484 | package jetbrains.buildServer.agent.runner
import jetbrains.buildServer.agent.FileSystemService
import jetbrains.buildServer.agent.Path
import jetbrains.buildServer.agent.VirtualContext
import jetbrains.buildServer.util.OSType
import java.io.File
import java.io.OutputStreamWriter
class WindowsPathResolverWorkflowFactory(
private val _pathsService: PathsService,
private val _fileSystemService: FileSystemService,
private val _virtualContext: VirtualContext,
private val _baseResolverWorkflowFactory: PathResolverWorkflowFactory)
: PathResolverWorkflowFactory {
override fun create(context: WorkflowContext, state: PathResolverState) =
if (context.status == WorkflowStatus.Running && _virtualContext.targetOSType == OSType.WINDOWS) {
val command = Path(_pathsService.getTempFileName("where.cmd").path)
_fileSystemService.write(File(command.path)) {
OutputStreamWriter(it).use {
it.write(commandToResolve)
}
}
_baseResolverWorkflowFactory.create(context, PathResolverState(state.pathToResolve, state.virtualPathObserver, command))
}
else {
Workflow()
}
companion object {
internal val commandToResolve = "@for %%A in (\"%path:;=\";\"%\") do @(@if exist %%~A\\%1 (@echo %%~A\\%1))"
}
} | apache-2.0 | 0a8c130555142c0c13e7bc39a894d34a | 42.676471 | 140 | 0.642183 | 5.013514 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/src/flow/operators/Merge.kt | 1 | 8282 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:JvmMultifileClass
@file:JvmName("FlowKt")
@file:Suppress("unused")
package kotlinx.coroutines.flow
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.internal.*
import kotlinx.coroutines.internal.*
import kotlin.jvm.*
import kotlinx.coroutines.flow.internal.unsafeFlow as flow
/**
* Name of the property that defines the value of [DEFAULT_CONCURRENCY].
*/
@FlowPreview
public const val DEFAULT_CONCURRENCY_PROPERTY_NAME: String = "kotlinx.coroutines.flow.defaultConcurrency"
/**
* Default concurrency limit that is used by [flattenMerge] and [flatMapMerge] operators.
* It is 16 by default and can be changed on JVM using [DEFAULT_CONCURRENCY_PROPERTY_NAME] property.
*/
@FlowPreview
public val DEFAULT_CONCURRENCY: Int = systemProp(DEFAULT_CONCURRENCY_PROPERTY_NAME,
16, 1, Int.MAX_VALUE
)
/**
* Transforms elements emitted by the original flow by applying [transform], that returns another flow,
* and then concatenating and flattening these flows.
*
* This method is a shortcut for `map(transform).flattenConcat()`. See [flattenConcat].
*
* Note that even though this operator looks very familiar, we discourage its usage in a regular application-specific flows.
* Most likely, suspending operation in [map] operator will be sufficient and linear transformations are much easier to reason about.
*/
@FlowPreview
public fun <T, R> Flow<T>.flatMapConcat(transform: suspend (value: T) -> Flow<R>): Flow<R> =
map(transform).flattenConcat()
/**
* Transforms elements emitted by the original flow by applying [transform], that returns another flow,
* and then merging and flattening these flows.
*
* This operator calls [transform] *sequentially* and then merges the resulting flows with a [concurrency]
* limit on the number of concurrently collected flows.
* It is a shortcut for `map(transform).flattenMerge(concurrency)`.
* See [flattenMerge] for details.
*
* Note that even though this operator looks very familiar, we discourage its usage in a regular application-specific flows.
* Most likely, suspending operation in [map] operator will be sufficient and linear transformations are much easier to reason about.
*
* ### Operator fusion
*
* Applications of [flowOn], [buffer], and [produceIn] _after_ this operator are fused with
* its concurrent merging so that only one properly configured channel is used for execution of merging logic.
*
* @param concurrency controls the number of in-flight flows, at most [concurrency] flows are collected
* at the same time. By default, it is equal to [DEFAULT_CONCURRENCY].
*/
@FlowPreview
public fun <T, R> Flow<T>.flatMapMerge(
concurrency: Int = DEFAULT_CONCURRENCY,
transform: suspend (value: T) -> Flow<R>
): Flow<R> =
map(transform).flattenMerge(concurrency)
/**
* Flattens the given flow of flows into a single flow in a sequential manner, without interleaving nested flows.
*
* Inner flows are collected by this operator *sequentially*.
*/
@FlowPreview
public fun <T> Flow<Flow<T>>.flattenConcat(): Flow<T> = flow {
collect { value -> emitAll(value) }
}
/**
* Merges the given flows into a single flow without preserving an order of elements.
* All flows are merged concurrently, without limit on the number of simultaneously collected flows.
*
* ### Operator fusion
*
* Applications of [flowOn], [buffer], and [produceIn] _after_ this operator are fused with
* its concurrent merging so that only one properly configured channel is used for execution of merging logic.
*/
public fun <T> Iterable<Flow<T>>.merge(): Flow<T> {
/*
* This is a fuseable implementation of the following operator:
* channelFlow {
* forEach { flow ->
* launch {
* flow.collect { send(it) }
* }
* }
* }
*/
return ChannelLimitedFlowMerge(this)
}
/**
* Merges the given flows into a single flow without preserving an order of elements.
* All flows are merged concurrently, without limit on the number of simultaneously collected flows.
*
* ### Operator fusion
*
* Applications of [flowOn], [buffer], and [produceIn] _after_ this operator are fused with
* its concurrent merging so that only one properly configured channel is used for execution of merging logic.
*/
public fun <T> merge(vararg flows: Flow<T>): Flow<T> = flows.asIterable().merge()
/**
* Flattens the given flow of flows into a single flow with a [concurrency] limit on the number of
* concurrently collected flows.
*
* If [concurrency] is more than 1, then inner flows are collected by this operator *concurrently*.
* With `concurrency == 1` this operator is identical to [flattenConcat].
*
* ### Operator fusion
*
* Applications of [flowOn], [buffer], and [produceIn] _after_ this operator are fused with
* its concurrent merging so that only one properly configured channel is used for execution of merging logic.
*
* When [concurrency] is greater than 1, this operator is [buffered][buffer] by default
* and size of its output buffer can be changed by applying subsequent [buffer] operator.
*
* @param concurrency controls the number of in-flight flows, at most [concurrency] flows are collected
* at the same time. By default, it is equal to [DEFAULT_CONCURRENCY].
*/
@FlowPreview
public fun <T> Flow<Flow<T>>.flattenMerge(concurrency: Int = DEFAULT_CONCURRENCY): Flow<T> {
require(concurrency > 0) { "Expected positive concurrency level, but had $concurrency" }
return if (concurrency == 1) flattenConcat() else ChannelFlowMerge(this, concurrency)
}
/**
* Returns a flow that produces element by [transform] function every time the original flow emits a value.
* When the original flow emits a new value, the previous `transform` block is cancelled, thus the name `transformLatest`.
*
* For example, the following flow:
* ```
* flow {
* emit("a")
* delay(100)
* emit("b")
* }.transformLatest { value ->
* emit(value)
* delay(200)
* emit(value + "_last")
* }
* ```
* produces `a b b_last`.
*
* This operator is [buffered][buffer] by default
* and size of its output buffer can be changed by applying subsequent [buffer] operator.
*/
@ExperimentalCoroutinesApi
public fun <T, R> Flow<T>.transformLatest(@BuilderInference transform: suspend FlowCollector<R>.(value: T) -> Unit): Flow<R> =
ChannelFlowTransformLatest(transform, this)
/**
* Returns a flow that switches to a new flow produced by [transform] function every time the original flow emits a value.
* When the original flow emits a new value, the previous flow produced by `transform` block is cancelled.
*
* For example, the following flow:
* ```
* flow {
* emit("a")
* delay(100)
* emit("b")
* }.flatMapLatest { value ->
* flow {
* emit(value)
* delay(200)
* emit(value + "_last")
* }
* }
* ```
* produces `a b b_last`
*
* This operator is [buffered][buffer] by default and size of its output buffer can be changed by applying subsequent [buffer] operator.
*/
@ExperimentalCoroutinesApi
public inline fun <T, R> Flow<T>.flatMapLatest(@BuilderInference crossinline transform: suspend (value: T) -> Flow<R>): Flow<R> =
transformLatest { emitAll(transform(it)) }
/**
* Returns a flow that emits elements from the original flow transformed by [transform] function.
* When the original flow emits a new value, computation of the [transform] block for previous value is cancelled.
*
* For example, the following flow:
* ```
* flow {
* emit("a")
* delay(100)
* emit("b")
* }.mapLatest { value ->
* println("Started computing $value")
* delay(200)
* "Computed $value"
* }
* ```
* will print "Started computing a" and "Started computing b", but the resulting flow will contain only "Computed b" value.
*
* This operator is [buffered][buffer] by default and size of its output buffer can be changed by applying subsequent [buffer] operator.
*/
@ExperimentalCoroutinesApi
public fun <T, R> Flow<T>.mapLatest(@BuilderInference transform: suspend (value: T) -> R): Flow<R> =
transformLatest { emit(transform(it)) }
| apache-2.0 | 4581e1f36d019293d997fa109071ac9d | 37.700935 | 136 | 0.711785 | 4.008712 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/wifi/graphutils/GraphDataPoint.kt | 1 | 1279 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.graphutils
import com.jjoe64.graphview.series.DataPoint
class GraphDataPoint(x: Double, y: Double) : DataPoint(x, y) {
constructor(x: Int, y: Int) : this(x.toDouble(), y.toDouble())
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as DataPoint
return x == other.x && y == other.y
}
override fun hashCode(): Int = 31 * x.hashCode() + y.hashCode()
} | gpl-3.0 | e61fec18fdc3c19b9b6e85e72e0807fb | 35.571429 | 90 | 0.704457 | 4.060317 | false | false | false | false |
leafclick/intellij-community | platform/util/ui/src/com/intellij/ui/svg/MyTranscoder.kt | 1 | 4265 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.svg
import com.intellij.openapi.diagnostic.Logger
import org.apache.batik.anim.dom.SAXSVGDocumentFactory
import org.apache.batik.anim.dom.SVGOMDocument
import org.apache.batik.bridge.BridgeContext
import org.apache.batik.bridge.UserAgent
import org.apache.batik.transcoder.SVGAbstractTranscoder
import org.apache.batik.transcoder.TranscoderException
import org.apache.batik.transcoder.TranscoderInput
import org.apache.batik.transcoder.TranscoderOutput
import org.apache.batik.transcoder.image.ImageTranscoder
import org.apache.batik.util.XMLResourceDescriptor
import org.w3c.dom.Element
import org.w3c.dom.svg.SVGDocument
import java.awt.GraphicsEnvironment
import java.awt.image.BufferedImage
import java.io.IOException
import java.io.StringReader
internal class MyTranscoder(private val scale: Double) : ImageTranscoder() {
companion object {
@JvmStatic
val iconMaxSize: Double by lazy {
var maxSize = Integer.MAX_VALUE.toDouble()
if (!GraphicsEnvironment.isHeadless()) {
val device = GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice
val bounds = device.defaultConfiguration.bounds
val tx = device.defaultConfiguration.defaultTransform
maxSize = Math.max(bounds.width * tx.scaleX, bounds.height * tx.scaleY).toInt().toDouble()
}
maxSize
}
@Throws(TranscoderException::class)
@JvmStatic
@JvmOverloads
fun createImage(scale: Double, input: TranscoderInput, overriddenWidth: Float = -1f, overriddenHeight: Float = -1f): MyTranscoder {
val transcoder = MyTranscoder(scale)
if (overriddenWidth != -1f) {
transcoder.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, overriddenWidth)
}
if (overriddenHeight != -1f) {
transcoder.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, overriddenHeight)
}
val iconMaxSize = iconMaxSize.toFloat()
transcoder.addTranscodingHint(SVGAbstractTranscoder.KEY_MAX_WIDTH, iconMaxSize)
transcoder.addTranscodingHint(SVGAbstractTranscoder.KEY_MAX_HEIGHT, iconMaxSize)
transcoder.transcode(input, null)
return transcoder
}
}
var origDocWidth = 0f
var origDocHeight = 0f
var image: BufferedImage? = null
private set
init {
width = 16f
height = 16f
}
override fun setImageSize(docWidth: Float, docHeight: Float) {
origDocWidth = docWidth
origDocHeight = docHeight
super.setImageSize((docWidth * scale).toFloat(), (docHeight * scale).toFloat())
}
override fun createImage(w: Int, h: Int): BufferedImage {
@Suppress("UndesirableClassUsage")
return BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB)
}
override fun writeImage(image: BufferedImage, output: TranscoderOutput?) {
this.image = image
}
override fun createUserAgent(): UserAgent {
return object : SVGAbstractTranscoder.SVGAbstractTranscoderUserAgent() {
override fun getBrokenLinkDocument(e: Element, url: String, message: String): SVGDocument {
Logger.getInstance(MyTranscoder::class.java).warn("$url $message")
return createFallbackPlaceholder()
}
}
}
// make it accessible
public override fun createBridgeContext(doc: SVGOMDocument): BridgeContext {
return super.createBridgeContext(doc)
}
}
private fun createFallbackPlaceholder(): SVGDocument {
try {
val fallbackIcon = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\">\n" +
" <rect x=\"1\" y=\"1\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"red\" stroke-width=\"2\"/>\n" +
" <line x1=\"1\" y1=\"1\" x2=\"15\" y2=\"15\" stroke=\"red\" stroke-width=\"2\"/>\n" +
" <line x1=\"1\" y1=\"15\" x2=\"15\" y2=\"1\" stroke=\"red\" stroke-width=\"2\"/>\n" +
"</svg>\n"
val factory = SAXSVGDocumentFactory(XMLResourceDescriptor.getXMLParserClassName())
return factory.createDocument(null, StringReader(fallbackIcon)) as SVGDocument
}
catch (e: IOException) {
throw IllegalStateException(e)
}
} | apache-2.0 | d25759df80fc44fad46a79bc33efe184 | 38.137615 | 140 | 0.708089 | 3.909258 | false | false | false | false |
leafclick/intellij-community | platform/diagnostic/src/startUpPerformanceReporter/TraceEventFormatWriter.kt | 1 | 4206 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic.startUpPerformanceReporter
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.core.JsonGenerator
import com.intellij.diagnostic.ActivityImpl
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.util.containers.ObjectLongHashMap
import com.intellij.util.io.jackson.array
import com.intellij.util.io.jackson.obj
import java.io.OutputStreamWriter
import java.util.concurrent.TimeUnit
// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit#
// ph - phase
// dur - duration
// pid - process id
// tid - thread id
internal class TraceEventFormatWriter(private val timeOffset: Long,
private val instantEvents: List<ActivityImpl>,
private val threadNameManager: ThreadNameManager) {
fun writeInstantEvents(writer: JsonGenerator) {
for (event in instantEvents) {
writer.obj {
writeCommonFields(event, writer)
writer.writeStringField("ph", "i")
writer.writeStringField("s", "g")
}
}
}
fun writeServiceEvents(writer: JsonGenerator, unsortedServices: List<ActivityImpl>, pluginCostMap: MutableMap<String, ObjectLongHashMap<String>>?) {
val servicesSortedByTime = unsortedServices.sortedWith(Comparator(::compareTime))
val ownDurations = computeOwnTime(servicesSortedByTime, threadNameManager)
for (event in servicesSortedByTime) {
writer.obj {
@Suppress("DuplicatedCode")
val computedOwnDuration = ownDurations.get(event)
val duration = if (computedOwnDuration == -1L) event.end - event.start else computedOwnDuration
writeCompleteEvent(event, writer, extraArgWriter = {
writer.writeNumberField("ownDur", TimeUnit.NANOSECONDS.toMicros(duration))
})
if (pluginCostMap != null) {
event.pluginId?.let {
StartUpMeasurer.doAddPluginCost(it, event.category?.name ?: "unknown", duration, pluginCostMap)
}
}
}
}
}
fun write(mainEvents: List<ActivityImpl>, categoryToActivity: Map<String, List<ActivityImpl>>, services: List<ActivityImpl>, outputWriter: OutputStreamWriter) {
val writer = JsonFactory().createGenerator(outputWriter)
writer.prettyPrinter = MyJsonPrettyPrinter()
writer.use {
writer.obj {
writer.writeStringField("version", StartUpPerformanceReporter.VERSION)
writer.array("traceEvents") {
writeInstantEvents(writer)
for (event in mainEvents) {
writer.obj {
writeCompleteEvent(event, writer)
}
}
writeServiceEvents(writer, services, pluginCostMap = null /* computed only by idea format writer */)
for (events in categoryToActivity.values) {
for (event in events) {
writer.obj {
writeCompleteEvent(event, writer)
}
}
}
}
}
}
}
private fun writeCompleteEvent(event: ActivityImpl, writer: JsonGenerator, extraArgWriter: (() -> Unit)? = null) {
writeCommonFields(event, writer)
writer.writeStringField("ph", "X")
writer.writeNumberField("dur", TimeUnit.NANOSECONDS.toMicros(event.end - event.start))
if (event.description != null || event.pluginId != null || extraArgWriter != null) {
writer.obj("args") {
event.description?.let {
writer.writeStringField("description", it)
}
event.pluginId?.let {
writer.writeStringField("plugin", it)
}
extraArgWriter?.invoke()
}
}
}
private fun writeCommonFields(event: ActivityImpl, writer: JsonGenerator) {
writer.writeStringField("name", event.name)
writer.writeNumberField("ts", TimeUnit.NANOSECONDS.toMicros(event.start - timeOffset))
writer.writeNumberField("pid", 1)
writer.writeStringField("tid", threadNameManager.getThreadName(event))
event.category?.let {
writer.writeStringField("cat", it.jsonName)
}
}
} | apache-2.0 | 9095ae932527720fd7702eeb8318f7c2 | 36.5625 | 162 | 0.67475 | 4.455508 | false | true | false | false |
leafclick/intellij-community | uast/uast-common/src/org/jetbrains/uast/declarations/UDeclaration.kt | 1 | 2470 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiJvmModifiersOwner
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiModifierListOwner
import org.jetbrains.uast.visitor.UastTypedVisitor
/**
* A [PsiElement] declaration wrapper.
*/
interface UDeclaration : UElement, PsiJvmModifiersOwner, UAnnotated {
/**
* Returns the original declaration (which is *always* unwrapped, never a [UDeclaration]).
*/
override val psi: PsiModifierListOwner
override fun getOriginalElement(): PsiElement? = sourcePsi?.originalElement
/**
* Returns the declaration name identifier. If declaration is anonymous other implementation dependant psi element will be returned.
* The main rule that returned element is "anchor": it is a single token which represents this declaration.
*
* It is useful for putting gutters and inspection reports.
*/
val uastAnchor: UElement?
/**
* Returns `true` if this declaration has a [PsiModifier.STATIC] modifier.
*/
val isStatic: Boolean
get() = hasModifierProperty(PsiModifier.STATIC)
/**
* Returns `true` if this declaration has a [PsiModifier.FINAL] modifier.
*/
val isFinal: Boolean
get() = hasModifierProperty(PsiModifier.FINAL)
/**
* Returns a declaration visibility.
*/
val visibility: UastVisibility
get() = UastVisibility[this]
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitDeclaration(this, data)
}
interface UDeclarationEx : UDeclaration {
override val javaPsi: PsiModifierListOwner
}
fun UElement?.getContainingDeclaration(): UDeclaration? = this?.withContainingElements?.drop(1)?.filterIsInstance<UDeclaration>()?.firstOrNull()
fun <T : UElement> UElement?.getContainingDeclaration(cls: Class<out T>): T? {
val element = this?.withContainingElements?.drop(1)?.filterIsInstance<UDeclaration>()?.firstOrNull()
return if (element != null && cls.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
element as T
} else {
null
}
}
fun UDeclaration?.getAnchorPsi():PsiElement? {
return this?.uastAnchor?.sourcePsi
}
/**
* A base interface for every [UElement] which have a name identifier. As analogy to [PsiNameIdentifierOwner]
*/
interface UAnchorOwner : UElement {
val uastAnchor: UIdentifier?
}
| apache-2.0 | 0fdbb0b84331e26a792423fefa6eb9ab | 31.077922 | 144 | 0.740081 | 4.490909 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/annotations/kotlinTopLevelPropertyAsParameter.kt | 2 | 1694 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
@Ann(i, s, f, d, l, b, bool, c, str) class MyClass
fun box(): String {
val ann = MyClass::class.java.getAnnotation(Ann::class.java)
if (ann == null) return "fail: cannot find Ann on MyClass}"
if (ann.i != 2) return "fail: annotation parameter i should be 2, but was ${ann.i}"
if (ann.s != 2.toShort()) return "fail: annotation parameter i should be 2, but was ${ann.i}"
if (ann.f != 2.toFloat()) return "fail: annotation parameter i should be 2, but was ${ann.i}"
if (ann.d != 2.toDouble()) return "fail: annotation parameter i should be 2, but was ${ann.i}"
if (ann.l != 2.toLong()) return "fail: annotation parameter i should be 2, but was ${ann.i}"
if (ann.b != 2.toByte()) return "fail: annotation parameter i should be 2, but was ${ann.i}"
if (!ann.bool) return "fail: annotation parameter i should be true, but was ${ann.i}"
if (ann.c != 'c') return "fail: annotation parameter i should be c, but was ${ann.i}"
if (ann.str != "str") return "fail: annotation parameter i should be str, but was ${ann.i}"
return "OK"
}
@Retention(AnnotationRetention.RUNTIME)
annotation class Ann(
val i: Int,
val s: Short,
val f: Float,
val d: Double,
val l: Long,
val b: Byte,
val bool: Boolean,
val c: Char,
val str: String
)
const val i: Int = 2
const val s: Short = 2
const val f: Float = 2.0.toFloat()
const val d: Double = 2.0
const val l: Long = 2
const val b: Byte = 2
const val bool: Boolean = true
const val c: Char = 'c'
const val str: String = "str"
| apache-2.0 | 5a419e26c4a474c86f292f181297d070 | 37.5 | 98 | 0.628689 | 3.315068 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SuspiciousVarPropertyInspection.kt | 4 | 2686 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.quickfix.ChangeVariableMutabilityFix
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.resolve.BindingContext
class SuspiciousVarPropertyInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
propertyVisitor(fun(property: KtProperty) {
if (property.isLocal || !property.isVar || property.initializer == null || property.setter != null) return
val getter = property.getter ?: return
val context = property.analyze()
val descriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? PropertyDescriptor ?: return
if (context[BindingContext.BACKING_FIELD_REQUIRED, descriptor] == false) return
if (getter.hasBackingFieldReference()) return
holder.registerProblem(
property.valOrVarKeyword,
KotlinBundle.message("suspicious.var.property.its.setter.does.not.influence.its.getter.result"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
IntentionWrapper(ChangeVariableMutabilityFix(property, makeVar = false, deleteInitializer = true))
)
})
companion object {
private fun KtPropertyAccessor.hasBackingFieldReference(): Boolean {
val bodyExpression = this.bodyExpression ?: return true
return bodyExpression.isBackingFieldReference(property) || bodyExpression.anyDescendantOfType<KtNameReferenceExpression> {
it.isBackingFieldReference(property)
}
}
fun KtExpression.isBackingFieldReference(property: KtProperty): Boolean =
this is KtNameReferenceExpression && isBackingFieldReference(property)
private fun KtNameReferenceExpression.isBackingFieldReference(property: KtProperty): Boolean {
return text == KtTokens.FIELD_KEYWORD.value && mainReference.resolve() == property
}
}
} | apache-2.0 | 06833543beaafc2dccfe9efea223b040 | 51.686275 | 158 | 0.738645 | 5.29783 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/math/Vec4.kt | 1 | 16585 | package de.fabmax.kool.math
import kotlin.math.sqrt
open class Vec4f(x: Float, y: Float, z: Float, w: Float) {
protected val fields = FloatArray(4)
open val x get() = this[0]
open val y get() = this[1]
open val z get() = this[2]
open val w get() = this[3]
constructor(f: Float) : this(f, f, f, f)
constructor(xyz: Vec3f, w: Float) : this(xyz.x, xyz.y, xyz.z, w)
constructor(v: Vec4f) : this(v.x, v.y, v.z, v.w)
init {
fields[0] = x
fields[1] = y
fields[2] = z
fields[3] = w
}
fun add(other: Vec4f, result: MutableVec4f): MutableVec4f = result.set(this).add(other)
fun distance(other: Vec4f): Float = sqrt(sqrDistance(other))
fun dot(other: Vec4f): Float = x * other.x + y * other.y + z * other.z + w * other.w
/**
* Checks vector components for equality using [de.fabmax.kool.math.isFuzzyEqual], that is all components must
* have a difference less or equal [eps].
*/
fun isFuzzyEqual(other: Vec4f, eps: Float = FUZZY_EQ_F): Boolean =
isFuzzyEqual(x, other.x, eps) && isFuzzyEqual(y, other.y, eps) && isFuzzyEqual(z, other.z, eps) && isFuzzyEqual(w, other.w, eps)
fun length(): Float = sqrt(sqrLength())
fun mix(other: Vec4f, weight: Float, result: MutableVec4f): MutableVec4f {
result.x = other.x * weight + x * (1f - weight)
result.y = other.y * weight + y * (1f - weight)
result.z = other.z * weight + z * (1f - weight)
result.w = other.w * weight + w * (1f - weight)
return result
}
fun mul(other: Vec4f, result: MutableVec4f): MutableVec4f = result.set(this).mul(other)
fun norm(result: MutableVec4f): MutableVec4f = result.set(this).norm()
fun quatProduct(otherQuat: Vec4f, result: MutableVec4f): MutableVec4f {
result.x = w * otherQuat.x + x * otherQuat.w + y * otherQuat.z - z * otherQuat.y
result.y = w * otherQuat.y + y * otherQuat.w + z * otherQuat.x - x * otherQuat.z
result.z = w * otherQuat.z + z * otherQuat.w + x * otherQuat.y - y * otherQuat.x
result.w = w * otherQuat.w - x * otherQuat.x - y * otherQuat.y - z * otherQuat.z
return result
}
fun scale(factor: Float, result: MutableVec4f): MutableVec4f = result.set(this).scale(factor)
fun sqrDistance(other: Vec4f): Float {
val dx = x - other.x
val dy = y - other.y
val dz = z - other.z
val dw = z - other.w
return dx*dx + dy*dy + dz*dz + dw*dw
}
fun sqrLength(): Float = x*x + y*y + z*z + w*w
fun subtract(other: Vec4f, result: MutableVec4f): MutableVec4f = result.set(this).subtract(other)
fun getXyz(result: MutableVec3f): MutableVec3f {
result.x = x
result.y = y
result.z = z
return result
}
open operator fun get(i: Int): Float = fields[i]
operator fun times(other: Vec4f): Float = dot(other)
override fun toString(): String = "($x, $y, $z, $w)"
fun toVec4d(): Vec4d = Vec4d(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
fun toMutableVec4d(): MutableVec4d = toMutableVec4d(MutableVec4d())
fun toMutableVec4d(result: MutableVec4d): MutableVec4d = result.set(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
/**
* Checks vector components for equality (using '==' operator). For better numeric stability consider using
* [isFuzzyEqual].
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Vec4f) return false
if (x != other.x) return false
if (y != other.y) return false
if (z != other.z) return false
if (w != other.w) return false
return true
}
override fun hashCode(): Int {
var result = x.hashCode()
result = 31 * result + y.hashCode()
result = 31 * result + z.hashCode()
result = 31 * result + w.hashCode()
return result
}
companion object {
val ZERO = Vec4f(0f)
val X_AXIS = Vec4f(1f, 0f, 0f, 0f)
val Y_AXIS = Vec4f(0f, 1f, 0f, 0f)
val Z_AXIS = Vec4f(0f, 0f, 1f, 0f)
val W_AXIS = Vec4f(0f, 0f, 0f, 1f)
val NEG_X_AXIS = Vec4f(-1f, 0f, 0f, 0f)
val NEG_Y_AXIS = Vec4f(0f, -1f, 0f, 0f)
val NEG_Z_AXIS = Vec4f(0f, 0f, -1f, 0f)
val NEG_W_AXIS = Vec4f(0f, 0f, 0f, -1f)
}
}
open class MutableVec4f(x: Float, y: Float, z: Float, w: Float) : Vec4f(x, y, z, w) {
override var x
get() = this[0]
set(value) { this[0] = value }
override var y
get() = this[1]
set(value) { this[1] = value }
override var z
get() = this[2]
set(value) { this[2] = value }
override var w
get() = this[3]
set(value) { this[3] = value }
val array: FloatArray
get() = fields
constructor() : this(0f, 0f, 0f, 0f)
constructor(f: Float) : this(f, f, f, f)
constructor(xyz: Vec3f, w: Float) : this(xyz.x, xyz.y, xyz.z, w)
constructor(other: Vec4f) : this(other.x, other.y, other.z, other.w)
fun add(other: Vec4f): MutableVec4f {
x += other.x
y += other.y
z += other.z
w += other.w
return this
}
fun mul(other: Vec4f): MutableVec4f {
x *= other.x
y *= other.y
z *= other.z
w *= other.w
return this
}
fun norm(): MutableVec4f = scale(1f / length())
fun quatProduct(otherQuat: Vec4f): MutableVec4f {
val px = w * otherQuat.x + x * otherQuat.w + y * otherQuat.z - z * otherQuat.y
val py = w * otherQuat.y + y * otherQuat.w + z * otherQuat.x - x * otherQuat.z
val pz = w * otherQuat.z + z * otherQuat.w + x * otherQuat.y - y * otherQuat.x
val pw = w * otherQuat.w - x * otherQuat.x - y * otherQuat.y - z * otherQuat.z
set(px, py, pz, pw)
return this
}
fun scale(factor : Float): MutableVec4f {
x *= factor
y *= factor
z *= factor
w *= factor
return this
}
fun set(x: Float, y: Float, z: Float, w: Float): MutableVec4f {
this.x = x
this.y = y
this.z = z
this.w = w
return this
}
fun set(other: Vec4f): MutableVec4f {
x = other.x
y = other.y
z = other.z
w = other.w
return this
}
fun set(xyz: Vec3f, w: Float = 0f): MutableVec4f {
x = xyz.x
y = xyz.y
z = xyz.z
this.w = w
return this
}
fun subtract(other: Vec4f): MutableVec4f {
x -= other.x
y -= other.y
z -= other.z
w -= other.w
return this
}
operator fun plusAssign(other: Vec4f) { add(other) }
operator fun minusAssign(other: Vec4f) { subtract(other) }
open operator fun set(i: Int, v: Float) { fields[i] = v }
}
open class Vec4d(x: Double, y: Double, z: Double, w: Double) {
protected val fields = DoubleArray(4)
open val x get() = this[0]
open val y get() = this[1]
open val z get() = this[2]
open val w get() = this[3]
constructor(f: Double) : this(f, f, f, f)
constructor(xyz: Vec3d, w: Double) : this(xyz.x, xyz.y, xyz.z, w)
constructor(v: Vec4d) : this(v.x, v.y, v.z, v.w)
init {
fields[0] = x
fields[1] = y
fields[2] = z
fields[3] = w
}
fun add(other: Vec4d, result: MutableVec4d): MutableVec4d = result.set(this).add(other)
fun distance(other: Vec4d): Double = sqrt(sqrDistance(other))
fun dot(other: Vec4d): Double = x * other.x + y * other.y + z * other.z + w * other.w
/**
* Checks vector components for equality using [de.fabmax.kool.math.isFuzzyEqual], that is all components must
* have a difference less or equal [eps].
*/
fun isFuzzyEqual(other: Vec4d, eps: Double = FUZZY_EQ_D): Boolean =
isFuzzyEqual(x, other.x, eps) && isFuzzyEqual(y, other.y, eps) && isFuzzyEqual(z, other.z, eps) && isFuzzyEqual(w, other.w, eps)
fun length(): Double = sqrt(sqrLength())
fun mix(other: Vec4d, weight: Double, result: MutableVec4d): MutableVec4d {
result.x = other.x * weight + x * (1.0 - weight)
result.y = other.y * weight + y * (1.0 - weight)
result.z = other.z * weight + z * (1.0 - weight)
result.w = other.w * weight + w * (1.0 - weight)
return result
}
fun mul(other: Vec4d, result: MutableVec4d): MutableVec4d = result.set(this).mul(other)
fun norm(result: MutableVec4d): MutableVec4d = result.set(this).norm()
fun quatProduct(otherQuat: Vec4d, result: MutableVec4d): MutableVec4d {
result.x = w * otherQuat.x + x * otherQuat.w + y * otherQuat.z - z * otherQuat.y
result.y = w * otherQuat.y + y * otherQuat.w + z * otherQuat.x - x * otherQuat.z
result.z = w * otherQuat.z + z * otherQuat.w + x * otherQuat.y - y * otherQuat.x
result.w = w * otherQuat.w - x * otherQuat.x - y * otherQuat.y - z * otherQuat.z
return result
}
fun scale(factor: Double, result: MutableVec4d): MutableVec4d = result.set(this).scale(factor)
fun sqrDistance(other: Vec4d): Double {
val dx = x - other.x
val dy = y - other.y
val dz = z - other.z
val dw = z - other.w
return dx*dx + dy*dy + dz*dz + dw*dw
}
fun sqrLength(): Double = x*x + y*y + z*z + w*w
fun subtract(other: Vec4d, result: MutableVec4d): MutableVec4d = result.set(this).subtract(other)
fun getXyz(result: MutableVec3d): MutableVec3d {
result.x = x
result.y = y
result.z = z
return result
}
open operator fun get(i: Int): Double = fields[i]
operator fun times(other: Vec4d): Double = dot(other)
override fun toString(): String = "($x, $y, $z, $w)"
fun toVec4f(): Vec4f = Vec4f(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
fun toMutableVec4f(): MutableVec4f = toMutableVec4f(MutableVec4f())
fun toMutableVec4f(result: MutableVec4f): MutableVec4f = result.set(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
/**
* Checks vector components for equality (using '==' operator). For better numeric stability consider using
* [isFuzzyEqual].
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Vec4d) return false
if (x != other.x) return false
if (y != other.y) return false
if (z != other.z) return false
if (w != other.w) return false
return true
}
override fun hashCode(): Int {
var result = x.hashCode()
result = 31 * result + y.hashCode()
result = 31 * result + z.hashCode()
result = 31 * result + w.hashCode()
return result
}
companion object {
val ZERO = Vec4d(0.0)
val X_AXIS = Vec4d(1.0, 0.0, 0.0, 0.0)
val Y_AXIS = Vec4d(0.0, 1.0, 0.0, 0.0)
val Z_AXIS = Vec4d(0.0, 0.0, 1.0, 0.0)
val W_AXIS = Vec4d(0.0, 0.0, 0.0, 1.0)
val NEG_X_AXIS = Vec4d(-1.0, 0.0, 0.0, 0.0)
val NEG_Y_AXIS = Vec4d(0.0, -1.0, 0.0, 0.0)
val NEG_Z_AXIS = Vec4d(0.0, 0.0, -1.0, 0.0)
val NEG_W_AXIS = Vec4d(0.0, 0.0, 0.0, -1.0)
}
}
open class MutableVec4d(x: Double, y: Double, z: Double, w: Double) : Vec4d(x, y, z, w) {
override var x
get() = this[0]
set(value) { this[0] = value }
override var y
get() = this[1]
set(value) { this[1] = value }
override var z
get() = this[2]
set(value) { this[2] = value }
override var w
get() = this[3]
set(value) { this[3] = value }
constructor() : this(0.0, 0.0, 0.0, 0.0)
constructor(f: Double) : this(f, f, f, f)
constructor(xyz: Vec3d, w: Double) : this(xyz.x, xyz.y, xyz.z, w)
constructor(other: Vec4d) : this(other.x, other.y, other.z, other.w)
fun add(other: Vec4d): MutableVec4d {
x += other.x
y += other.y
z += other.z
w += other.w
return this
}
fun mul(other: Vec4d): MutableVec4d {
x *= other.x
y *= other.y
z *= other.z
w *= other.w
return this
}
fun norm(): MutableVec4d = scale(1.0 / length())
fun quatProduct(otherQuat: Vec4d): MutableVec4d {
val px = w * otherQuat.x + x * otherQuat.w + y * otherQuat.z - z * otherQuat.y
val py = w * otherQuat.y + y * otherQuat.w + z * otherQuat.x - x * otherQuat.z
val pz = w * otherQuat.z + z * otherQuat.w + x * otherQuat.y - y * otherQuat.x
val pw = w * otherQuat.w - x * otherQuat.x - y * otherQuat.y - z * otherQuat.z
set(px, py, pz, pw)
return this
}
fun scale(factor : Double): MutableVec4d {
x *= factor
y *= factor
z *= factor
w *= factor
return this
}
fun set(x: Double, y: Double, z: Double, w: Double): MutableVec4d {
this.x = x
this.y = y
this.z = z
this.w = w
return this
}
fun set(other: Vec4d): MutableVec4d {
x = other.x
y = other.y
z = other.z
w = other.w
return this
}
fun set(xyz: Vec3d, w: Double = 0.0): MutableVec4d {
x = xyz.x
y = xyz.y
z = xyz.z
this.w = w
return this
}
fun subtract(other: Vec4d): MutableVec4d {
x -= other.x
y -= other.y
z -= other.z
w -= other.w
return this
}
operator fun plusAssign(other: Vec4d) { add(other) }
operator fun minusAssign(other: Vec4d) { subtract(other) }
open operator fun set(i: Int, v: Double) { fields[i] = v }
}
open class Vec4i(x: Int, y: Int, z: Int, w: Int) {
protected val fields = IntArray(4)
open val x get() = this[0]
open val y get() = this[1]
open val z get() = this[2]
open val w get() = this[3]
constructor(f: Int) : this(f, f, f, f)
constructor(v: Vec4i) : this(v.x, v.y, v.z, v.w)
init {
fields[0] = x
fields[1] = y
fields[2] = z
fields[3] = w
}
open operator fun get(i: Int): Int = fields[i]
override fun toString(): String = "($x, $y, $z, $w)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Vec4i) return false
if (x != other.x) return false
if (y != other.y) return false
if (z != other.z) return false
if (w != other.w) return false
return true
}
override fun hashCode(): Int {
var result = x.hashCode()
result = 31 * result + y.hashCode()
result = 31 * result + z.hashCode()
result = 31 * result + w.hashCode()
return result
}
companion object {
val ZERO = Vec4i(0)
val X_AXIS = Vec4i(1, 0, 0, 0)
val Y_AXIS = Vec4i(0, 1, 0, 0)
val Z_AXIS = Vec4i(0, 0, 1, 0)
val W_AXIS = Vec4i(0, 0, 0, 1)
val NEG_X_AXIS = Vec4i(-1, 0, 0, 0)
val NEG_Y_AXIS = Vec4i(0, -1, 0, 0)
val NEG_Z_AXIS = Vec4i(0, 0, -1, 0)
val NEG_W_AXIS = Vec4i(0, 0, 0, -1)
}
}
open class MutableVec4i(x: Int, y: Int, z: Int, w: Int) : Vec4i(x, y, z, w) {
override var x
get() = this[0]
set(value) { this[0] = value }
override var y
get() = this[1]
set(value) { this[1] = value }
override var z
get() = this[2]
set(value) { this[2] = value }
override var w
get() = this[3]
set(value) { this[3] = value }
val array: IntArray
get() = fields
constructor() : this(0, 0, 0, 0)
constructor(f: Int) : this(f, f, f, f)
constructor(other: Vec4i) : this(other.x, other.y, other.z, other.w)
init {
fields[0] = x
fields[1] = y
fields[2] = z
fields[3] = w
}
fun set(x: Int, y: Int, z: Int, w: Int): MutableVec4i {
this.x = x
this.y = y
this.z = z
this.w = w
return this
}
fun set(other: Vec4i): MutableVec4i {
x = other.x
y = other.y
z = other.z
w = other.w
return this
}
open operator fun set(i: Int, v: Int) { fields[i] = v }
fun add(other: Vec4i): MutableVec4i {
x += other.x
y += other.y
z += other.z
w += other.w
return this
}
fun subtract(other: Vec4i): MutableVec4i {
x -= other.x
y -= other.y
z -= other.z
w -= other.w
return this
}
} | apache-2.0 | d3377416d0a5497265f9fdd3d428068f | 28.355752 | 140 | 0.543141 | 3.106387 | false | false | false | false |
jotomo/AndroidAPS | danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusBolus.kt | 1 | 1741 | package info.nightscout.androidaps.danar.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.danar.R
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
class MsgInitConnStatusBolus(
injector: HasAndroidInjector
) : MessageBase(injector) {
init {
SetCommand(0x0302)
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(bytes: ByteArray) {
if (bytes.size - 10 > 12) {
failed = true
return
}
failed = false
val bolusConfig = intFromBuff(bytes, 0, 1)
danaPump.isExtendedBolusEnabled = bolusConfig and 0x01 != 0
danaPump.bolusStep = intFromBuff(bytes, 1, 1) / 100.0
danaPump.maxBolus = intFromBuff(bytes, 2, 2) / 100.0
//int bolusRate = intFromBuff(bytes, 4, 8);
aapsLogger.debug(LTag.PUMPCOMM, "Is Extended bolus enabled: " + danaPump.isExtendedBolusEnabled)
aapsLogger.debug(LTag.PUMPCOMM, "Bolus increment: " + danaPump.bolusStep)
aapsLogger.debug(LTag.PUMPCOMM, "Bolus max: " + danaPump.maxBolus)
if (!danaPump.isExtendedBolusEnabled) {
val notification = Notification(Notification.EXTENDED_BOLUS_DISABLED, resourceHelper.gs(R.string.danar_enableextendedbolus), Notification.URGENT)
rxBus.send(EventNewNotification(notification))
} else {
rxBus.send(EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED))
}
}
} | agpl-3.0 | d0fb77f691efe9223eec5b19b18a0b29 | 42.55 | 157 | 0.714532 | 4.487113 | false | true | false | false |
androidx/androidx | work/work-runtime/src/main/java/androidx/work/impl/model/WorkProgress.kt | 3 | 1367 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.work.impl.model
import androidx.annotation.RestrictTo
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
import androidx.work.Data
/**
* A Database entity which stores progress of a given [WorkSpec] id.
*
* @hide
*/
@Entity(
foreignKeys = [ForeignKey(
entity = WorkSpec::class,
parentColumns = ["id"],
childColumns = ["work_spec_id"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)]
)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class WorkProgress(
@ColumnInfo(name = "work_spec_id")
@PrimaryKey
val workSpecId: String,
@ColumnInfo(name = "progress")
val progress: Data
) | apache-2.0 | 3cf94a047f52052afee6b5c0cddf9d95 | 28.73913 | 75 | 0.71763 | 4.155015 | false | false | false | false |
brianwernick/ExoMedia | demo/src/main/kotlin/com/devbrackets/android/exomediademo/playlist/BaseMediaApi.kt | 1 | 1165 | package com.devbrackets.android.exomediademo.playlist
import com.devbrackets.android.exomedia.listener.*
import com.devbrackets.android.exomediademo.data.MediaItem
import com.devbrackets.android.playlistcore.api.MediaPlayerApi
import com.devbrackets.android.playlistcore.listener.MediaStatusListener
abstract class BaseMediaApi : MediaPlayerApi<MediaItem>, OnPreparedListener, OnCompletionListener, OnErrorListener, OnSeekCompletionListener, OnBufferUpdateListener {
protected var bufferPercent: Int = 0
protected var statusListener: MediaStatusListener<MediaItem>? = null
override fun setMediaStatusListener(listener: MediaStatusListener<MediaItem>) {
statusListener = listener
}
override fun onCompletion() {
statusListener?.onCompletion(this)
}
override fun onError(e: Exception?): Boolean {
return statusListener?.onError(this) == true
}
override fun onPrepared() {
statusListener?.onPrepared(this)
}
override fun onSeekComplete() {
statusListener?.onSeekComplete(this)
}
override fun onBufferingUpdate(percent: Int) {
bufferPercent = percent
statusListener?.onBufferingUpdate(this, percent)
}
}
| apache-2.0 | 097f8eb158bac905d10451318a6d1352 | 30.486486 | 166 | 0.788841 | 4.854167 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/gradle/SettingsGradleFileIR.kt | 4 | 1656 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle
import kotlinx.collections.immutable.PersistentList
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter
data class SettingsGradleFileIR(
@NonNls val projectName: String,
val subProjects: List<String>,
override val irs: PersistentList<BuildSystemIR>
) : FileIR, GradleIR {
override fun withReplacedIrs(irs: PersistentList<BuildSystemIR>): SettingsGradleFileIR = copy(irs = irs)
override fun GradlePrinter.renderGradle() {
irsOfTypeOrNull<PluginManagementIR>()?.let { pluginManagementIrs ->
sectionCall("pluginManagement", needIndent = true) {
pluginManagementIrs.irsOfTypeOrNull<PluginManagementRepositoryIR>()?.let { repositories ->
sectionCall("repositories") {
repositories.distinctAndSorted().listNl()
}
}
nl()
freeIrs().removeSingleIRDuplicates().listNl()
}
}
nl()
+"rootProject.name = "; +projectName.quotified
nl(lineBreaks = 2)
if (subProjects.isNotEmpty()) {
nl()
subProjects.list(separator = { nl() }) { subProject ->
+"include("; +subProject.quotified; +")"
}
nl(lineBreaks = 2)
}
}
} | apache-2.0 | 2c095837f3756439c96104c4cf410543 | 39.414634 | 158 | 0.644324 | 4.842105 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/compiler-plugins/sam-with-receiver/gradle/src/org/jetbrains/kotlin/idea/compilerPlugin/samWithReceiver/gradleJava/SamWithReceiverGradleProjectImportHandler.kt | 4 | 1550 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.compilerPlugin.samWithReceiver.gradleJava
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.compilerPlugin.toJpsVersionAgnosticKotlinBundledPath
import org.jetbrains.kotlin.idea.gradleJava.compilerPlugin.AbstractAnnotationBasedCompilerPluginGradleImportHandler
import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverPluginNames
import org.jetbrains.kotlin.idea.gradleTooling.model.samWithReceiver.SamWithReceiverModel
class SamWithReceiverGradleProjectImportHandler : AbstractAnnotationBasedCompilerPluginGradleImportHandler<SamWithReceiverModel>() {
override val compilerPluginId = SamWithReceiverPluginNames.PLUGIN_ID
override val pluginName = "sam-with-receiver"
override val annotationOptionName = SamWithReceiverPluginNames.ANNOTATION_OPTION_NAME
override val pluginJarFileFromIdea = KotlinArtifacts.samWithReceiverCompilerPlugin.toJpsVersionAgnosticKotlinBundledPath()
override val modelKey = SamWithReceiverProjectResolverExtension.KEY
override fun getAnnotationsForPreset(presetName: String): List<String> {
for ((name, annotations) in SamWithReceiverPluginNames.SUPPORTED_PRESETS.entries) {
if (presetName == name) {
return annotations
}
}
return super.getAnnotationsForPreset(presetName)
}
}
| apache-2.0 | 1ca316191b9f45786500ddac6809674f | 56.407407 | 158 | 0.814194 | 5.677656 | false | false | false | false |
JetBrains/xodus | environment/src/main/kotlin/jetbrains/exodus/env/BitmapIterator.kt | 1 | 4276 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 jetbrains.exodus.env
import jetbrains.exodus.bindings.LongBinding
import jetbrains.exodus.bindings.LongBinding.compressedEntryToLong
import jetbrains.exodus.core.dataStructures.hash.LongIterator
import jetbrains.exodus.env.BitmapImpl.Companion.asEntry
import jetbrains.exodus.env.BitmapImpl.Companion.asLong
import java.io.Closeable
class BitmapIterator(
val txn: Transaction,
var store: StoreImpl,
private val direction: Int = 1
) : LongIterator, Closeable {
val cursor: Cursor = store.openCursor(txn)
private var current: Long? = null
private var next: Long? = null
private var key = 0L
private var value = 0L
private var bitIndex = 1
init {
if (direction != 1 && direction != -1) {
throw IllegalArgumentException("direction can only be 1 or -1")
}
}
override fun remove() {
current?.let { current ->
val keyEntry = LongBinding.longToCompressedEntry(current.key)
val bitmap = store.get(txn, keyEntry)?.asLong ?: 0L
(bitmap xor (1L shl current.index)).let {
if (it == 0L) {
store.delete(txn, keyEntry)
} else {
store.put(txn, keyEntry, it.asEntry)
}
}
this.current = null
return
}
throw IllegalStateException()
}
override fun hasNext(): Boolean {
if (next == null) {
setNext()
}
return next != null
}
override fun next(): Long = nextLong()
override fun nextLong(): Long {
if (hasNext()) {
current = next
next?.also {
setNext()
return it
}
}
throw NoSuchElementException()
}
override fun close() = cursor.close()
private fun setNext() {
while (value == 0L && if (direction == 1) cursor.next else cursor.prev) {
key = compressedEntryToLong(cursor.key)
value = cursor.value.asLong
bitIndex = if (direction == 1) 0 else 63
}
if (value != 0L) {
setNextBitIndex()
next = (key shl 6) + bitIndex
value -= 1L shl bitIndex
} else {
next = null
cursor.close()
}
}
private fun setNextBitIndex() {
while (value and 1L.shl(bitIndex) == 0L) {
bitIndex += direction
}
}
fun getSearchBit(bit: Long): Boolean {
val searchKey = bit.key
val searchIndex = bit.index
if (this.getSearchKey(searchKey)) {
val navigatedKey = compressedEntryToLong(cursor.key)
key = navigatedKey
value = cursor.value.asLong
bitIndex = if (navigatedKey != searchKey) if (direction > 0) 0 else 63
else {
if (direction > 0) {
// clear lower bits
value = (value shr searchIndex) shl searchIndex
} else {
// clear higher bits
val shiftBits = Long.SIZE_BITS - searchIndex - 1
value = (value shl shiftBits) ushr shiftBits
}
searchIndex
}
setNext()
return true
}
return false
}
private fun getSearchKey(searchKey: Long): Boolean {
var navigated = cursor.getSearchKeyRange(LongBinding.longToCompressedEntry(searchKey)) != null
if (direction < 0 && compressedEntryToLong(cursor.key) != searchKey) {
navigated = cursor.prev
}
return navigated
}
} | apache-2.0 | 905034ed20cda5ed20932020c8b53b1f | 29.992754 | 102 | 0.572264 | 4.602799 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-web-database/src/main/kotlin/com/onyx/server/DatabaseUserAccount.kt | 1 | 798 | package com.onyx.server
import com.onyx.entity.SystemUser
import io.undertow.security.idm.Account
import java.security.Principal
import java.util.HashSet
/**
* Created by timothy.osborn on 4/23/15.
*
* Auth account object
*/
class DatabaseUserAccount(@Suppress("MemberVisibilityCanPrivate") val user: SystemUser?) : Account {
private var roles: MutableSet<String>? = null
val password: String?
get() = user!!.password
override fun getPrincipal(): Principal? = user
override fun getRoles(): Set<String>? {
if (user == null) {
return null
}
if (roles == null) {
roles = HashSet()
if (user.role != null) {
roles!!.add(user.role!!.name)
}
}
return roles
}
}
| agpl-3.0 | d7f53da5ed2b3a203026b65601cccf8d | 21.166667 | 100 | 0.598997 | 4.15625 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/breakpoints/LineBreakpointExpressionVisitor.kt | 3 | 8696 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.core.breakpoints
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class ApplicabilityResult(val isApplicable: Boolean, val shouldStop: Boolean) {
companion object {
@JvmStatic
fun definitely(result: Boolean) = ApplicabilityResult(result, shouldStop = true)
@JvmStatic
fun maybe(result: Boolean) = ApplicabilityResult(result, shouldStop = false)
@JvmField
val UNKNOWN = ApplicabilityResult(isApplicable = false, shouldStop = false)
@JvmField
val DEFINITELY_YES = ApplicabilityResult(isApplicable = true, shouldStop = true)
@JvmField
val DEFINITELY_NO = ApplicabilityResult(isApplicable = false, shouldStop = true)
@JvmField
val MAYBE_YES = ApplicabilityResult(isApplicable = true, shouldStop = false)
}
}
class LineBreakpointExpressionVisitor private constructor(
private val document: Document,
private val mainLine: Int
) : KtVisitor<ApplicabilityResult, Unit?>() {
companion object {
@JvmStatic
fun of(file: VirtualFile, line: Int): LineBreakpointExpressionVisitor? {
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
return LineBreakpointExpressionVisitor(document, line)
}
}
override fun visitKtElement(element: KtElement, data: Unit?): ApplicabilityResult {
return visitChildren(element.children.asList(), data)
}
private fun visitChildren(children: List<PsiElement>, data: Unit?): ApplicabilityResult {
if (children.isEmpty() || !children.first().isSameLine()) {
return ApplicabilityResult.UNKNOWN
}
var isApplicable = false
for (child in children) {
val ktElement = child as? KtElement ?: continue
val result = ktElement.accept(this, data)
if (result.shouldStop) {
return result
}
isApplicable = isApplicable or result.isApplicable
}
return ApplicabilityResult.maybe(isApplicable)
}
override fun visitExpression(expression: KtExpression, data: Unit?): ApplicabilityResult {
if (expression.isSameLine()) {
val superResult = super.visitExpression(expression, data)
if (superResult.shouldStop) {
return superResult
}
return ApplicabilityResult.MAYBE_YES
}
return ApplicabilityResult.UNKNOWN
}
override fun visitClass(klass: KtClass, data: Unit?): ApplicabilityResult {
visitChildren(klass.primaryConstructorParameters, data).handle()?.let { return it }
return klass.body?.accept(this, data) ?: ApplicabilityResult.UNKNOWN
}
override fun visitObjectDeclaration(declaration: KtObjectDeclaration, data: Unit?): ApplicabilityResult {
return declaration.body?.accept(this, data) ?: ApplicabilityResult.UNKNOWN
}
override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor, data: Unit?): ApplicabilityResult {
return constructor.bodyExpression?.accept(this, data)
?.acceptIfMultiLineParent(constructor)
?: ApplicabilityResult.UNKNOWN
}
override fun visitParameter(parameter: KtParameter, data: Unit?): ApplicabilityResult {
val defaultValue = parameter.defaultValue
if (defaultValue.isSameLine()) {
return ApplicabilityResult.DEFINITELY_YES
}
return ApplicabilityResult.UNKNOWN
}
override fun visitCatchSection(catchClause: KtCatchClause, data: Unit?): ApplicabilityResult {
return ApplicabilityResult.MAYBE_YES
}
override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry, data: Unit?): ApplicabilityResult {
return ApplicabilityResult.UNKNOWN
}
override fun visitPackageDirective(directive: KtPackageDirective, data: Unit?): ApplicabilityResult {
return ApplicabilityResult.UNKNOWN
}
override fun visitImportDirective(importDirective: KtImportDirective, data: Unit?): ApplicabilityResult {
return ApplicabilityResult.UNKNOWN
}
override fun visitProperty(property: KtProperty, data: Unit?): ApplicabilityResult {
if (property.hasModifier(KtTokens.CONST_KEYWORD)) {
return ApplicabilityResult.UNKNOWN
}
return super.visitProperty(property, data)
}
override fun visitNamedFunction(function: KtNamedFunction, data: Unit?): ApplicabilityResult {
if (function.isSameLine() && KtPsiUtil.isLocal(function)) {
return ApplicabilityResult.MAYBE_YES
}
visitChildren(function.valueParameters, data).handle()?.let { return it }
return function.bodyExpression?.accept(this, data)
?.acceptIfMultiLineParent(function)
?: ApplicabilityResult.UNKNOWN
}
override fun visitPropertyAccessor(accessor: KtPropertyAccessor, data: Unit?): ApplicabilityResult {
return accessor.bodyExpression?.accept(this, data)
?.acceptIfMultiLineParent(accessor)
?: ApplicabilityResult.UNKNOWN
}
override fun visitPropertyDelegate(delegate: KtPropertyDelegate, data: Unit?): ApplicabilityResult {
return ApplicabilityResult.maybe(delegate.isSameLine())
}
override fun visitLambdaExpression(expression: KtLambdaExpression, data: Unit?): ApplicabilityResult {
if (expression.isSameLine()) {
return ApplicabilityResult.DEFINITELY_YES
}
return ApplicabilityResult.UNKNOWN
}
override fun visitWhenEntry(ktWhenEntry: KtWhenEntry, data: Unit?): ApplicabilityResult {
ktWhenEntry.expression?.accept(this, data)?.handle()?.let { return it }
return ApplicabilityResult.maybe(ktWhenEntry.conditions.isNotEmpty() || ktWhenEntry.isElse)
}
override fun visitDestructuringDeclaration(multiDeclaration: KtDestructuringDeclaration, data: Unit?): ApplicabilityResult {
return ApplicabilityResult.maybe(multiDeclaration.isSameLine())
}
override fun visitBlockExpression(expression: KtBlockExpression, data: Unit?): ApplicabilityResult {
return visitChildren(expression.statements, data)
}
override fun visitParenthesizedExpression(expression: KtParenthesizedExpression, data: Unit?): ApplicabilityResult {
val parenthesized = expression.expression ?: return ApplicabilityResult.UNKNOWN
val lines = parenthesized.getLines()
if (lines.start > mainLine) {
return ApplicabilityResult.UNKNOWN
}
if (lines.isMultiLine) {
return parenthesized.accept(this, data)
}
return ApplicabilityResult.UNKNOWN
}
private fun PsiElement?.isSameLine(): Boolean {
val lines = getLines()
return lines.start == mainLine
}
private fun PsiElement?.getLines(): Lines {
if (this == null) {
return Lines.EMPTY
}
val startOffset = maxOf(this.startOffset, this.textOffset)
val endOffset = this.endOffset
if (startOffset < 0 || endOffset < 0 || startOffset > endOffset) {
return Lines.EMPTY
}
val maxOffset = document.textLength
if (startOffset > maxOffset || endOffset > maxOffset) {
return Lines.EMPTY
}
val startLine = document.getLineNumber(startOffset)
val endLine = document.getLineNumber(endOffset)
return Lines(startLine, endLine)
}
private fun ApplicabilityResult.acceptIfMultiLineParent(parent: KtExpression): ApplicabilityResult? {
if (this.shouldStop) {
return this
}
if (parent.getLines().isSingleLine) {
return null
}
return this
}
}
private fun ApplicabilityResult.handle(): ApplicabilityResult? {
if (this.shouldStop || this.isApplicable) {
return this
}
return null
}
private class Lines(val start: Int, val end: Int) {
companion object {
val EMPTY = Lines(-1, -1)
}
val isSingleLine: Boolean
get() = start == end && start >= 0
val isMultiLine: Boolean
get() = start != end && start >= 0 && end >= 0
} | apache-2.0 | 91c28655cedb9606ecc325ec969da42f | 33.927711 | 128 | 0.682153 | 5.462312 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/MultiplePluginVersionGradleImportingTestCase.kt | 1 | 8086 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
/**
* This TestCase implements possibility to test import with different versions of gradle and different
* versions of gradle kotlin plugin
*/
package org.jetbrains.kotlin.idea.codeInsight.gradle
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.util.Disposer
import org.gradle.util.GradleVersion
import org.jetbrains.kotlin.gradle.ProjectInfo
import org.jetbrains.kotlin.idea.codeInsight.gradle.KotlinGradlePluginVersions.V_1_4_32
import org.jetbrains.kotlin.idea.codeInsight.gradle.KotlinGradlePluginVersions.V_1_5_32
import org.jetbrains.kotlin.idea.codeInsight.gradle.KotlinGradlePluginVersions.V_1_6_21
import org.jetbrains.kotlin.idea.codeInsight.gradle.KotlinGradlePluginVersions.V_1_7_20
import org.jetbrains.kotlin.tooling.core.KotlinToolingVersion
import org.jetbrains.plugins.gradle.tooling.util.VersionMatcher
import org.junit.Rule
import org.junit.runners.Parameterized
@Suppress("ACCIDENTAL_OVERRIDE")
abstract class MultiplePluginVersionGradleImportingTestCase : KotlinGradleImportingTestCase() {
sealed class KotlinVersionRequirement {
data class Exact(val version: KotlinToolingVersion) : KotlinVersionRequirement()
data class Range(
val lowestIncludedVersion: KotlinToolingVersion?, val highestIncludedVersion: KotlinToolingVersion?
) : KotlinVersionRequirement()
}
data class KotlinPluginVersionParam(
val version: KotlinToolingVersion,
val name: String = version.toString()
) {
override fun toString(): String = name
}
@Rule
@JvmField
var gradleAndKotlinPluginVersionMatchingRule = PluginTargetVersionsRule()
@JvmField
@Parameterized.Parameter(1)
var kotlinPluginVersionParam: KotlinPluginVersionParam? = null
val kotlinPluginVersion: KotlinToolingVersion
get() = checkNotNull(kotlinPluginVersionParam) {
"Missing 'kotlinPluginVersionParam'"
}.version
override fun setUp() {
super.setUp()
setupSystemProperties()
}
private fun setupSystemProperties() {
/*
Commonizer runner forwarded this property and failed, because IntelliJ might set a custom
ClassLoader, which will not be available for the Commonizer.
*/
if (kotlinPluginVersion < KotlinToolingVersion("1.5.20")) {
val classLoaderKey = "java.system.class.loader"
System.getProperty(classLoaderKey)?.let { configuredClassLoader ->
System.clearProperty(classLoaderKey)
Disposer.register(testRootDisposable) {
System.setProperty(classLoaderKey, configuredClassLoader)
}
}
}
val gradleNativeKey = "org.gradle.native"
System.getProperty(gradleNativeKey).let { configuredGradleNative ->
System.setProperty(gradleNativeKey, "false")
Disposer.register(testRootDisposable) {
if (configuredGradleNative == null) System.clearProperty(gradleNativeKey)
else System.setProperty(gradleNativeKey, configuredGradleNative)
}
}
}
companion object {
const val kotlinAndGradleParametersName: String = "Gradle-{0}, KotlinGradlePlugin-{1}"
@JvmStatic
@Suppress("ACCIDENTAL_OVERRIDE")
@Parameterized.Parameters(name = kotlinAndGradleParametersName)
fun data(): Collection<Array<Any>> {
val parameters = mutableListOf<Array<Any>>()
fun addVersions(
gradleVersion: String, kotlinVersion: KotlinToolingVersion, kotlinVersionName: String = kotlinVersion.toString()
) = parameters.add(arrayOf(gradleVersion, KotlinPluginVersionParam(kotlinVersion, kotlinVersionName)))
if (!IS_UNDER_SAFE_PUSH) {
addVersions("6.8.3", V_1_4_32)
addVersions("7.3.3", V_1_6_21)
addVersions("7.4.2", V_1_7_20)
}
addVersions(
"7.5.1", KotlinGradlePluginVersions.latest,
"${KotlinGradlePluginVersions.latest.major}.${KotlinGradlePluginVersions.latest.minor}"
)
return parameters
}
}
val androidProperties: Map<String, String>
get() = mapOf(
"android_gradle_plugin_version" to "7.3.0",
"compile_sdk_version" to "31",
"build_tools_version" to "28.0.3",
)
val isHmppEnabledByDefault get() = kotlinPluginVersion.isHmppEnabledByDefault
protected val hmppProperties: Map<String, String>
get() = mapOf(
"enable_hmpp_flags" to enableHmppProperties,
"disable_hmpp_flags" to disableHmppProperties
)
protected val enableHmppProperties: String
get() = if (isHmppEnabledByDefault) "" else """
kotlin.mpp.enableGranularSourceSetsMetadata=true
kotlin.native.enableDependencyPropagation=false
kotlin.mpp.enableHierarchicalCommonization=true
""".trimIndent()
protected val disableHmppProperties: String
get() = if (isHmppEnabledByDefault) "kotlin.mpp.hierarchicalStructureSupport=false" else ""
protected fun repositories(useKts: Boolean): String = GradleKotlinTestUtils.listRepositories(
useKts, GradleVersion.version(gradleVersion), kotlinPluginVersion
)
override val defaultProperties: Map<String, String>
get() = super.defaultProperties.toMutableMap().apply {
putAll(androidProperties)
putAll(hmppProperties)
put("kotlin_plugin_version", kotlinPluginVersion.toString())
put("kotlin_plugin_repositories", repositories(false))
put("kts_kotlin_plugin_repositories", repositories(true))
}
protected open fun checkProjectStructure(
exhaustiveModuleList: Boolean = true,
exhaustiveSourceSourceRootList: Boolean = true,
exhaustiveDependencyList: Boolean = true,
body: ProjectInfo.() -> Unit = {}
) {
org.jetbrains.kotlin.gradle.checkProjectStructure(
myProject,
projectPath,
exhaustiveModuleList,
exhaustiveSourceSourceRootList,
exhaustiveDependencyList,
false,
body
)
}
fun createHighlightingCheck(
testLineMarkers: Boolean = true,
severityLevel: HighlightSeverity = HighlightSeverity.GENERIC_SERVER_ERROR_OR_WARNING,
correspondingFilePostfix: String = ""
): HighlightingCheck {
return HighlightingCheck(
project = myTestFixture.project,
projectPath = projectPath,
testDataDirectory = testDataDirectory(),
testLineMarkers = testLineMarkers,
severityLevel = severityLevel,
correspondingFilePostfix = correspondingFilePostfix
)
}
fun checkHighlightingOnAllModules(testLineMarkers: Boolean = true) {
createHighlightingCheck(testLineMarkers).invokeOnAllModules()
}
}
fun MultiplePluginVersionGradleImportingTestCase.kotlinPluginVersionMatches(versionRequirement: String): Boolean {
return parseKotlinVersionRequirement(versionRequirement).matches(kotlinPluginVersion)
}
/**
* Since 1.8.0, because we no longer support 1.6 jvm target, we are going to merge
* kotlin-stdlib-jdk[7|8] into kotlin-stdlib. So we won't add the dependency to -jdk[7|8] by default.
* That was implemented in the kotlin/4441033134a383b718 commit, and then, the logic was temporarily reverted
* in the kotlin/928e0e7fb8b3 commit
*/
fun MultiplePluginVersionGradleImportingTestCase.isStdlibJdk78AddedByDefault() =
kotlinPluginVersion >= KotlinToolingVersion("1.5.0-M1")
fun MultiplePluginVersionGradleImportingTestCase.gradleVersionMatches(version: String): Boolean {
return VersionMatcher(GradleVersion.version(gradleVersion)).isVersionMatch(version, true)
}
| apache-2.0 | 3f067f64de57e8497557da9af9bbb3c8 | 39.43 | 158 | 0.692926 | 5.000618 | false | true | false | false |
smmribeiro/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/CreateSetterWithFieldAction.kt | 17 | 2122 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.java.actions
import com.intellij.codeInsight.daemon.QuickFixBundle.message
import com.intellij.codeInsight.generation.GenerateMembersUtil.generateSimpleSetterPrototype
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.lang.java.beans.PropertyKind
import com.intellij.lang.jvm.actions.CreateMethodRequest
import com.intellij.lang.jvm.actions.CreateWriteOnlyPropertyActionGroup
import com.intellij.lang.jvm.actions.JvmActionGroup
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiFile
import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass
/**
* This action renders a write-only property (field + setter) in Java class when setter is requested.
*/
internal class CreateSetterWithFieldAction(target: PsiClass, request: CreateMethodRequest) : CreatePropertyActionBase(target, request) {
override fun getActionGroup(): JvmActionGroup = CreateWriteOnlyPropertyActionGroup
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
return super.isAvailable(project, editor, file) && propertyInfo.second == PropertyKind.SETTER
}
override fun getText(): String {
return message("create.write.only.property.from.usage.full.text", getPropertyName(), getNameForClass(target, false))
}
override fun createRenderer(project: Project) = object : PropertyRenderer(project, target, request, propertyInfo) {
override fun fillTemplate(builder: TemplateBuilderImpl): RangeExpression? {
val prototypeField = generatePrototypeField()
val prototype = generateSimpleSetterPrototype(prototypeField, target)
val accessor = insertAccessor(prototype) ?: return null
val data = accessor.extractSetterTemplateData()
val typeExpression = builder.setupInput(data)
builder.setupSetterParameter(data)
return typeExpression
}
}
}
| apache-2.0 | d7ddd7609b4490e51dd439a5348e3b13 | 47.227273 | 140 | 0.799717 | 4.553648 | false | false | false | false |
Jire/Charlatano | src/main/kotlin/com/charlatano/scripts/BoneTrigger.kt | 1 | 1702 | /*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano.scripts
import com.charlatano.game.CSGO.clientDLL
import com.charlatano.game.angle
import com.charlatano.game.clientState
import com.charlatano.game.entity.position
import com.charlatano.game.me
import com.charlatano.game.offsets.ClientOffsets.dwForceAttack
import com.charlatano.scripts.aim.findTarget
import com.charlatano.settings.*
import com.charlatano.utils.*
import org.jire.kna.set
private val onBoneTriggerTarget = hook(1) {
if (ENABLE_BONE_TRIGGER) findTarget(
me.position(), clientState.angle(), false,
BONE_TRIGGER_FOV, BONE_TRIGGER_BONE, false
) >= 0
else false
}
fun boneTrigger() = onBoneTriggerTarget {
if (keyReleased(FIRE_KEY)) {
if (LEAGUE_MODE) mouse(MOUSEEVENTF_LEFTDOWN) else clientDLL[dwForceAttack] = 5.toByte()
Thread.sleep(8 + randLong(16))
if (LEAGUE_MODE) mouse(MOUSEEVENTF_LEFTUP) else clientDLL[dwForceAttack] = 4.toByte()
}
} | agpl-3.0 | a0e0d07f05f19d47f874b54a45d21d33 | 36.021739 | 89 | 0.76087 | 3.605932 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/model/statistics/StatisticsDataBuilder.kt | 1 | 3682 | package sk.styk.martin.apkanalyzer.model.statistics
import sk.styk.martin.apkanalyzer.manager.appanalysis.MAX_SDK_VERSION
import sk.styk.martin.apkanalyzer.model.InstallLocation
import sk.styk.martin.apkanalyzer.model.detail.AppSource
import java.util.*
class StatisticsDataBuilder(datasetSize: Int) {
private val arraySize = datasetSize + 1
private var analyzeSuccess = 0
private var analyzeFailed = 0
private var systemApps: Int = 0
private val installLocation = HashMap<InstallLocation, MutableList<String>>(3)
private val targetSdk = HashMap<Int, MutableList<String>>(MAX_SDK_VERSION)
private val minSdk = HashMap<Int, MutableList<String>>(MAX_SDK_VERSION)
private val appSource = HashMap<AppSource, MutableList<String>>(AppSource.values().size)
private val apkSize = FloatArray(arraySize)
private val signAlgorithm = HashMap<String, MutableList<String>>(5)
private val activities = FloatArray(arraySize)
private val services = FloatArray(arraySize)
private val providers = FloatArray(arraySize)
private val receivers = FloatArray(arraySize)
private val usedPermissions = FloatArray(arraySize)
private val definedPermissions = FloatArray(arraySize)
fun build(): StatisticsData {
return StatisticsData(
analyzeSuccess = PercentagePair(analyzeSuccess, analyzeSuccess + analyzeFailed),
analyzeFailed = PercentagePair(analyzeFailed, analyzeSuccess + analyzeFailed),
systemApps = PercentagePair(systemApps, analyzeSuccess),
installLocation = installLocation,
targetSdk = targetSdk,
minSdk = minSdk,
appSource = appSource,
apkSize = MathStatisticsBuilder(apkSize).build(),
signAlgorithm = signAlgorithm,
activities = MathStatisticsBuilder(activities).build(),
services = MathStatisticsBuilder(services).build(),
receivers = MathStatisticsBuilder(receivers).build(),
providers = MathStatisticsBuilder(providers).build(),
usedPermissions = MathStatisticsBuilder(usedPermissions).build(),
definedPermissions = MathStatisticsBuilder(definedPermissions).build(),
)
}
fun add(appData: StatisticsAppData?) {
if (appData == null) {
analyzeFailed++
return
}
analyzeSuccess++
if (appData.isSystemApp) systemApps++
addToMap(installLocation, InstallLocation.from(appData.installLocation), appData.packageName)
addToMap(targetSdk, appData.targetSdk, appData.packageName)
addToMap(minSdk, appData.minSdk, appData.packageName)
apkSize[analyzeSuccess] = appData.apkSize.toFloat()
addToMap(signAlgorithm, appData.signAlgorithm, appData.packageName)
addToMap(appSource, appData.appSource, appData.packageName)
activities[analyzeSuccess] = appData.activities.toFloat()
services[analyzeSuccess] = appData.services.toFloat()
providers[analyzeSuccess] = appData.providers.toFloat()
receivers[analyzeSuccess] = appData.receivers.toFloat()
usedPermissions[analyzeSuccess] = appData.usedPermissions.toFloat()
definedPermissions[analyzeSuccess] = appData.definedPermissions.toFloat()
}
private fun <T> addToMap(map: MutableMap<T, MutableList<String>>, key: T, packageName: String) {
var apps: MutableList<String>? = map[key]
if (apps != null) {
apps.add(packageName)
} else {
apps = mutableListOf(packageName)
}
map[key] = apps
}
}
| gpl-3.0 | 7ec85197156598bf0f1d27ce74ecdb7b | 40.370787 | 101 | 0.684954 | 4.902796 | false | false | false | false |
7449/Album | buildSrc/src/main/kotlin/Version.kt | 1 | 2487 | @file:Suppress("MemberVisibilityCanBePrivate")
object Plugin {
const val androidVersion = "7.3.1"
const val kotlinVersion = "1.7.20"
const val application = "com.android.application"
const val library = "com.android.library"
const val kotlin_android = "android"
const val kotlin_parcelize = "kotlin-parcelize"
}
object Version {
const val applicationId = "com.gallery.sample"
const val compileSdk = 33
const val minSdk = 21
const val targetSdk = 33
const val versionCode = 1
const val versionName = "1.0"
}
object Args {
const val moduleName = "-module-name"
const val prefix = "com.github.7449.album."
}
object Dep {
const val kotlin = "org.jetbrains.kotlin:kotlin-stdlib:${Plugin.kotlinVersion}"
const val appcompat = "androidx.appcompat:appcompat:1.5.1"
const val fragment = "androidx.fragment:fragment:1.5.4"
const val recyclerView = "androidx.recyclerview:recyclerview:1.2.1"
const val viewPager2 = "androidx.viewpager2:viewpager2:1.1.0-beta01"
const val material = "com.google.android.material:material:1.6.1"
const val cameraview = "com.otaliastudios:cameraview:2.7.2"
const val cropper = "com.theartofdev.edmodo:android-image-cropper:2.8.0"
const val glide = "com.github.bumptech.glide:glide:4.14.2"
}
object DepList {
/** scan dependencies */
val scan = mutableListOf(Dep.fragment, Dep.kotlin)
/** core dependencies */
val core = scan
.plus(Dep.appcompat)
.plus(Dep.viewPager2)
.plus(Dep.recyclerView)
/** compat dependencies */
val compat = core
/** material dependencies */
val material = compat
.plus(Dep.glide)
.plus(Dep.cropper)
/** wechat dependencies */
val wechat = compat
.plus(Dep.glide)
/** sample dependencies */
val sample = (scan + core + material + wechat)
.plus(Dep.material)
.plus(Dep.cameraview)
}
object DepLib {
/** core dependencies */
val core = mutableListOf(":scan")
/** compat dependencies */
val compat = core.plus(":core")
/** material dependencies */
val material = compat.plus(":compat")
/** wechat dependencies */
val wechat = compat.plus(":compat")
/** sample dependencies */
val sample = (wechat + material)
.plus(":wechat")
.plus(":material")
} | mpl-2.0 | bc34e391115927362444575b8c9da255 | 27.282353 | 83 | 0.618416 | 3.991974 | false | false | false | false |
marktony/ZhiHuDaily | app/src/main/java/com/marktony/zhihudaily/database/dao/ZhihuDailyNewsDao.kt | 1 | 1742 | /*
* Copyright 2016 lizhaotailang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marktony.zhihudaily.database.dao
import android.arch.persistence.room.*
import com.marktony.zhihudaily.data.ZhihuDailyNewsQuestion
/**
* Created by lizhaotailang on 2017/6/15.
*
* Interface for database access on [com.marktony.zhihudaily.data.ZhihuDailyNews] related operations.
*/
@Dao
interface ZhihuDailyNewsDao {
@Query("SELECT * FROM zhihu_daily_news WHERE timestamp <= :timestamp ORDER BY timestamp ASC")
fun queryAllByDate(timestamp: Long): List<ZhihuDailyNewsQuestion>
@Query("SELECT * FROM zhihu_daily_news WHERE id = :id")
fun queryItemById(id: Int): ZhihuDailyNewsQuestion?
@Query("SELECT * FROM zhihu_daily_news WHERE favorite = 1")
fun queryAllFavorites(): List<ZhihuDailyNewsQuestion>
@Query("SELECT * FROM zhihu_daily_news WHERE (timestamp < :timestamp) AND (favorite = 0)")
fun queryAllTimeoutItems(timestamp: Long): List<ZhihuDailyNewsQuestion>
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insertAll(items: List<ZhihuDailyNewsQuestion>)
@Update
fun update(item: ZhihuDailyNewsQuestion)
@Delete
fun delete(item: ZhihuDailyNewsQuestion)
}
| apache-2.0 | 8bcd9ab268055c226ab26da9bd36e8ad | 32.5 | 101 | 0.745121 | 4.079625 | false | false | false | false |
android/midi-samples | MidiTools/src/main/java/com/example/android/miditools/EventScheduler.kt | 1 | 6145 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.miditools
import kotlin.jvm.Volatile
import java.util.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* Store SchedulableEvents in a timestamped buffer.
* Events may be written in any order.
* Events will be read in sorted order.
* Events with the same timestamp will be read in the order they were added.
*
* Only one Thread can write into the buffer.
* And only one Thread can read from the buffer.
*/
open class EventScheduler {
private val lock = ReentrantLock()
private val condition = lock.newCondition()
private val mEventBuffer: SortedMap<Long, FastEventQueue>
// This does not have to be guarded. It is only set by the writing thread.
// If the reader sees a null right before being set then that is OK.
private var mEventPool: FastEventQueue? = null
// If we keep at least one node in the list then it can be atomic
// and non-blocking.
private inner class FastEventQueue(// One thread takes from the beginning of the list.
@field:Volatile var mFirst: SchedulableEvent?
) {
// A second thread returns events to the end of the list.
@Volatile
var mLast: SchedulableEvent?
@Volatile
var mEventsAdded: Long
@Volatile
var mEventsRemoved: Long
fun size(): Int {
return (mEventsAdded - mEventsRemoved).toInt()
}
/**
* Do not call this unless there is more than one event
* in the list.
* @return first event in the list
*/
fun remove(): SchedulableEvent {
// Take first event.
mEventsRemoved++
val event = mFirst
mFirst = event!!.mNext
return event
}
/**
* @param event
*/
fun add(event: SchedulableEvent) {
event.mNext = null
mLast!!.mNext = event
mLast = event
mEventsAdded++
}
init {
mLast = mFirst
mEventsAdded = 1 // Always created with one event added. Never empty.
mEventsRemoved = 0 // None removed yet.
}
}
/**
* Base class for events that can be stored in the EventScheduler.
*/
open class SchedulableEvent
/**
* @param timestamp
*/(
/**
* The timestamp should not be modified when the event is in the
* scheduling buffer.
*/
var timestamp: Long
) {
/**
* @return timestamp
*/
var mNext: SchedulableEvent? = null
}
/**
* Get an event from the pool.
* Always leave at least one event in the pool.
* @return event or null
*/
fun removeEventFromPool(): SchedulableEvent? {
var event: SchedulableEvent? = null
if (mEventPool != null && mEventPool!!.size() > 1) {
event = mEventPool!!.remove()
}
return event
}
/**
* Return events to a pool so they can be reused.
*
* @param event
*/
open fun addEventToPool(event: SchedulableEvent) {
if (mEventPool == null) {
mEventPool = FastEventQueue(event) // add event to pool
// If we already have enough items in the pool then just
// drop the event. This prevents unbounded memory leaks.
} else if (mEventPool!!.size() < MAX_POOL_SIZE) {
mEventPool!!.add(event)
}
}
/**
* Add an event to the scheduler. Events with the same time will be
* processed in order.
*
* @param event
*/
fun add(event: SchedulableEvent) {
lock.withLock {
var list = mEventBuffer[event.timestamp]
if (list == null) {
val lowestTime =
if (mEventBuffer.isEmpty()) Long.MAX_VALUE else mEventBuffer.firstKey()
list = FastEventQueue(event)
mEventBuffer[event.timestamp] = list
// If the event we added is earlier than the previous earliest
// event then notify any threads waiting for the next event.
if (event.timestamp < lowestTime) {
condition.signal()
}
} else {
list.add(event)
}
}
}
// Caller must synchronize on lock before calling.
private fun removeNextEventLocked(lowestTime: Long): SchedulableEvent {
val list = mEventBuffer[lowestTime]
// Remove list from tree if this is the last node.
if (list!!.size() == 1) {
mEventBuffer.remove(lowestTime)
}
return list.remove()
}
/**
* Check to see if any scheduled events are ready to be processed.
*
* @param time
* @return next event or null if none ready
*/
fun getNextEvent(time: Long): SchedulableEvent? {
var event: SchedulableEvent? = null
lock.withLock {
if (!mEventBuffer.isEmpty()) {
val lowestTime = mEventBuffer.firstKey()
// Is it time for this list to be processed?
if (lowestTime <= time) {
event = removeNextEventLocked(lowestTime)
}
}
}
// Log.i(TAG, "getNextEvent: event = " + event);
return event
}
companion object {
private const val MAX_POOL_SIZE = 200
}
init {
mEventBuffer = TreeMap()
}
} | apache-2.0 | a14978b9a665615f2f8b86503719c540 | 29.73 | 91 | 0.582913 | 4.644747 | false | false | false | false |
deltadak/plep | src/test/kotlin/nl/deltadak/plep/database/TaskFamilyTest.kt | 1 | 3445 | package nl.deltadak.plep.database
import nl.deltadak.plep.HomeworkTask
import nl.deltadak.plep.database.tables.SubTasks
import nl.deltadak.plep.database.tables.Tasks
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import java.time.LocalDate
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* Test the [TaskFamily] methods.
*/
object TaskFamilyTest : Spek({
given("database with tasks table") {
regularTransaction {
SchemaUtils.drop(Tasks)
SchemaUtils.create(Tasks)
}
val today = LocalDate.now()
val tomorrow = today.plusDays(1)
val todaytasks = listOf(
listOf(HomeworkTask(text = "today 1"),
HomeworkTask(text = "sub 1.1")),
listOf(HomeworkTask(text = "today 2"),
HomeworkTask(text = "sub 2.1"))
)
val tomorrowTask = listOf(listOf(HomeworkTask(text = "tomorrow 1"), HomeworkTask(text = "tomsub 1.1")))
on("inserting tasks in the database") {
TaskFamily.updateAllDay(today, todaytasks)
it("should store the new tasks in the database") {
val tasks = TaskFamily.getAllOnDay(today)
// The sets should be equal.
todaytasks.flatten().forEach { assertTrue { tasks.flatten().contains(it) } }
tasks.flatten().forEach { assertTrue { todaytasks.flatten().contains(it) } }
}
}
on("requesting all the tasks of a day") {
val tasks = TaskFamily.getAllOnDay(today)
it("should return all the tasks of that day") {
// The sets should be equal, order doesn't matter.
todaytasks.flatten().forEach { assertTrue { tasks.flatten().contains(it) } }
tasks.flatten().forEach { assertTrue { todaytasks.flatten().contains(it) } }
}
it("should not return tasks of any other day") {
tomorrowTask.forEach { it.forEach { task -> assertFalse { tasks.flatten().contains(task) } } }
}
it("should return the parent tasks as first in the lists") {
todaytasks.forEach { original -> assertTrue { tasks.map { it.first() }.contains(original.first()) } }
}
}
on("copying and inserting a task to a new day") {
val task = HomeworkTask(text = "today 1")
TaskFamily.copyAndInsert(tomorrow, task)
it("should insert the task on the new day") {
assertTrue { Tasks.getParentsOnDay(tomorrow).contains(task) }
}
}
on("deleting a task and its subtasks") {
val taskToBeDeleted = Tasks.getParentsOnDay(today).first()
TaskFamily.deleteAll(taskToBeDeleted.databaseID)
it("should delete the task") {
assertFalse { Tasks.getParentsOnDay(today).contains(taskToBeDeleted) }
}
it("should delete the subtasks") {
assertFalse {
regularTransaction {
SubTasks.selectAll().map { it[SubTasks.parentID] }
}.contains(taskToBeDeleted.databaseID)
}
}
}
}
}) | mit | c22a184f5041ffefea8169b2086a38c3 | 37.288889 | 117 | 0.58897 | 4.515072 | false | false | false | false |
cmcpasserby/MayaCharm | src/main/kotlin/settings/ApplicationSettings.kt | 1 | 3204 | package settings
import mayacomms.mayaFromMayaPy
import mayacomms.mayaPyExecutableName
import com.intellij.openapi.components.*
import com.jetbrains.python.sdk.PythonSdkUtil
import java.util.*
typealias SdkPortMap = MutableMap<String, ApplicationSettings.SdkInfo>
private val portRange = (4434..4534).toSet()
@State(
name = "MCAppSettings",
storages = [Storage(value = "mayacharm.settings.xml", roamingType = RoamingType.DISABLED)]
)
class ApplicationSettings : PersistentStateComponent<ApplicationSettings.State> {
data class SdkInfo(var mayaPyPath: String = "", var port: Int = -1) {
val mayaPath: String
get() = mayaFromMayaPy(mayaPyPath) ?: ""
}
data class State(var mayaSdkMapping: SdkPortMap = mutableMapOf())
private var myState = State()
companion object {
val INSTANCE: ApplicationSettings
get() = service()
}
init {
val mayaSdk =
PythonSdkUtil.getAllLocalCPythons().filter { it.homePath?.endsWith(mayaPyExecutableName) ?: false }
val homePaths = mayaSdk.map { it.homePath!! }
for (path in homePaths) {
mayaSdkMapping[path] = SdkInfo(path, -1)
}
assignEmptyPorts()
}
var mayaSdkMapping: SdkPortMap
get() = myState.mayaSdkMapping
set(value) {
myState.mayaSdkMapping = value
}
override fun getState(): State {
return myState
}
override fun loadState(state: State) {
val mayaPySdks =
PythonSdkUtil.getAllLocalCPythons().filter { x -> x.homePath?.endsWith(mayaPyExecutableName) ?: false }
val homePaths = mayaPySdks.map { it.homePath!! }
mayaSdkMapping.clear()
for (path in homePaths) {
if (state.mayaSdkMapping.containsKey(path)) {
mayaSdkMapping[path] = state.mayaSdkMapping[path]!!
continue
}
mayaSdkMapping[path] = SdkInfo(path, -1)
}
assignEmptyPorts()
}
fun refreshPythonSdks() {
val mayaSdk =
PythonSdkUtil.getAllLocalCPythons().filter { it.homePath?.endsWith(mayaPyExecutableName) ?: false }
val homePathsSet = mayaSdk.map { it.homePath!! }.toSet()
val sdkMappingKeySet = mayaSdkMapping.keys.toSet()
val toAdd = homePathsSet - sdkMappingKeySet
val toRemove = sdkMappingKeySet - homePathsSet
for (path in toRemove) {
mayaSdkMapping.remove(path)
}
for (path in toAdd) {
mayaSdkMapping[path] = SdkInfo(path, -1)
}
assignEmptyPorts()
}
private fun assignEmptyPorts() {
val usedPorts = mayaSdkMapping.map { it.value.port }.filter { it > 0 }.toSet()
val freePorts = PriorityQueue((portRange - usedPorts).sorted())
for (key in mayaSdkMapping.filter { it.value.port < 0 }.keys) {
mayaSdkMapping[key]!!.port = freePorts.remove()
}
}
fun getUnusedPort(): Int {
val usedPorts = mayaSdkMapping.map { it.value.port }.filter { it > 0 }.toSet()
val freePorts = PriorityQueue((portRange - usedPorts).sorted())
return freePorts.remove()
}
}
| mit | 233f26ec9b47c1eafebcac0fde2a602f | 29.514286 | 115 | 0.62578 | 4.188235 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/item/AutoPageScrollAction.kt | 1 | 4173 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.action.item
import android.app.AlertDialog
import android.os.Parcel
import android.os.Parcelable
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.action.SingleAction
import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity
import jp.hazuki.yuzubrowser.ui.app.StartActivityInfo
import java.io.IOException
class AutoPageScrollAction : SingleAction, Parcelable {
var scrollSpeed = 40
private set
@Throws(IOException::class)
constructor(id: Int, reader: JsonReader?) : super(id) {
if (reader != null) {
if (reader.peek() != JsonReader.Token.BEGIN_OBJECT) return
reader.beginObject()
while (reader.hasNext()) {
if (reader.peek() != JsonReader.Token.NAME) return
when (reader.nextName()) {
FIELD_NAME_SPEED -> scrollSpeed = reader.nextInt()
else -> reader.skipValue()
}
}
reader.endObject()
}
}
@Throws(IOException::class)
override fun writeIdAndData(writer: JsonWriter) {
writer.value(id)
writer.beginObject()
writer.name(FIELD_NAME_SPEED)
writer.value(scrollSpeed)
writer.endObject()
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(id)
dest.writeInt(scrollSpeed)
}
private constructor(source: Parcel) : super(source.readInt()) {
scrollSpeed = source.readInt()
}
override fun showMainPreference(context: ActionActivity): StartActivityInfo? {
return showSubPreference(context)
}
override fun showSubPreference(context: ActionActivity): StartActivityInfo? {
val view = View.inflate(context, R.layout.action_auto_scroll, null)
val editText = view.findViewById<EditText>(R.id.editText)
editText.setText(scrollSpeed.toString())
AlertDialog.Builder(context)
.setTitle(R.string.action_settings)
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
var y = 0
try {
y = Integer.parseInt(editText.text.toString())
} catch (e: NumberFormatException) {
e.printStackTrace()
}
if (y == 0) {
Toast.makeText(context.applicationContext, R.string.action_auto_scroll_speed_zero, Toast.LENGTH_SHORT).show()
showSubPreference(context)
return@setPositiveButton
}
scrollSpeed = y
}
.setNegativeButton(android.R.string.cancel, null)
.show()
return null
}
companion object {
private const val FIELD_NAME_SPEED = "0"
@JvmField
val CREATOR: Parcelable.Creator<AutoPageScrollAction> = object : Parcelable.Creator<AutoPageScrollAction> {
override fun createFromParcel(source: Parcel): AutoPageScrollAction {
return AutoPageScrollAction(source)
}
override fun newArray(size: Int): Array<AutoPageScrollAction?> {
return arrayOfNulls(size)
}
}
}
}
| apache-2.0 | cf37a126298d023947a57b3399576371 | 33.204918 | 133 | 0.619698 | 4.646993 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/DistanceCommand.kt | 1 | 4918 | package com.rpkit.essentials.bukkit.command
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.core.util.MathUtils
import com.rpkit.essentials.bukkit.RPKEssentialsBukkit
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.tracking.bukkit.tracking.RPKTrackingProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class DistanceCommand(private val plugin: RPKEssentialsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (sender.hasPermission("rpkit.essentials.command.distance")) {
if (sender is Player) {
if (args.isNotEmpty()) {
val bukkitPlayer = plugin.server.getPlayer(args[0])
if (bukkitPlayer != null) {
if (bukkitPlayer.world === sender.world) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val trackingProvider = plugin.core.serviceManager.getServiceProvider(RPKTrackingProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null) {
if (!trackingProvider.isTrackable(character)) {
sender.sendMessage(plugin.messages["distance-invalid-untrackable"])
bukkitPlayer.sendMessage(plugin.messages["distance-untrackable-notification", mapOf(
Pair("player", minecraftProfile.minecraftUsername)
)])
return true
}
val itemRequirement = plugin.config.getItemStack("distance-command.item-requirement")
if (itemRequirement != null && !bukkitPlayer.inventory.containsAtLeast(itemRequirement, itemRequirement.amount)) {
sender.sendMessage(plugin.messages["distance-invalid-item", mapOf(
Pair("amount", itemRequirement.amount.toString()),
Pair("type", itemRequirement.type.toString().toLowerCase().replace('_', ' '))
)])
return true
}
val maximumDistance = plugin.config.getInt("distance-command.maximum-distance")
val distance = MathUtils.fastSqrt(bukkitPlayer.location.distanceSquared(sender.location))
if (maximumDistance >= 0 && distance > maximumDistance) {
sender.sendMessage(plugin.messages["distance-invalid-distance"])
return true
}
sender.sendMessage(plugin.messages["distance-valid", mapOf(
Pair("character", character.name),
Pair("player", minecraftProfile.minecraftUsername),
Pair("distance", distance.toString())
)])
} else {
sender.sendMessage(plugin.messages["no-character"])
}
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["distance-invalid-world"])
}
} else {
sender.sendMessage(plugin.messages["distance-invalid-offline"])
}
} else {
sender.sendMessage(plugin.messages["distance-usage"])
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-distance"])
}
return true
}
}
| apache-2.0 | 5b9a495b902c9e07ae298230eab90da6 | 61.253165 | 150 | 0.509557 | 6.691156 | false | false | false | false |
like5188/Common | sample/src/main/java/com/like/common/sample/dialog/OneButtonNoTitleDialog.kt | 1 | 1149 | package com.like.common.sample.dialog
import android.os.Bundle
import com.like.common.sample.R
import com.like.common.sample.databinding.DialogFragmentOneButtonNoTitleBinding
import com.like.common.util.BaseDialogFragment
class OneButtonNoTitleDialog : BaseDialogFragment<DialogFragmentOneButtonNoTitleBinding>() {
companion object {
val KEY_MESSAGE = "key_message"
val KEY_BUTTON_NAME = "key_button_name"
}
override fun initView(binding: DialogFragmentOneButtonNoTitleBinding, arguments: Bundle?) {
binding.rlOuter.setOnClickListener {
hide()
}
if (arguments != null) {
val message = arguments.getString(OneButtonNoTitleDialog.KEY_MESSAGE)
val buttonName = arguments.getString(OneButtonNoTitleDialog.KEY_BUTTON_NAME)
binding.tvMessage.text = message
binding.tvButton.text = buttonName
binding.tvButton.setOnClickListener {
hide()
}
}
}
override fun cancelable() = false
override fun getDialogFragmentLayoutResId(): Int = R.layout.dialog_fragment_one_button_no_title
}
| apache-2.0 | b3d32619d38df61484461529d1ad2aad | 31.828571 | 99 | 0.691906 | 4.419231 | false | false | false | false |
blhps/lifeograph-android | app/src/main/java/net/sourceforge/lifeograph/Lifeograph.kt | 1 | 16638 | /* *********************************************************************************
Copyright (C) 2012-2021 Ahmet Öztürk ([email protected])
This file is part of Lifeograph.
Lifeograph 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.
Lifeograph 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 Lifeograph. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
package net.sourceforge.lifeograph
import android.app.AlertDialog
import android.app.Application
import android.content.Context
import android.content.DialogInterface
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import androidx.navigation.Navigation
import net.sourceforge.lifeograph.helpers.Result
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.lang.StringBuilder
class Lifeograph : Application() {
override fun onCreate() {
mInstance = this
super.onCreate()
}
// class MutableBool {
// constructor() {
// v = false
// }
//
// constructor(v0: Boolean) {
// v = v0
// }
//
// var v: Boolean
// }
class MutableInt {
constructor() {
v = 0
}
constructor(v0: Int) {
v = v0
}
@JvmField
var v: Int
}
class MutableString {
// constructor(v0: String) {
// v = v0
// }
@JvmField
var v: String = ""
}
companion object {
// CONSTANTS ===============================================================================
//public static final String PROGRAM_NAME = "Lifeograph";
const val LIFEOGRAPH_RELEASE_CODENAME = "the spring of goliath"
const val LANG_INHERIT_DIARY = "d"
const val MI_TO_KM_RATIO = 1.609344
lateinit var mActivityMain: ActivityMain
@JvmStatic
val context: Context
get() = mInstance!!
fun getActionBar(): ActionBar {
return mActivityMain.mActionBar!!
}
// VARIABLES ===============================================================================
@JvmField
var sOptImperialUnits = false
// LIFEOGRAPH APPLICATION-WIDE FUNCTIONALITY ===============================================
@JvmStatic
fun getTodoIcon(es: Int): Int {
return when(es) {
DiaryElement.ES_PROGRESSED -> R.drawable.ic_todo_progressed
DiaryElement.ES_DONE -> R.drawable.ic_todo_done
DiaryElement.ES_CANCELED -> R.drawable.ic_todo_canceled
//DiaryElement.ES_TODO -> R.drawable.ic_todo_open
else -> R.drawable.ic_todo_open
}
}
@JvmStatic
fun goToToday() {
if(BuildConfig.DEBUG && !Diary.d.is_open) {
throw AssertionError("Assertion failed")
}
var entry = Diary.d._entry_today
if(entry == null) // add new entry if no entry exists on selected date
entry = Diary.d.add_today()
showElem(entry)
}
@JvmStatic
fun addEntry(date0: Long, text: String?) {
var date = date0
if(BuildConfig.DEBUG && !Diary.d.is_in_edit_mode) {
throw AssertionError("Assertion failed")
}
if(!Date.is_ordinal(date) && Date.get_order_3rd(date) == 0) date++ // fix order
val entry = Diary.d.create_entry(date, text)
if(entry != null) showElem(entry)
}
@JvmStatic
fun duplicateEntry(entrySrc: Entry, title: String): Entry {
val entry = Diary.d.create_entry(entrySrc._date_t, title)
for((i, para) in entrySrc.m_paragraphs.withIndex())
if(i > 0)
entry.add_paragraph(para.m_text)
return entry
}
@JvmStatic
fun showElem(elem: DiaryElement) {
if(BuildConfig.DEBUG && !Diary.d.is_open) {
throw AssertionError("Assertion failed")
}
mActivityMain.showElem(elem)
}
fun enableEditing(editor: FragmentDiaryEditor) {
// HANDLE OLD DIARY
if(Diary.d.is_old) {
showConfirmationPrompt(
editor.context,
R.string.diary_upgrade_confirm,
R.string.upgrade_diary
) { _: DialogInterface?, _: Int -> enableEditing2(editor) }
return
}
enableEditing2(editor)
}
private fun enableEditing2(editor: FragmentDiaryEditor) {
if(!Diary.d.can_enter_edit_mode()) return
if(Diary.d.enable_editing() != Result.SUCCESS) return
editor.enableEditing()
}
fun logoutWithoutSaving(view: View) {
if(Diary.d.is_open) {
showConfirmationPrompt(view.context,
R.string.logoutwosaving_confirm,
R.string.logoutwosaving
) { _: DialogInterface?, _: Int ->
// unlike desktop version Android version
// does not back up changes
Diary.d.setSavingEnabled(false)
Navigation.findNavController(view)
.navigate(R.id.nav_diaries)
}
}
}
// ANDROID & JAVA HELPERS ======================================================================
const val TAG = "LFO"
private var mInstance: Lifeograph? = null
@JvmField
var screenWidth = 0.0f
@JvmField
var screenHeight = 0.0f
@JvmField
var sDPIX = 0.0f
private var sDPIY = 0.0f
const val MIN_HEIGHT_FOR_NO_EXTRACT_UI = 6.0
@JvmStatic
fun getStr(i: Int): String {
if(BuildConfig.DEBUG && mInstance == null) {
error("Assertion failed")
}
return mInstance!!.getString(i)
}
@JvmStatic
fun showConfirmationPrompt(context: Context?,
message: Int,
positiveText: Int,
posListener: DialogInterface.OnClickListener?) {
val builder = AlertDialog.Builder(context, R.style.LifeoAlertDlgTheme)
builder.setMessage(message)
.setPositiveButton(positiveText, posListener)
.setNegativeButton(R.string.cancel, null)
.show()
}
@JvmStatic
fun showConfirmationPrompt(context: Context?,
message: Int,
positiveText: Int,
posListener: DialogInterface.OnClickListener?,
negativeText: Int,
negListener: DialogInterface.OnClickListener?) {
val builder = AlertDialog.Builder(context, R.style.LifeoAlertDlgTheme)
builder.setMessage(message)
.setPositiveButton(positiveText, posListener)
.setNegativeButton(negativeText, negListener)
.show()
}
// fun showSnack(view: View?, message: String?) {
// Snackbar.make(view!!, message!!, Snackbar.LENGTH_LONG)
// .setAction("Action", null).show()
// }
@JvmStatic
fun showToast(message: String?) {
Toast.makeText(mInstance, message, Toast.LENGTH_LONG).show()
}
@JvmStatic
fun showToast(message: Int) {
Toast.makeText(mInstance, message, Toast.LENGTH_LONG).show()
}
@JvmStatic
fun joinPath(p1: String, p2: String): String {
val file1 = File(p1)
return File(file1, p2).path
}
@JvmStatic
@Throws(IOException::class)
fun copyFile(src: File?, dst: File?) {
FileInputStream(src).use { `in` ->
FileOutputStream(dst).use { out ->
// Transfer bytes from in to out
val buf = ByteArray(1024)
var len: Int
while(`in`.read(buf).also { len = it } > 0) {
out.write(buf, 0, len)
}
}
}
}
// public static String getEnvLang() {
// return Locale.getDefault().getLanguage();
// }
// public static void initializeConstants( Context ctx ) {
// sContext = ctx;
// sIsLargeScreen = ( ctx.getResources().getConfiguration().screenLayout
// & Configuration.SCREENLAYOUT_SIZE_MASK ) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
// }
fun updateScreenSizes(context: Context) {
val wm = context.getSystemService(WINDOW_SERVICE) as WindowManager
val metrics = DisplayMetrics()
wm.defaultDisplay.getMetrics(metrics)
screenWidth = metrics.widthPixels / metrics.xdpi
screenHeight = metrics.heightPixels / metrics.ydpi
sDPIX = metrics.xdpi
sDPIY = metrics.ydpi
Log.d(TAG, "Updated the sizes: " + screenWidth + "x" + screenHeight)
}
// instead of below, use dimens.xml as much as possible:
// static int
// getPixelsAsDP( int pixels ) {
// final float scale = mActivityMain.getResources().getDisplayMetrics().density;
// return (int) ( pixels * scale + 0.5f );
// }
@JvmStatic
val screenShortEdge: Float
get() = screenHeight.coerceAtMost(screenWidth)
// public static boolean isLargeScreen() {
// return sIsLargeScreen;
// }
// static boolean isExternalStorageWritable() {
// String state = Environment.getExternalStorageState();
// return Environment.MEDIA_MOUNTED.equals( state );
// }
@JvmStatic
fun getLine(source: String, o: MutableInt, line: MutableString): Boolean {
if(source.isEmpty() || o.v >= source.length) return false
val oEnd = source.indexOf('\n', o.v)
if(oEnd == -1) {
line.v = source.substring(o.v)
o.v = source.length
}
else {
line.v = source.substring(o.v, oEnd)
o.v = oEnd + 1
}
return true
}
@JvmStatic
fun getLong(line: String, i: MutableInt): Long {
var result: Long = 0
while(i.v < line.length && line[i.v] >= '0' && line[i.v] <= '9') {
result = result * 10 + line[i.v].toLong() - '0'.toLong()
i.v++
}
return result
}
@JvmStatic
fun getInt(line: String, i: MutableInt): Int {
var result = 0
while(i.v < line.length && line[i.v] >= '0' && line[i.v] <= '9') {
result = result * 10 + line[i.v].toInt() - '0'.toInt()
i.v++
}
return result
}
@JvmStatic
fun getDouble(text: String): Double {
//NOTE: this implementation may be a little bit more forgiving than good for health
var value = 0.0
//char lf{ '=' }; // =, \, #, $(unit)
var divider = 0
var negative = false
var c: Char
for(element in text) {
c = element
when(c) {
',', '.' -> if(divider == 0) // note that if divider
divider = 1
'-' -> negative = true
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> {
value *= 10.0
value += (c - '0').toDouble()
if(divider != 0) divider *= 10
}
else -> {
}
}
}
if(divider > 1) value /= divider.toDouble()
if(negative) value *= -1.0
return value
}
@JvmStatic
fun getDouble(line: String, i: MutableInt): Double {
var value = 0.0
var divider = 0
var negative = false
var fContinue = true
var c: Char
while(i.v < line.length && fContinue) {
c = line[i.v]
when(c) {
',', '.' -> if(divider == 0) // note that if divider
divider = 1
'-' -> negative = true
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> {
value *= 10.0
value += (c - '0').toDouble()
if(divider != 0) divider *= 10
}
else -> {
i.v--
fContinue = false // end loop
}
}
i.v++
}
if(divider > 1) value /= divider.toDouble()
if(negative) value *= -1.0
return value
}
fun formatNumber(number: Double): String {
val result = number.toString()
val posPoint = result.indexOfFirst { c: Char -> (c == '.') or (c == ',') }
val size = result.length
if( posPoint == -1 )
return result
val str = StringBuilder() // decimals separator
var decimalCnt = 0
for(p in size-1 downTo 0) {
when {
p == posPoint -> {
str.insert(0, '.')
}
p < (posPoint - 3) && posPoint > 4 && ((posPoint - 1 - p) % 3) == 0 -> {
str.insert(0, ' ')
str.insert(0, result[p])
}
p > posPoint && (decimalCnt > 0 || result[p] != '0') -> {
str.insert(0, result[p])
decimalCnt++
}
else -> {
str.insert(0, result[p])
}
}
}
return str.toString()
}
// TODO WILL BE IMPLEMENTED LATER
// protected void import_messages() {
// Cursor cursor =
// getContentResolver().query( Uri.parse( "content://sms/inbox" ), null, null, null,
// null );
// cursor.moveToFirst();
//
// do {
// String body = new String();
// Calendar cal = Calendar.getInstance();
//
// for( int idx = 0; idx < cursor.getColumnCount(); idx++ ) {
// String msgData = cursor.getColumnName( idx );
//
// if( msgData.compareTo( "body" ) == 0 )
// body = cursor.getString( idx );
// else if( msgData.compareTo( "date" ) == 0 )
// cal.setTimeInMillis( cursor.getLong( idx ) );
// }
//
// Diary.diary.create_entry( new Date( cal.get( Calendar.YEAR ),
// cal.get( Calendar.MONTH ) + 1,
// cal.get( Calendar.DAY_OF_MONTH ) ), body, false );
// }
// while( cursor.moveToNext() );
//
// }
}
}
| gpl-3.0 | 97ad9739ea63c9844f0873f087ef59e1 | 35.086768 | 108 | 0.462551 | 4.80254 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/model/SpeakersLoader.kt | 1 | 1042 | package com.openconference.model
import com.openconference.model.database.dao.SpeakerDao
import rx.Observable
/**
* Responsible to load Speakers
*
* @author Hannes Dorfmann
*/
interface SpeakersLoader {
/**
* Get a list of all speakers
*/
fun allSpeakers(): Observable<List<Speaker>>
fun getSpeaker(id: String): Observable<Speaker>
}
/**
* A [SpeakersLoader] that uses the speakers from local database
*/
class LocalStorageSpeakersLoader(private val scheduleDataAwareObservableFactory: ScheduleDataAwareObservableFactory, private val speakerDao: SpeakerDao) : SpeakersLoader {
override fun allSpeakers(): Observable<List<Speaker>> = scheduleDataAwareObservableFactory.create(
speakerDao.getSpeakers())
override fun getSpeaker(id: String): Observable<Speaker> =
scheduleDataAwareObservableFactory.create(
speakerDao.getSpeaker(id)).map {
if (it == null) throw SpeakerNotFoundException(
"Speaker with the id = $id has not been found in database")
else it
}
} | apache-2.0 | a61b1f0309c1bd4f082f343b203fce5b | 27.189189 | 171 | 0.732246 | 4.396624 | false | false | false | false |
daemontus/Distributed-CTL-Model-Checker | src/main/kotlin/com/github/sybila/checker/ModelChecker.kt | 3 | 9319 | package com.github.sybila.checker
import com.github.sybila.checker.channel.SingletonChannel
import com.github.sybila.checker.operator.*
import com.github.sybila.checker.partition.SingletonPartition
import com.github.sybila.huctl.*
import java.io.Closeable
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.Executors
/**
* Read Me:
*
* State identifiers are integers and should be unique across the whole system.
* (If you have more than 2^31 states, you are going to time-out anyway)
* Reason: They are easy to serialize and pass around.
*
* Params don't have any direct operations, everything is implemented in the solver.
* The checker/communicator ensures that:
* - only colors created by the solver are passed to it as parameters
* - only one thread can access a specific solver at a time
* - colors are transferred between solvers:
* - in a solver-agnostic format (ByteBuffer)
* - using clone operation which locks both outgoing and incoming solver
*/
interface Operator<out Params : Any> {
fun compute(): StateMap<Params>
}
class SequentialChecker<out Params : Any>(model: Model<Params>) : Closeable {
private val checker = Checker(model)
fun verify(formula: Formula): StateMap<Params> = verify(mapOf("formula" to formula))["formula"]!!
fun verify(formulas: Map<String, Formula>): Map<String, StateMap<Params>>
= checker.verify(formulas).mapValues { it.value.first() }
override fun close() {
checker.close()
}
}
class Checker<Params : Any>(
private val config: List<Channel<Params>>
) : Closeable {
constructor(model: Model<Params>) : this(listOf(SingletonChannel(SingletonPartition(model))))
private val executor = Executors.newFixedThreadPool(config.size)
fun verify(formula: Formula): List<StateMap<Params>> = verify(mapOf("formula" to formula))["formula"]!!
fun verify(formulas: Map<String, Formula>): Map<String, List<StateMap<Params>>> {
synchronized(this) {
val result: List<Map<String, StateMap<Params>>> = config.map {
Worker(it)
}.map {
executor.submit(Callable<Map<String, StateMap<Params>>> {
it.verify(formulas)
})
}.map {
it.get()
}
return formulas.mapValues { name ->
result.map { it[name.key]!! }
}
}
}
override fun close() {
executor.shutdown()
}
}
private class Worker<out Params : Any>(
private val channel : Channel<Params>
) {
fun verify(formulas: Map<String, Formula>): Map<String, StateMap<Params>> {
val dependencyTree: Map<String, Pair<Formula, Operator<Params>>> = HashMap<Formula, Operator<Params>>().let { tree ->
fun resolve(formula: Formula): Operator<Params> {
//TODO: caching is still suboptimal, because the references are not canonical, so
//exists s: forall x: x && s and exists s: forall z: z && s will create two separate trees
val key = formula
return tree.computeIfAbsent(key) {
@Suppress("USELESS_CAST", "RemoveExplicitTypeArguments")
when (key) {
is Formula.Atom -> when (key) {
is Formula.Atom.False -> FalseOperator(channel)
is Formula.Atom.True -> TrueOperator(channel)
is Formula.Atom.Reference -> ReferenceOperator(key.name.toInt(), channel)
is Formula.Atom.Float -> FloatOperator(key, channel)
is Formula.Atom.Transition -> TransitionOperator(key, channel)
}
is Formula.Not -> ComplementOperator(resolve(True), resolve(key.inner), channel)
is Formula.Bool<*> -> when (key as Formula.Bool<*>) {
is Formula.Bool.And -> AndOperator(resolve(key.left), resolve(key.right), channel)
is Formula.Bool.Or -> OrOperator(resolve(key.left), resolve(key.right), channel)
is Formula.Bool.Implies -> resolve(not(key.left) or key.right)
is Formula.Bool.Equals -> resolve((key.left and key.right) or (not(key.left) and not(key.right)))
}
is Formula.Simple<*> -> when (key as Formula.Simple<*>) {
is Formula.Simple.Next -> if (key.quantifier.isExistential()) {
ExistsNextOperator(key.quantifier.isNormalTimeFlow(), key.direction, resolve(key.inner), channel)
} else {
AllNextOperator(key.quantifier.isNormalTimeFlow(), key.direction, resolve(key.inner), channel)
}
//Until operators are not slower, because the path null check is fast and predictable
is Formula.Simple.Future -> if (key.quantifier.isExistential()) {
ExistsUntilOperator(key.quantifier.isNormalTimeFlow(), key.direction, false, null, resolve(key.inner), channel)
} else {
AllUntilOperator(key.quantifier.isNormalTimeFlow(), key.direction, false, null, resolve(key.inner), channel)
}
is Formula.Simple.WeakFuture -> if (key.quantifier.isExistential()) {
ExistsUntilOperator(key.quantifier.isNormalTimeFlow(), key.direction, true, null, resolve(key.inner), channel)
} else {
AllUntilOperator(key.quantifier.isNormalTimeFlow(), key.direction, true, null, resolve(key.inner), channel)
}
//EwX = !AX!
//AwX = !EX!
is Formula.Simple.WeakNext -> resolve(not(Formula.Simple.Next(
key.quantifier.invertCardinality(),
not(key.inner), key.direction
)))
//EG = !AF! / !AwF!
//AG = !EG! / !EwF!
is Formula.Simple.Globally -> if (key.direction == DirectionFormula.Atom.True) {
resolve(not(Formula.Simple.Future(
key.quantifier.invertCardinality(),
not(key.inner), key.direction
)))
} else {
resolve(not(Formula.Simple.WeakFuture(
key.quantifier.invertCardinality(),
not(key.inner), key.direction
)))
}
else -> throw IllegalStateException()
}
is Formula.Until -> if (key.quantifier.isExistential()) {
ExistsUntilOperator(key.quantifier.isNormalTimeFlow(), key.direction, false, resolve(key.path), resolve(key.reach), channel)
} else {
AllUntilOperator(key.quantifier.isNormalTimeFlow(), key.direction, false, resolve(key.path), resolve(key.reach), channel)
}
is Formula.FirstOrder<*> -> when (key as Formula.FirstOrder<*>) {
//TODO: This is a bug apparently - Params needs to be specified because of list nullity
is Formula.FirstOrder.ForAll -> ForAllOperator<Params>(resolve(True),
(0 until channel.stateCount).map { resolve(key.target.bindReference(key.name, it)) }.toMutableList(),
resolve(key.bound), channel
)
is Formula.FirstOrder.Exists -> ExistsOperator<Params>(
(0 until channel.stateCount).map { resolve(key.target.bindReference(key.name, it)) }.toMutableList(),
resolve(key.bound), channel
)
}
is Formula.Hybrid<*> -> when (key as Formula.Hybrid<*>) {
is Formula.Hybrid.Bind -> BindOperator<Params>(
(0 until channel.stateCount).map { resolve(key.target.bindReference(key.name, it)) }.toMutableList(),
channel
)
is Formula.Hybrid.At -> AtOperator(key.name.toInt(), resolve(key.target), channel)
}
}
}
}
formulas.mapValues {
val (name, formula) = it
formula to resolve(formula)
}
}
return dependencyTree.mapValues {
val (formula, operator) = it.value
operator.compute()
}
}
} | gpl-3.0 | 3b4b5eb239d6130ffb29deef3ee120c6 | 48.839572 | 152 | 0.523876 | 4.996783 | false | false | false | false |
AK-47-D/cms | src/main/kotlin/com/ak47/cms/cms/entity/Image.kt | 1 | 1086 | package com.ak47.cms.cms.entity
import java.util.*
import javax.persistence.*
@Entity
@Table(indexes = arrayOf(
Index(name = "idx_url", unique = true, columnList = "url"),
Index(name = "idx_category", unique = false, columnList = "category")))
class Image {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = -1
@Version
var version: Int = 0
@Column(length = 255)
var category: String = ""
var isFavorite: Int = 0
@Column(length = 255, unique = true, nullable = false)
var url: String = ""
var gmtCreated: Date = Date()
var gmtModified: Date = Date()
var isDeleted: Int = 0 //1 Yes 0 No
var deletedDate: Date = Date()
@Lob
var imageBlob: ByteArray = byteArrayOf()
/* 0-Baidu 1-Gank 2-HuaBan*/
var sourceType: Int = 0
override fun toString(): String {
return "Image(id=$id, version=$version, category='$category', isFavorite=$isFavorite, url='$url', gmtCreated=$gmtCreated, gmtModified=$gmtModified, isDeleted=$isDeleted, deletedDate=$deletedDate)"
}
}
| apache-2.0 | c2edfae8f11ebcc0583abb6060b2e909 | 28.351351 | 204 | 0.640884 | 3.744828 | false | false | false | false |
shymmq/librus-client-kotlin | app/src/main/kotlin/com/wabadaba/dziennik/vo/TimetableEntry.kt | 1 | 1290 | package com.wabadaba.dziennik.vo
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.wabadaba.dziennik.api.Parser
import io.requery.Embedded
import io.requery.Entity
import io.requery.Key
@Entity
@LibrusEntity("TimetableEntries")
@JsonDeserialize(`as` = TimetableEntryEntity::class)
interface TimetableEntry : Identifiable {
@get:Key
override val id: String
@get:Embedded
@get:JsonDeserialize(using = ClassroomDeserializer::class)
val classroom: Classroom?
}
@Embedded
interface Classroom {
val symbol: String?
val name: String?
val size: Int?
}
class ClassroomDeserializer : JsonDeserializer<Classroom>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Classroom? {
val parsingContext = p.parsingContext
val timetableEntry = parsingContext.currentValue as TimetableEntry
val classroom = timetableEntry.classroom
Parser.mapper.readerForUpdating(classroom)
.readValue<TimetableEntryEntity_ClassroomEntity>(p, TimetableEntryEntity_ClassroomEntity::class.java)
return classroom
}
} | gpl-3.0 | 2ad60847ac129ba57d6d585665a31e59 | 30.487805 | 117 | 0.769767 | 4.343434 | false | false | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/module/main/MusicOverviewFragment.kt | 1 | 17388 | package tech.summerly.quiet.module.main
import android.animation.Animator
import android.animation.ObjectAnimator
import android.graphics.Rect
import android.os.Bundle
import android.support.annotation.DrawableRes
import android.support.v4.app.Fragment
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.PopupMenu
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.fragment_music_overview.view.*
import kotlinx.android.synthetic.main.header_playlist_list.view.*
import kotlinx.android.synthetic.main.item_pinned_card.view.*
import kotlinx.android.synthetic.main.item_playlist.view.*
import me.drakeet.multitype.MultiTypeAdapter
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.defaultSharedPreferences
import tech.summerly.quiet.AppContext
import tech.summerly.quiet.R
import tech.summerly.quiet.bean.Playlist
import tech.summerly.quiet.data.local.LocalMusicApi
import tech.summerly.quiet.data.model.PreferenceModel
import tech.summerly.quiet.data.netease.NeteaseCloudMusicApi
import tech.summerly.quiet.extensions.*
import tech.summerly.quiet.extensions.lib.KItemViewBinder
import tech.summerly.quiet.module.common.bean.MusicType
import tech.summerly.quiet.module.local.LocalMusicActivity
import tech.summerly.quiet.module.local.PlayerStatisticsActivity
import tech.summerly.quiet.module.main.MusicOverviewFragment.Companion.newInstance
import tech.summerly.quiet.module.playlistdetail.PlaylistDetailActivity
import tech.summerly.quiet.ui.widget.PlaylistCreatorDialog
/**
* author : summerly
* e-mail : [email protected]
* time : 2017/7/31
* desc : 对应侧边栏选项 - 我的音乐,提供对所有音乐的概览
* 显示的内容有 -> 固定标签列表 : 本地音乐 , 最近播放...
* 自定义标签列表(即自定义的歌单)
* 使用 [newInstance] 创建实例
*/
class MusicOverviewFragment : Fragment() {
companion object {
private val SPAN_COUNT = 2
fun newInstance(): MusicOverviewFragment = MusicOverviewFragment()
}
val SPACE_DECORATION = AppContext.instance.dip(8)
private val pinnedTags = listOf(PinedTag(string(R.string.fragment_overview_pinned_local), R.drawable.ic_library_music_black_24dp),
PinedTag(string(R.string.fragment_overview_pinned_tends), R.drawable.ic_trending_up_black_24dp),
PinedTag(string(R.string.fragment_overview_pinned_fav), R.drawable.ic_favorite_black_24dp),
PinedTag(string(R.string.fragment_overview_pinned_latest), R.drawable.ic_latest_black_24dp))
//初始化 items,为其添加上固定的4个列表和播放列表头(默认列表头处于展开状态)
private val items = ArrayList<Any>().also {
it.addAll(pinnedTags)
it.add(PlaylistHeader(string(R.string.fragment_overview_local_playlist_header_title),
MusicType.LOCAL, true))
it.add(PlaylistHeader(string(R.string.fragment_overview_netease_playlist_header_title),
MusicType.NETEASE, true))
}
private val playlists = ArrayList<Playlist>()
private val compositeDisposable = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_music_overview, container, false)
val listPlaylist = rootView.listPlaylist
listPlaylist.adapter = MultiTypeAdapter().also {
it.register(PinedTag::class.java, PinedTagViewBinder())
it.register(Playlist::class.java, PlaylistViewBinder(this::onPlaylistItemClick))
it.register(PlaylistHeader::class.java, PlaylistHeaderViewBinder(this::onPlaylistsHeaderClick))
}
//两个PinnedTag合占一行,一个普通的播放列表独占一行
listPlaylist.layoutManager = GridLayoutManager(context, SPAN_COUNT).apply {
spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
val item = attempt { items[position] }.value
return if (item is PinedTag) 1 else SPAN_COUNT
}
}
}
listPlaylist.addItemDecoration(object : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildLayoutPosition(view)
//如果是PinnedTag
if ((listPlaylist.layoutManager as GridLayoutManager).spanSizeLookup.getSpanSize(position) == 1) {
//fixme
outRect.set(SPACE_DECORATION, SPACE_DECORATION,
SPACE_DECORATION, 0)
//如果是最底部的两个 PinnedTag,则多设置一个向下的分割
if (position == pinnedTags.size - 1 || position == pinnedTags.size - 2) {
outRect.set(SPACE_DECORATION, SPACE_DECORATION,
SPACE_DECORATION, SPACE_DECORATION)
}
} else {//如果是普通的播放列表(单独占一行)
}
}
})
listPlaylist.multiTypeAdapter.setData(items)
listPlaylist.itemAnimator = object : DefaultItemAnimator() {
var animatorExpandIndicator: Animator? = null
override fun onChangeStarting(holder: RecyclerView.ViewHolder, oldItem: Boolean) {
// start change animation
items[holder.adapterPosition].takeIf { it is PlaylistHeader }?.let {
it as PlaylistHeader
if (it.isExpand) {
holder.itemView.iconExpandIndicator.animateToRotation(90f)
} else {
holder.itemView.iconExpandIndicator.animateToRotation(0f)
}
}
}
override fun onChangeFinished(item: RecyclerView.ViewHolder?, oldItem: Boolean) {
super.onChangeFinished(item, oldItem)
animatorExpandIndicator?.end()
}
private fun ImageView.animateToRotation(r: Float) {
if (rotation == r) {
return
}
animatorExpandIndicator = ObjectAnimator.ofFloat(this, "rotation", rotation, r)
.setDuration(changeDuration)
animatorExpandIndicator?.start()
}
}
loadData()
return rootView
}
private fun loadData() {
//获取本地歌单
LocalMusicApi
.playlists()
.observeOn(AndroidSchedulers.mainThread())
.subscribeK {
onNext {
playlists.removeAll {
it.type == MusicType.LOCAL
}
log("本地歌单:$it")
playlists.addAll(it)
//before notify playlist load succeed ,we need to refresh header state
items.forEach {
if ((it is PlaylistHeader && it.type == MusicType.LOCAL)) {
it.isLoading = false
}
}
onPlaylistsLoadSucceed()
}
}
.let {
compositeDisposable.add(it)
}
val id = PreferenceModel.getNeteaseUserId()
if (id == 0L) {
items.removeAll {
it is PlaylistHeader && it.type == MusicType.NETEASE
}
} else {
//获取网易云音乐歌单
NeteaseCloudMusicApi.instance
.getUserPlayerList(id)
.observeOn(AndroidSchedulers.mainThread())
.subscribeK {
onNext {
playlists.removeAll {
it.type == MusicType.NETEASE
}
playlists.addAll(it)
//before notify playlist load succeed ,we need to refresh header state
items.forEach {
if ((it is PlaylistHeader && it.type == MusicType.NETEASE)) {
it.isLoading = false
}
}
onPlaylistsLoadSucceed()
}
}
.let {
compositeDisposable.add(it)
}
}
}
override fun onStart() {
super.onStart()
//get expand state
items.forEach {
if (it is PlaylistHeader) {
it.isExpand = defaultSharedPreferences.getBoolean(it.type.name, it.isExpand)
}
}
}
@Suppress("UNUSED_PARAMETER")
private fun onPlaylistItemClick(view: View, item: Playlist) {
when (item.type) {
MusicType.LOCAL -> PlaylistDetailActivity.startForLocalPlaylist(activity, item.id)
else -> TODO()
}
}
private fun onPlaylistsHeaderClick(header: PlaylistHeader, position: Int) {
val root = view ?: return
if (header.isExpand) {
header.isExpand = false
shrinkHeader(header)
} else {
header.isExpand = true
expandHeader(header)
}
root.listPlaylist.multiTypeAdapter.notifyItemChanged(position)
}
/**
* 当知道 [playlists] 已经加载完毕了.
*/
private fun onPlaylistsLoadSucceed() {
val root = view ?: return
//当有来自某个来源的歌单列表加载完毕时,需要移除RecyclerView正在显示的所有列表
//然后并通知其DataSet已经改变
//再展开当前处于展开状态下的列表
items.removeAll {
it is Playlist
}
root.listPlaylist.multiTypeAdapter.notifyDataSetChanged()
@Suppress("UNCHECKED_CAST") //此强制转换是安全的
val currentExpandHeader = (items.filter { it is PlaylistHeader } as ArrayList<PlaylistHeader>)
.filter {
it.isExpand
}
currentExpandHeader.forEach {
expandHeader(it)
}
}
private fun expandHeader(header: PlaylistHeader) {
val root = view ?: return
val index = root.listPlaylist.multiTypeAdapter.items.indexOf(header)
val itemsToAdd = playlists.filter {
it.type == header.type
}
items.addAll(index = index + 1, elements = itemsToAdd)
root.listPlaylist.multiTypeAdapter.notifyItemRangeInserted(index + 1, itemsToAdd.size)
}
private fun shrinkHeader(header: PlaylistHeader) {
val root = view ?: return
//计算要移除的item个数
val size = playlists.filter {
it.type == header.type
}.size
//计算要移除的item起始点
val index = root.listPlaylist.multiTypeAdapter.items.indexOf(header)
//移除item
items.removeAll {
it is Playlist && it.type == header.type
}
//更新view
root.listPlaylist.multiTypeAdapter.notifyItemRangeRemoved(index + 1, size)
}
override fun onStop() {
super.onStop()
//save expand state
defaultSharedPreferences.edit {
items.forEach {
if (it is PlaylistHeader) {
putBoolean(it.type.name, it.isExpand)
}
}
}
}
override fun onDestroy() {
super.onDestroy()
compositeDisposable.clear()
}
/**
* 固定在顶部的Tag
*/
private data class PinedTag(val title: String, @DrawableRes val icon: Int)
private class PinedTagViewBinder : KItemViewBinder<PinedTag>() {
override fun onBindViewHolder(holder: KItemViewBinder.KViewHolder, item: PinedTag) {
holder.itemView.imagePinnedIcon.setImageResource(item.icon)
holder.itemView.textPinnedTitle.text = item.title
when (item.title) {
string(R.string.fragment_overview_pinned_local) -> {
holder.itemView.tagPinned.setOnClickListener {
holder.itemView.context.startActivity<LocalMusicActivity>()
}
}
string(R.string.fragment_overview_pinned_latest) -> {
holder.itemView.tagPinned.setOnClickListener {
holder.itemView.context.startActivity<LatestPlayMusicActivity>()
}
}
string(R.string.fragment_overview_pinned_tends) -> {
holder.itemView.tagPinned.setOnClickListener {
it.context.startActivity<PlayerStatisticsActivity>()
}
}
string(R.string.fragment_overview_pinned_fav) -> {
holder.itemView.tagPinned.setOnClickListener {
doAsync {
val playlist = LocalMusicApi.PLAYLIST_LIKE
uiThread {
PlaylistDetailActivity.startForLocalPlaylist(holder.itemView.context, playlist.id)
}
}
}
}
}
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): KViewHolder {
val view = inflater.inflate(R.layout.item_pinned_card, parent, false)
return KViewHolder(view)
}
}
/**
* Playlist 的 header
*/
private class PlaylistHeader(val title: String,
val type: MusicType,
var isExpand: Boolean,
var isLoading: Boolean = true)
private inner class PlaylistHeaderViewBinder(private val onHeaderClick: (header: PlaylistHeader, position: Int) -> Unit)
: KItemViewBinder<PlaylistHeader>() {
override fun onBindViewHolder(holder: KViewHolder, item: PlaylistHeader) {
holder.itemView.setOnClickListener {
onHeaderClick(item, holder.adapterPosition)
}
holder.itemView.headerTitle.text = item.title
holder.itemView.headerMore.setOnClickListener {
createHeaderMenu(it).show()
}
if (item.isExpand) {
holder.itemView.iconExpandIndicator.rotation = 90f
} else {
holder.itemView.iconExpandIndicator.rotation = 0f
}
if (item.isLoading) {
holder.itemView.iconExpandIndicator.visibility = View.INVISIBLE
holder.itemView.progressBar.visibility = View.VISIBLE
} else {
holder.itemView.iconExpandIndicator.visibility = View.VISIBLE
holder.itemView.progressBar.visibility = View.INVISIBLE
}
}
private fun createHeaderMenu(anchor: View): PopupMenu {
val popupMenu = PopupMenu(activity, anchor)
popupMenu.inflate(R.menu.popup_playlist_header)
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.popup_playlist_create -> {
showPlaylistCreator()
}
}
true
}
return popupMenu
}
private fun showPlaylistCreator() {
PlaylistCreatorDialog(activity)
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): KViewHolder {
val view = inflater.inflate(R.layout.header_playlist_list, parent, false)
return KViewHolder(view)
}
}
class PlaylistViewBinder(private val onTagClickListener: (view: View, item: Playlist) -> Unit) : KItemViewBinder<Playlist>() {
override fun onBindViewHolder(holder: KItemViewBinder.KViewHolder, item: Playlist) {
with(holder.itemView) {
imageTagIcon.setImageURI(item.imageUrlString())
textTagTitle.text = item.name
setOnClickListener {
onTagClickListener(it, item)
}
setOnLongClickListener {
val menu = PopupMenuHelper(this.context).getPlaylistItemPopupMenu(it, item)
menu.show()
true
}
}
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): KViewHolder {
val view = inflater.inflate(R.layout.item_playlist, parent, false)
return KViewHolder(view)
}
}
}
| gpl-2.0 | 7cb5ac8f76af68314f994865a3b901b6 | 37.981481 | 134 | 0.581116 | 4.961697 | false | false | false | false |
alexmonthy/lttng-scope | lttng-scope/src/main/kotlin/org/lttng/scope/views/timeline/DebugOptions.kt | 2 | 4786 | /*
* Copyright (C) 2017-2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.views.timeline
import com.efficios.jabberwocky.common.ConfigOption
import javafx.scene.paint.*
import javafx.scene.text.Font
import javafx.scene.text.Text
/**
* Debug options for the timeline. Advanced users or unit
* tests might want to modify these.
*/
class DebugOptions {
companion object {
const val ELLIPSIS_STRING = "..."
}
// ------------------------------------------------------------------------
// General options
// ------------------------------------------------------------------------
/**
* Painting flag. Indicates if automatic redrawing of the view is enabled
*/
val isPaintingEnabled = ConfigOption(true)
/**
* Entry padding. Number of tree elements to print above *and* below the
* visible range
*/
val entryPadding = ConfigOption(5)
/**
* How much "padding" around the current visible window, on the left and
* right, should be pre-rendered. Expressed as a fraction of the current
* window (for example, 1.0 would render one "page" on each side).
*/
val renderRangePadding = ConfigOption(0.1)
/**
* Time between UI updates, in milliseconds
*/
val uiUpdateDelay = ConfigOption(250)
/**
* Whether the view should respond to vertical or horizontal scrolling
* actions.
*/
val isScrollingListenersEnabled = ConfigOption(true)
// ------------------------------------------------------------------------
// Loading overlay
// ------------------------------------------------------------------------
val isLoadingOverlayEnabled = ConfigOption(true)
val loadingOverlayColor: ConfigOption<Color> = ConfigOption(Color.GRAY)
val loadingOverlayFullOpacity = ConfigOption(0.3)
val loadingOverlayTransparentOpacity = ConfigOption(0.0)
val loadingOverlayFadeInDuration = ConfigOption(1000.0)
val loadingOverlayFadeOutDuration = ConfigOption(100.0)
// ------------------------------------------------------------------------
// Zoom animation
// ------------------------------------------------------------------------
/**
* The zoom animation duration, which is the amount of milliseconds it takes
* to complete the zoom animation (smaller number means a faster animation).
*/
val zoomAnimationDuration = ConfigOption(50)
/**
* Each zoom action (typically, one mouse-scroll == one zoom action) will
* increase or decrease the current visible time range by this factor.
*/
val zoomStep = ConfigOption(0.08)
/**
* Each zoom action will be centered on the center of the selection if it's
* currently visible.
*/
val zoomPivotOnSelection = ConfigOption(true)
/**
* Each zoom action will be centered on the current mouse position if the
* zoom action originates from a mouse event. If zoomPivotOnSelection is
* enabled, it has priority.
*/
val zoomPivotOnMousePosition = ConfigOption(true)
// ------------------------------------------------------------------------
// State rectangles
// ------------------------------------------------------------------------
val stateIntervalOpacity = ConfigOption(1.0)
val multiStatePaint: ConfigOption<Paint> = listOf(Stop(0.0, Color.BLACK), Stop(1.0, Color.WHITE))
.let { LinearGradient(0.0, 0.0, 0.0, 1.0, true, CycleMethod.NO_CYCLE, it) }
.let { ConfigOption(it) }
// ------------------------------------------------------------------------
// State labels
// ------------------------------------------------------------------------
val stateLabelFont = ConfigOption(Text().font).apply {
addListener { _ -> ellipsisWidth = recomputeEllipsisWidth() }
}
@Transient
var ellipsisWidth: Double = recomputeEllipsisWidth()
private set
@Synchronized
private fun recomputeEllipsisWidth(): Double {
with(Text(ELLIPSIS_STRING)) {
font = stateLabelFont.get()
applyCss()
return layoutBounds.width
}
}
// ------------------------------------------------------------------------
// Tooltips
// ------------------------------------------------------------------------
val toolTipFont: ConfigOption<Font> = ConfigOption(Font.font(14.0))
val toolTipFontFill: ConfigOption<Color> = ConfigOption(Color.WHITE)
}
| epl-1.0 | b0238a5858a3c5a86815044ce42321e4 | 32.704225 | 101 | 0.545341 | 5.146237 | false | true | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/gpaCalculator/AddModuleActivity.kt | 1 | 9681 | package com.itachi1706.cheesecakeutilities.modules.gpaCalculator
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Toast
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.database.DataSnapshot
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaInstitution
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaModule
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaScoring
import com.itachi1706.cheesecakeutilities.R
import com.itachi1706.cheesecakeutilities.util.FirebaseValueEventListener
import com.itachi1706.helperlib.helpers.LogHelper
import com.itachi1706.cheesecakeutilities.extlibs.com.thebluealliance.spectrum.SpectrumPalette
import kotlinx.android.synthetic.main.activity_gpa_calculator_add_module.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.LinkedHashMap
class AddModuleActivity : AddActivityBase() {
private var selectedInstitution: GpaInstitution? = null
private var scoringObject: GpaScoring? = null
private lateinit var selectedSemesterKey: String
private lateinit var instituteString: String
private var colorSelected: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_gpa_calculator_add_module)
instituteString = intent?.extras!!.getString("institute", "-_-_-")
selectedSemesterKey = intent?.extras!!.getString("key", "-")
if (instituteString == "-_-_-" || selectedSemesterKey == "-") {
Toast.makeText(this, "Invalid Institution or Semester", Toast.LENGTH_SHORT).show()
finish()
return
}
if (editKey == null) randomizeColor() // Randomly pick color if in add mode
// Get the calculation modes
getInstitution(instituteString)
gpacalc_add.setOnClickListener { v ->
when (val result = validate()) {
is String -> Snackbar.make(v, result, Snackbar.LENGTH_LONG).show()
is GpaModule -> {
addToDb(result)
Toast.makeText(v.context, "Module ${if (module == null) "Added" else "Updated"}", Toast.LENGTH_LONG).show()
finish()
}
else -> {
LogHelper.e(TAG, "Invalid Validation")
Snackbar.make(v, "An error occurred adding module", Snackbar.LENGTH_LONG).show()
}
}
}
cbPassFail.setOnCheckedChangeListener { _, _ -> updateGradeTierSpinner() }
module_color_selector.setOnColorSelectedListener(object: SpectrumPalette.OnColorSelectedListener {
override fun onColorSelected(color: Int) {
colorSelected = color
LogHelper.d(TAG, "Color Selected: #${Integer.toHexString(color).toUpperCase(Locale.US)}")
}
})
}
private fun randomizeColor() {
val typeArrayTmp = resources.obtainTypedArray(R.array.module_colors)
val colorArray: ArrayList<Int> = ArrayList()
for (i in 0 until typeArrayTmp.length()) {
colorArray.add(typeArrayTmp.getColor(i, 0))
}
colorSelected = colorArray.shuffled().take(1)[0]
module_color_selector.setSelectedColor(colorSelected)
typeArrayTmp.recycle()
}
private var module: GpaModule? = null
override fun editModeEnabled(editKey: String) {
GpaCalcFirebaseUtils.getGpaDatabaseUser(userId).child(instituteString).child(GpaCalcFirebaseUtils.FB_REC_SEMESTER).child(selectedSemesterKey)
.child(GpaCalcFirebaseUtils.FB_REC_MODULE).child(editKey).addListenerForSingleValueEvent(object: FirebaseValueEventListener(TAG, "editMode"){
override fun onDataChange(dataSnapshot: DataSnapshot) {
// Make user update scoring mode again
module = dataSnapshot.getValue(GpaModule::class.java)
Snackbar.make(findViewById(android.R.id.content), "Please update grade agian", Snackbar.LENGTH_LONG).show()
etName.setText(module?.name)
etCourseCode.setText(module?.courseCode)
etCredits.setText(module?.credits.toString())
cbPassFail.isChecked = module?.passFail ?: false
gpacalc_add.text = "Edit Module"
if (module?.color != 0) module_color_selector.setSelectedColor(module?.color!!)
else randomizeColor()
supportActionBar?.title = "Edit a Module"
supportActionBar?.subtitle = "${etName.text.toString()} [${etCourseCode.text.toString()}]"
}
})
}
override fun validate(): Any {
val name = etName.text.toString()
val courseCode = etCourseCode.text.toString()
val creditsStr = etCredits.text.toString()
val credits = if (creditsStr.isEmpty()) -1 else creditsStr.toInt()
val passFail = cbPassFail.isChecked
val grade = spinnerGpaGrade.selectedItemPosition - 1
til_etName.error = "Required field"
til_etCourseCode.error = "Required field"
til_etName.isErrorEnabled = name.isEmpty()
til_etCourseCode.isErrorEnabled = courseCode.isEmpty()
// Make sure course code is unique
if (selectedInstitution == null) return "Invalid institution error"
if (selectedInstitution!!.semester[selectedSemesterKey]?.modules?.contains(courseCode)!! && module == null) {
til_etCourseCode.error = "Module Already Exists"
til_etCourseCode.isErrorEnabled = true
}
if (til_etName.isErrorEnabled || til_etCourseCode.isErrorEnabled) return "Please resolve the errors before continuing"
if (colorSelected == 0) return "Please select module color"
return GpaModule(name, courseCode, grade, credits, passFail, colorSelected)
}
private fun addToDb(newModule: GpaModule) {
if (selectedInstitution == null) return // Don't try to add if you cannot add
val db = GpaCalcFirebaseUtils.getGpaDatabaseUser(userId).child(selectedInstitution!!.shortName).child(GpaCalcFirebaseUtils.FB_REC_SEMESTER)
.child(selectedSemesterKey).child(GpaCalcFirebaseUtils.FB_REC_MODULE)
if (module == null) db.child(newModule.courseCode).setValue(newModule)
else {
val edited = module!!.copy(name = newModule.name, courseCode = newModule.courseCode, gradeTier = newModule.gradeTier, credits = newModule.credits, passFail = newModule.passFail,
color = colorSelected)
if (edited.courseCode != module!!.courseCode) {
// Change of shortname as well, delete old key
db.child(module!!.courseCode).removeValue()
}
db.child(edited.courseCode).setValue(edited)
}
}
private fun updateScoringFeatures() {
// Check if count or gpa and hide accordingly. Also check if there is a pass/fail tier
if (scoringObject?.passtier == null) cbPassFail.isChecked = false
cbPassFail.isEnabled = scoringObject?.passtier != null
til_etCredits.visibility = if (scoringObject?.type == "count") View.GONE else View.VISIBLE
updateGradeTierSpinner()
}
private val gradeTierList: LinkedHashMap<String, GpaScoring.GpaTier?> = LinkedHashMap()
private fun updateGradeTierSpinner() {
gradeTierList.clear()
if (scoringObject == null) return // Haven't init scoring object yet
gradeTierList["- (Not Graded)"] = null
val tier = if (cbPassFail.isChecked && scoringObject?.passtier != null) scoringObject?.passtier!! else scoringObject?.gradetier!!
tier.forEach {
gradeTierList.put("${it.name} (${it.desc})".replace(" (No description)", ""), it)
}
//gradeTierList.putAll(tier.map { i -> "${i.name} (${i.desc})".replace(" (No description)", "") }, tier.toList())
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, gradeTierList.keys.toList())
spinnerGpaGrade.adapter = adapter
}
private fun getScoringObject() {
LogHelper.i(TAG, "Retrieving Scoring Object for this institution")
val db = GpaCalcFirebaseUtils.getGpaDatabase().child(GpaCalcFirebaseUtils.FB_REC_SCORING).child(selectedInstitution!!.type)
db.keepSynced(true)
db.addListenerForSingleValueEvent(object: FirebaseValueEventListener(TAG, "getScoringObject") {
override fun onDataChange(dataSnapshot: DataSnapshot) {
scoringObject = dataSnapshot.getValue(GpaScoring::class.java)
updateScoringFeatures()
}
})
}
private fun getInstitution(institute: String) {
val db = GpaCalcFirebaseUtils.getGpaDatabaseUser(userId).child(institute)
db.keepSynced(true)
db.addListenerForSingleValueEvent(object: FirebaseValueEventListener(TAG, "getInstitution") {
override fun onDataChange(dataSnapshot: DataSnapshot) {
selectedInstitution = dataSnapshot.getValue(GpaInstitution::class.java)
supportActionBar?.subtitle = if (selectedInstitution == null) "An error occurred" else "${selectedInstitution?.name} | ${selectedInstitution?.semester!![selectedSemesterKey]?.name}"
getScoringObject()
}
})
}
companion object {
private const val TAG = "GpaCalcAddModule"
}
}
| mit | d96fb1e777a1399bad8295f1af8b9746 | 47.893939 | 197 | 0.664807 | 4.47987 | false | false | false | false |
UprootLabs/unplug | src/co/uproot/unplug/api.kt | 1 | 13151 | package co.uproot.unplug
import com.eclipsesource.json.JsonArray
import com.eclipsesource.json.JsonObject
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import java.io.IOException
import java.net.URLEncoder
import java.util.ArrayList
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
data class AccessToken(val token: String)
data class Message(
val id: String?,
val ts: Long,
val roomId: String?,
val type: String,
val userId: String,
val content: JsonObject)
data class State(
val type: String,
val ts: Long,
val userId: String,
val stateKey: String,
val content: JsonObject) {
}
data class Room(val id: String, val aliases: List<String>, val messages: MutableList<Message>, val states: List<State>) {
fun isChatMessage(message: Message): Boolean {
return when (message.type) {
"m.room.create" -> true
"m.room.member" -> true
"m.room.message" -> true
else -> false
}
}
fun chatMessages(): List<Message> {
return messages.asSequence().filter({ isChatMessage(it) }).toList()
}
fun getAliasOrId(): String {
if (aliases.size > 0) {
return aliases.get(0)
} else {
return id
}
}
}
fun JsonObject.getObject(name: String): JsonObject {
return this.get(name).asObject()
}
fun JsonObject.getArray(name: String): JsonArray {
return this.get(name).asArray()
}
class SyncResult(val rooms: List<Room>, val presence: List<Message>)
class EventResult(val messages: List<Message>, val end: String)
class CreateRoomResult(val roomAlias: String, val roomId: String)
class JoinRoomResult(val roomId: String, val servers: String)
class InviteMemResult(val result: String?)
class LeaveRoomResult(val result: String?)
class BanRoomResult(val result: String?)
data class LoginResult(val userId: String, val accessToken: AccessToken, val api: API)
interface RoomIdentifier
class RoomId(val id: String) : RoomIdentifier
class RoomName(val name: String) : RoomIdentifier
// TODO: Change API to be fully type-safe, and not return JSON objects
class API(val baseURL: String) {
val apiURL = baseURL + "_matrix/client/r0/"
val mediaURL = baseURL + "_matrix/media/r0/"
private final val client = OkHttpClient.Builder()
.followRedirects(false)
.followSslRedirects(false)
.connectTimeout(40, TimeUnit.SECONDS)
.readTimeout(40, TimeUnit.SECONDS)
.writeTimeout(40, TimeUnit.SECONDS)
.build()
private final val net = Net(client)
fun login(username: String, password: String): LoginResult? {
try {
val postBody = """
{"type":"m.login.password", "user":"$username", "password":"$password"}
"""
val responseStr = net.doPost(apiURL + "login", postBody)
val jsonObj = JsonObject.readFrom(responseStr)
val tokenStr = jsonObj.getString("access_token", null)
val userId = jsonObj.getString("user_id", null)
if (tokenStr != null && userId != null) {
return LoginResult(userId, AccessToken(tokenStr), this)
} else {
return null
}
} catch(e: IOException) {
e.printStackTrace()
return null;
}
}
fun createRoom(accessToken: AccessToken, roomname: String, visibility: String): CreateRoomResult {
val post = """
{"room_alias_name":"$roomname", "visibility":"$visibility"}
"""
val responseStr = net.doPost(apiURL + "createRoom?access_token=${accessToken.token}", post)
val jsonObj = JsonObject.readFrom(responseStr)
val roomAlias = jsonObj.getString("room_alias", null)
val roomId = jsonObj.getString("room_id", null)
return CreateRoomResult(roomAlias, roomId)
}
fun joiningRoon(accessToken: AccessToken, room: RoomIdentifier): JoinRoomResult {
val roomId = getRoomId(accessToken, room)
val nameEncode = URLEncoder.encode(roomId, "UTF-8")
val responseStr = net.doPost(apiURL + "join/$nameEncode?access_token=${accessToken.token}", "")
val jsonObj = JsonObject.readFrom(responseStr)
val roomIdResult = jsonObj.getString("room_id", null)
val servers = jsonObj.getString("servers", null)
return JoinRoomResult(roomIdResult, servers)
}
fun invitingMember(accessToken: AccessToken, room: RoomIdentifier, memId: String): InviteMemResult {
val roomId = getRoomId(accessToken, room)
val roomIdEncode = URLEncoder.encode(roomId, "UTF-8")
val rmIdEncode = roomIdEncode.substring(3)
val post = """
{"user_id":"$memId"}"""
val responseStr = net.doPost(apiURL + "rooms/state!$rmIdEncode/invite?access_token=${accessToken.token}", post)
return InviteMemResult(responseStr)
}
fun banningMember(accessToken: AccessToken, room: RoomIdentifier, memId: String, appState: AppState): BanRoomResult {
val roomId = getRoomId(accessToken, room)
val ban = "ban"
val roomIdEncode = URLEncoder.encode(roomId, "UTF-8")
val rmIdEncode = roomIdEncode.substring(3)
val memIdEncode = URLEncoder.encode(memId, "UTF-8")
if (roomId != null) {
val mediaURL1 = baseURL + "/_matrix/media/v1/"
val badUrl = mediaURL1 + "thumbnail/"
val url = appState.getRoomUsers(roomId)
val a = url.firstOrNull { it.id == memId }
if (a != null) {
val displayName = a.displayName.getValue()
val url1 = a.avatarURL.getValue()
// TODO: val url2 = url1.toString().replaceAll(badUrl, "mcx://")
val url2 = url1.toString()
val finalUrl = url2.substringBefore("?")
val header = """
{"avatar_url":"$finalUrl","displayName":"$displayName","membership":"$ban"}"""
val responseStr = net.doPut(apiURL + "rooms/!$rmIdEncode/state/m.room.member/$memIdEncode?access_token=${accessToken.token}", header)
return BanRoomResult(responseStr)
}
}
return BanRoomResult(null)
}
fun leavingRoom(accessToken: AccessToken, room: RoomIdentifier): LeaveRoomResult {
val roomId = getRoomId(accessToken, room)
val roomIdEncode = URLEncoder.encode(roomId, "UTF-8")
val rmIdEncode = roomIdEncode.substring(3)
val responseStr = net.doPost(apiURL + "rooms/!$rmIdEncode/leave?access_token=${accessToken.token}", "{}")
// TODO: Parse response
return LeaveRoomResult(null)
}
private fun getRoomId(accessToken: AccessToken, room: RoomIdentifier): String? {
return when (room) {
is RoomId -> room.id
is RoomName -> getRoomId(accessToken, room.name)
else -> throw UnknownError("Unknown room identifier") // TODO: Use sealed class
}
}
fun getRoomId(accessToken: AccessToken, roomAlias: String): String? {
val roomAliasEscaped = URLEncoder.encode(roomAlias, "UTF-8")
val responseStr = net.doGet(apiURL + "directory/room/$roomAliasEscaped?access_token=${accessToken.token}")
if (responseStr == null) {
return null
} else {
val jsonObj = JsonObject.readFrom(responseStr)
return jsonObj.getString("room_id", null)
}
}
private var txnIdUnique = AtomicLong()
fun sendMessage(accessToken: AccessToken, roomId: String, message: String): String {
val postBody = """
{"msgtype":"m.text", "body":"$message"}
"""
val txnId = txnIdUnique.addAndGet(1L)
val responseStr = net.doPut(apiURL + "rooms/$roomId/send/m.room.message/$txnId?access_token=${accessToken.token}", postBody)
val jsonObj = JsonObject.readFrom(responseStr)
val eventId = jsonObj.getString("event_id", null)
return eventId
}
fun roomInitialSync(accessToken: AccessToken, roomId: String): SyncResult? {
val roomIdEncode = URLEncoder.encode(roomId, "UTF-8")
val rmIdEncode = roomIdEncode.substring(3)
val responseStr = net.doGet(apiURL + "rooms/!$rmIdEncode/initialSync?access_token=${accessToken.token}")
if (responseStr == null) {
return null
}
val room = JsonObject.readFrom(responseStr)
val roomObj = room.asObject()
val messages = roomObj.getObject("messages")
val chunks = messages.getArray("chunk").map { it.asObject() }
val messageList = parseChunks(chunks)
val states = roomObj.getArray("state")
val aliasStates = states.filter { it.asObject().getString("type", null) == "m.room.aliases" }
val aliases = aliasStates.flatMap {
it.asObject().getObject("content").getArray("aliases").map { it.asString() }
}
val stateList = states.map { state ->
val so = state.asObject()
State(so.getString("type", null), so.getLong("origin_server_ts", 0L), so.getString("user_id", null), so.getString("state_key", null), so.getObject("content"))
}
val arrayList = ArrayList<Room>()
val a = Room(roomObj.getString("room_id", null), aliases, messageList.toMutableList(), stateList)
arrayList.add(a)
val presence = parseChunks(room.getArray("presence").map { it.asObject() })
return SyncResult(arrayList, presence)
}
fun initialSync(accessToken: AccessToken): SyncResult? {
val responseStr = net.doGet(apiURL + "initialSync?access_token=${accessToken.token}")
if (responseStr == null) {
return null
}
val jsonObj = JsonObject.readFrom(responseStr)
val rooms = jsonObj.getArray("rooms")
val roomList = rooms.map { room ->
val roomObj = room.asObject()
val messages = roomObj.getObject("messages")
val chunks = messages.getArray("chunk").map { it.asObject() }
val messageList = parseChunks(chunks)
val states = roomObj.getArray("state")
val aliasStates = states.filter { it.asObject().getString("type", null) == "m.room.aliases" }
val aliases = aliasStates.flatMap {
it.asObject().getObject("content").getArray("aliases").map { it.asString() }
}
val stateList = states.map { state ->
val so = state.asObject()
State(so.getString("type", null), so.getLong("origin_server_ts", 0L), so.getString("user_id", null), so.getString("state_key", null), so.getObject("content"))
}
Room(roomObj.getString("room_id", null), aliases, messageList.toMutableList(), stateList)
}
val presence = parseChunks(jsonObj.getArray("presence").map { it.asObject() })
return SyncResult(roomList, presence)
}
fun getEvents(accessToken: AccessToken, from: String?): EventResult? {
val eventURL = apiURL + "events?access_token=${accessToken.token}" + (from?.let { "&from=" + it } ?: "")
val responseStr = net.doGet(eventURL)
val jsonObj = JsonObject.readFrom(responseStr)
val chunks = jsonObj.getArray("chunk")
return EventResult(parseChunks(chunks.map { it.asObject() }), jsonObj.getString("end", null))
}
private fun parseChunks(chunk: List<JsonObject>): List<Message> {
val messageList = chunk.map { messageObj ->
val userId = messageObj.getString("user_id", "")
val type = messageObj.getString("type", "")
val eventId: String? = messageObj.getString("event_id", null)
val roomId: String? = messageObj.getString("room_id", null)
Message(eventId, messageObj.getLong("origin_server_ts", 0L), roomId, type, userId, messageObj.getObject("content"))
}
return messageList
}
private val mxcRegex = "^mxc://(.*)/([^#]*)(#auto)?$".toRegex()
fun getAvatarThumbnailURL(mxcURL: String): String {
/*
val matchResult = mxcRegex.matchEntire(mxcURL)
matchResult.let{ r ->
val serverName = r.groupValues.get(1)
val mediaId = r.groupValues.get(2)
mediaURL + "thumbnail/$serverName/$mediaId?width=24&height=24"
}
val matcher = mxcRegex.matcher(mxcURL)
if (matcher.matches()) {
val serverName = matcher.group(1)
val mediaId = matcher.group(2)
return mediaURL + "thumbnail/$serverName/$mediaId?width=24&height=24"
} else {
return ""
}
*/
return ""
}
}
private class Net(val client: OkHttpClient) {
private final val jsonMediaType = MediaType.parse("application/json;; charset=utf-8")
// TODO: a non-blank UA String
private final val uaString = ""
fun doGet(url: String): String? {
val request = Request.Builder()
.url(url)
.addHeader("User-Agent", uaString)
.build()
val response = client.newCall(request).execute()
if (!response.isSuccessful()) {
return null
} else {
return response.body().string()
}
}
fun doPost(url: String, json: String): String {
return doVerb("post", url, json)
}
fun doPut(url: String, json: String): String {
return doVerb("put", url, json)
}
fun doVerb(verb: String, url: String, json: String): String {
val requestBody = RequestBody.create(jsonMediaType, json)
val requestBuilder = Request.Builder()
.url(url)
.addHeader("User-Agent", uaString)
when (verb) {
"put" -> requestBuilder.put(requestBody)
"post" -> requestBuilder.post(requestBody)
else -> throw NotImplementedError("http verb is not yet implemented: $verb")
}
val request = requestBuilder.build()
val response = client.newCall(request).execute()
if (!response.isSuccessful()) {
throw IOException("Unexpected code " + response)
} else {
return response.body().string()
}
}
}
| gpl-3.0 | 2246b2a5078a7280c8c3840a0e4478f1 | 35.129121 | 166 | 0.673865 | 3.893132 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/colorinfo/ColorInfoExecutor.kt | 1 | 8481 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.colorinfo
import dev.kord.common.kColor
import net.perfectdreams.discordinteraktions.common.builder.message.embed
import net.perfectdreams.discordinteraktions.common.utils.field
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.ColorInfoCommand
import net.perfectdreams.loritta.cinnamon.discord.utils.images.ImageFormatType
import net.perfectdreams.loritta.cinnamon.discord.utils.images.ImageUtils
import net.perfectdreams.loritta.cinnamon.discord.utils.images.ImageUtils.toByteArray
import java.awt.Color
import java.awt.Font
import java.awt.Graphics
import java.awt.image.BufferedImage
abstract class ColorInfoExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
companion object {
private const val FACTOR = 0.7
}
suspend fun executeWithColor(context: ApplicationCommandContext, color: Color) {
context.deferChannelMessage()
val hsbVals = Color.RGBtoHSB(color.red, color.green, color.blue, null)
val hue = hsbVals[0] * 360
val saturation = hsbVals[1] * 100
val brightness = hsbVals[2] * 100
val shadesColors = getShades(color)
val tintsColors = getTints(color)
val complementaryColor = Color(Color.HSBtoRGB(((hue + 180) % 360 / 360), saturation / 100, brightness / 100))
val triadColor1 = Color(Color.HSBtoRGB(((hue + 120) % 360 / 360), saturation / 100, brightness / 100))
val triadColor2 = Color(Color.HSBtoRGB(((hue - 120) % 360 / 360), saturation / 100, brightness / 100))
val analogousColor1 = Color(Color.HSBtoRGB(((hue + 30) % 360 / 360), saturation / 100, brightness / 100))
val analogousColor2 = Color(Color.HSBtoRGB(((hue - 30) % 360 / 360), saturation / 100, brightness / 100))
val image = generate(
Color(color.red, color.green, color.blue),
shadesColors,
tintsColors,
Color(triadColor1.red, triadColor1.green, triadColor1.blue),
Color(triadColor2.red, triadColor2.green, triadColor2.blue),
Color(analogousColor1.red, analogousColor1.green, analogousColor1.blue),
Color(analogousColor2.red, analogousColor2.green, analogousColor2.blue),
Color(complementaryColor.red, complementaryColor.green, complementaryColor.blue),
context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.Shades),
context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.Tints),
context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.Triadic),
context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.Analogous),
context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.Complementary)
)
context.sendMessage {
addFile("color.png", image.toByteArray(ImageFormatType.PNG).inputStream())
embed {
val colorName = ColorUtils.getColorNameFromColor(color)
title = "\uD83C\uDFA8 $colorName"
this.color = color.kColor
field("RGB", "`${color.red}, ${color.green}, ${color.blue}`", true)
val hex = String.format("#%02x%02x%02x", color.red, color.green, color.blue)
field("Hexadecimal", "`$hex`", true)
field("Decimal", "`${color.rgb}`", true)
field("HSB", "`${hue.toInt()}°, ${saturation.toInt()}%, ${brightness.toInt()}%`", true)
field(context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.Shades), joinColorsToHex(shadesColors), false)
field(context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.Tints), joinColorsToHex(tintsColors), false)
field(context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.Triadic), joinColorsToHex(listOf(triadColor1, triadColor2)), false)
field(context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.Analogous), joinColorsToHex(listOf(analogousColor1, analogousColor2)), false)
field(context.i18nContext.get(ColorInfoCommand.I18N_PREFIX.Complementary), joinColorsToHex(listOf(complementaryColor)), false)
this.image = "attachment://color.png"
}
}
}
private fun generate(
color: Color,
shadesColors: List<Color>,
tintsColors: List<Color>,
triadColor1: Color,
triadColor2: Color,
analogousColor1: Color,
analogousColor2: Color,
complementaryColor: Color,
shades: String,
tints: String,
triadic: String,
analogous: String,
complementary: String
): BufferedImage {
val colorInfo = BufferedImage(333, 250, BufferedImage.TYPE_INT_ARGB)
val graphics = colorInfo.graphics
val font = loritta.graphicsFonts.m5x7.deriveFont(16f)
graphics.font = font
// Color Sections
drawColorSection(0, 0, graphics, shades, shadesColors)
drawColorSection(0, 61, graphics, tints, tintsColors)
drawColorSection(0, 122, graphics, triadic, listOf(color, triadColor1, triadColor2))
drawColorSection(148, 122, graphics, complementary, listOf(color, complementaryColor))
drawColorSection(0, 183, graphics, analogous, listOf(analogousColor1, analogousColor2))
// Color Preview (smol circle at the right bottom side of the image)
val colorPreview = BufferedImage(192, 192, BufferedImage.TYPE_INT_ARGB)
val previewGraphics = colorPreview.graphics
previewGraphics.color = color
previewGraphics.fillRect(0, 0, 192, 192)
graphics.drawImage(ImageUtils.makeRoundedCorners(colorPreview, 99999), 237, 167, null)
return colorInfo
}
private fun getShades(color: Color): List<Color> {
val colors = mutableListOf<Color>()
var shade = Color(color.rgb)
var previousShade: Int? = null
while (previousShade != shade.rgb) {
val newR = shade.red * (1 - FACTOR)
val newG = shade.green * (1 - FACTOR)
val newB = shade.blue * (1 - FACTOR)
previousShade = shade.rgb
shade = Color(newR.toInt(), newG.toInt(), newB.toInt())
colors.add(shade)
}
return colors
}
private fun getTints(color: Color): List<Color> {
val colors = mutableListOf<Color>()
var tint = Color(color.rgb)
var previousTint: Int? = null
while (previousTint != tint.rgb) {
val newR = tint.red + (255 - tint.red) * FACTOR
val newG = tint.green + (255 - tint.green) * FACTOR
val newB = tint.blue + (255 - tint.blue) * FACTOR
previousTint = tint.rgb
tint = Color(newR.toInt(), newG.toInt(), newB.toInt())
colors.add(tint)
}
return colors
}
private fun drawColorSection(
x: Int,
y: Int,
graphics: Graphics,
title: String,
colors: List<Color>
) {
var currentX = x
val currentY = y
fun Graphics.drawWithOutline(text: String, x: Int, y: Int) {
this.color = Color.BLACK
this.drawString(text, x - 1, y)
this.drawString(text, x + 1, y)
this.drawString(text, x, y - 1)
this.drawString(text, x, y + 1)
this.color = Color.WHITE
this.drawString(text, x, y)
}
fun Graphics.drawColor(color: Color, x: Int, y: Int) {
this.color = color
this.fillRect(x, y, 48, 48)
val hex = String.format("#%02x%02x%02x", color.red, color.green, color.blue)
var _x = x + 48
for (char in hex) {
_x -= this.fontMetrics.charWidth(char)
}
this.drawWithOutline(hex, _x - 1, y + 48 - 2)
}
graphics.drawWithOutline(title, currentX + 1, currentY + 10)
for (color in colors) {
graphics.drawColor(color, currentX, currentY + 13)
currentX += 48
}
}
fun joinColorsToHex(colors: List<Color>) = colors.joinToString(", ") { "`${String.format("#%02x%02x%02x", it.red, it.green, it.blue)}`" }
} | agpl-3.0 | aae940ac5c927c0096765eb393248c50 | 39.578947 | 152 | 0.639387 | 3.95338 | false | false | false | false |
YounesRahimi/java-utils | src/test/java/ir/iais/utilities/javautils/KTest.kt | 2 | 3222 | @file:JvmName("KTestKt")
package ir.iais.utilities.javautils
import com.ibm.icu.lang.UCharacter
import com.winterbe.expekt.should
import ir.iais.utilities.javautils.utils.*
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
import java.io.File
import java.nio.file.Paths
import java.util.*
fun main(args: Array<String>) {
// "newman run -h".shell()!!.println()
println("user.dir=${System.getProperty("user.dir")}")
println("user.home=${System.getProperty("user.home")}")
println("JAVA_HOME=${System.getProperty("JAVA_HOME")}")
workingDir.toString().println()
println("Current Working Directory 3=${File("").absolutePath}")
println("Current Working Directory 4=${Paths.get(".").toAbsolutePath().normalize()}")
println("newman.js File Path From IQ Class 1=${IQ::class.java.getResource("newman.js").file}")
println("project-java-utils.properties File Path From Everywhere=${IQ::class.file("/project-java-utils.properties")}")
println("project-java-utils.properties File Content From Everywhere:\n" +
IQ::class.java.getResource("/project-java-utils.properties")
.readText()
)
}
internal class KKtTest {
@Test
fun `test readFile`() {
val readText = UCharacter::class.readFile("package.html").readText()
readText.should.contain("<title>C:ICU4J .lang Package Overview</title>")
println("package.html Content Using UCharacter.classLoader::getResourceAsStream:\n" + readText)
}
@Test
fun `test runCommand`() {
val commandOutput = IQ::class.resourcesDir.shell("ls -lahS")
commandOutput.should.not.`null`
val (stdout, stderr, exitCode) = commandOutput!!
exitCode.should.equal(0)
stderr.should.empty
stdout.should.contain("project-java-utils.properties")
commandOutput.println()
}
@Test
fun `test file`() {
val newmanFile = IQ::class.file("newman.js")
println("newman.js File Path From IQ Class 2=${newmanFile.path}")
newmanFile.path.should.endWith("java-utils/target/classes/ir/iais/utilities/javautils/newman.js")
newmanFile.readText().should.contain("""console.log("Hello Newman. I'm Kotlin!")""")
println("newman.js File Content From IQ Class:\n" + newmanFile.readText())
val ucharFile = UCharacter::class.file("package.html")
ucharFile.path.should.endWith("com/ibm/icu/icu4j/59.1/icu4j-59.1.jar!/com/ibm/icu/lang/package.html")
println("package.html File Path From UCharacter:" + ucharFile.path)
}
@Test
fun `test dir`() {
println("Class IQ Directory=" + IQ::class.dir)
IQ::class.dir.path.should.endWith("java-utils/target/classes/ir/iais/utilities/javautils")
}
@Test
fun `test workingDir`() {
assertNotNull(workingDir)
workingDir.should.not.be.`null`
}
@Test
fun `test resourceDir`() {
IQ::class.resourcesDir.path.should.endWith("java-utils/target/classes")
println("Resources Root Directory=" + IQ::class.resourcesDir)
}
@Test
fun format() {
Date().formatAsJalali().println()
}
}
| gpl-3.0 | 24747e16a58625e569ad7f6037208cc1 | 36.034483 | 122 | 0.657976 | 3.826603 | false | true | false | false |
luoyuan800/NeverEnd | dataModel/src/cn/luo/yuan/maze/model/KeyResult.kt | 1 | 670 | package cn.luo.yuan.maze.model
import cn.luo.yuan.maze.utils.Field
import cn.luo.yuan.maze.utils.StringUtils
import java.io.Serializable
/**
* Copyright @Luo
* Created by Gavin Luo on 8/16/2017.
*/
class KeyResult : Serializable {
companion object {
private const val serialVersionUID: Long = Field.SERVER_VERSION
}
var gift = 0
var debris =0
var mate= 0L
var verify = false
override fun toString(): String {
return if(verify) "获得了 锻造 ${StringUtils.formatNumber(mate)} ${if(gift > 0) ", $gift 个礼包" else ""} ${if(debris > 0) ", $debris 个碎片" else ""}" else "该兑换码已经使用过了!";
}
} | bsd-3-clause | 7122c59908cc64ba88c376c5bba13e8a | 27.5 | 168 | 0.65655 | 3.09901 | false | false | false | false |
toastkidjp/Jitte | app/src/main/java/jp/toastkid/yobidashi/main/MainActivity.kt | 1 | 26378 | package jp.toastkid.yobidashi.main
import android.Manifest
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import jp.toastkid.lib.AppBarViewModel
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentScrollable
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.FileExtractorFromUri
import jp.toastkid.lib.TabListViewModel
import jp.toastkid.lib.fragment.CommonFragmentAction
import jp.toastkid.lib.input.Inputs
import jp.toastkid.lib.intent.OpenDocumentIntentFactory
import jp.toastkid.lib.preference.ColorPair
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.lib.tab.TabUiFragment
import jp.toastkid.lib.view.ToolbarColorApplier
import jp.toastkid.lib.view.WindowOptionColorApplier
import jp.toastkid.lib.view.filter.color.ForegroundColorFilterUseCase
import jp.toastkid.media.music.popup.permission.ReadAudioPermissionRequestContract
import jp.toastkid.search.SearchCategory
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.browser.BrowserFragment
import jp.toastkid.yobidashi.browser.BrowserFragmentViewModel
import jp.toastkid.yobidashi.browser.LoadingViewModel
import jp.toastkid.yobidashi.browser.bookmark.BookmarkFragment
import jp.toastkid.yobidashi.browser.floating.FloatingPreview
import jp.toastkid.yobidashi.browser.page_search.PageSearcherModule
import jp.toastkid.yobidashi.browser.permission.DownloadPermissionRequestContract
import jp.toastkid.yobidashi.browser.webview.GlobalWebViewPool
import jp.toastkid.yobidashi.databinding.ActivityMainBinding
import jp.toastkid.yobidashi.libs.Toaster
import jp.toastkid.yobidashi.libs.clip.ClippingUrlOpener
import jp.toastkid.yobidashi.libs.image.BackgroundImageLoaderUseCase
import jp.toastkid.yobidashi.libs.network.DownloadAction
import jp.toastkid.yobidashi.main.launch.ElseCaseUseCase
import jp.toastkid.yobidashi.main.launch.LauncherIntentUseCase
import jp.toastkid.yobidashi.main.launch.RandomWikipediaUseCase
import jp.toastkid.yobidashi.main.usecase.BackgroundTabOpenerUseCase
import jp.toastkid.yobidashi.main.usecase.MusicPlayerUseCase
import jp.toastkid.yobidashi.menu.MenuBinder
import jp.toastkid.yobidashi.menu.MenuSwitchColorApplier
import jp.toastkid.yobidashi.menu.MenuUseCase
import jp.toastkid.yobidashi.menu.MenuViewModel
import jp.toastkid.yobidashi.search.SearchAction
import jp.toastkid.yobidashi.search.SearchFragment
import jp.toastkid.yobidashi.search.clip.SearchWithClip
import jp.toastkid.yobidashi.search.usecase.SearchFragmentFactoryUseCase
import jp.toastkid.yobidashi.settings.SettingFragment
import jp.toastkid.yobidashi.settings.fragment.OverlayColorFilterViewModel
import jp.toastkid.yobidashi.tab.TabAdapter
import jp.toastkid.yobidashi.tab.model.EditorTab
import jp.toastkid.yobidashi.tab.model.Tab
import jp.toastkid.yobidashi.tab.tab_list.TabListDialogFragment
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
/**
* Main of this calendar app.
*
* @author toastkidjp
*/
class MainActivity : AppCompatActivity(), TabListDialogFragment.Callback {
/**
* Data binding object.
*/
private lateinit var binding: ActivityMainBinding
/**
* Preferences wrapper.
*/
private lateinit var preferenceApplier: PreferenceApplier
private lateinit var tabs: TabAdapter
private var floatingPreview: FloatingPreview? = null
/**
* Menu's view model.
*/
private var menuViewModel: MenuViewModel? = null
private var contentViewModel: ContentViewModel? = null
private var tabListViewModel: TabListViewModel? = null
private var browserViewModel: BrowserViewModel? = null
/**
* Search-with-clip object.
*/
private lateinit var searchWithClip: SearchWithClip
private val backgroundImageLoaderUseCase by lazy { BackgroundImageLoaderUseCase() }
/**
* Find-in-page module.
*/
private lateinit var pageSearchPresenter: PageSearcherModule
private lateinit var tabReplacingUseCase: TabReplacingUseCase
private lateinit var onBackPressedUseCase: OnBackPressedUseCase
private lateinit var appBarVisibilityUseCase: AppBarVisibilityUseCase
private lateinit var fragmentReplacingUseCase: FragmentReplacingUseCase
private var tabListUseCase: TabListUseCase? = null
private lateinit var menuSwitchColorApplier: MenuSwitchColorApplier
private var musicPlayerUseCase: MusicPlayerUseCase? = null
private var activityResultLauncher: ActivityResultLauncher<Intent>? =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode != Activity.RESULT_OK) {
return@registerForActivityResult
}
val data = it.data ?: return@registerForActivityResult
val uri = data.data ?: return@registerForActivityResult
val takeFlags: Int =
data.flags and Intent.FLAG_GRANT_READ_URI_PERMISSION
contentResolver?.takePersistableUriPermission(uri, takeFlags)
tabs.openNewPdfTab(uri)
replaceToCurrentTab(true)
tabListUseCase?.dismiss()
}
private val requestPermissionForOpenPdfTab =
registerForActivityResult(ActivityResultContracts.RequestPermission()) {
if (!it) {
return@registerForActivityResult
}
activityResultLauncher?.launch(OpenDocumentIntentFactory()("application/pdf"))
}
private val mediaPermissionRequestLauncher =
registerForActivityResult(ReadAudioPermissionRequestContract()) {
it.second?.invoke(it.first)
}
private val musicPlayerBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
musicPlayerUseCase?.invoke(binding.root)
}
}
private val downloadPermissionRequestLauncher =
registerForActivityResult(DownloadPermissionRequestContract()) {
if (it.first.not()) {
contentViewModel?.snackShort(R.string.message_requires_permission_storage)
return@registerForActivityResult
}
val url = it.second ?: return@registerForActivityResult
DownloadAction(this).invoke(url)
}
/**
* Disposables.
*/
private val disposables: Job by lazy { Job() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(LAYOUT_ID)
preferenceApplier = PreferenceApplier(this)
binding = DataBindingUtil.setContentView(this, LAYOUT_ID)
setSupportActionBar(binding.toolbar)
fragmentReplacingUseCase = FragmentReplacingUseCase(supportFragmentManager)
val colorPair = preferenceApplier.colorPair()
pageSearchPresenter = PageSearcherModule(binding.sip)
appBarVisibilityUseCase = AppBarVisibilityUseCase(binding.toolbar, preferenceApplier)
initializeHeaderViewModel()
initializeContentViewModel()
initializeMenuViewModel()
menuSwitchColorApplier = MenuSwitchColorApplier(binding.menuSwitch)
val activityViewModelProvider = ViewModelProvider(this)
browserViewModel = activityViewModelProvider.get(BrowserViewModel::class.java)
browserViewModel?.preview?.observe(this, Observer {
val uri = it?.getContentIfNotHandled() ?: return@Observer
Inputs.hideKeyboard(binding.content)
if (floatingPreview == null) {
floatingPreview = FloatingPreview(this)
}
floatingPreview?.show(binding.root, uri.toString())
})
browserViewModel?.open?.observe(this, Observer {
val uri = it?.getContentIfNotHandled() ?: return@Observer
openNewWebTab(uri)
})
val backgroundTabOpenerUseCase = BackgroundTabOpenerUseCase(
binding.content,
{ title, url -> tabs.openBackgroundTab(title, url) },
{ replaceToCurrentTab(true) }
)
browserViewModel?.openBackground?.observe(this, Observer {
val urlString = it?.getContentIfNotHandled()?.toString() ?: return@Observer
backgroundTabOpenerUseCase(urlString, urlString, preferenceApplier.colorPair())
})
browserViewModel?.openBackgroundWithTitle?.observe(this, Observer {
val pair = it?.getContentIfNotHandled() ?: return@Observer
backgroundTabOpenerUseCase(pair.first, pair.second.toString(), preferenceApplier.colorPair())
})
browserViewModel?.download?.observe(this, Observer {
val url = it?.getContentIfNotHandled() ?: return@Observer
downloadPermissionRequestLauncher.launch(url)
})
invokeSearchWithClip(colorPair)
CoroutineScope(Dispatchers.Main).launch {
activityViewModelProvider.get(LoadingViewModel::class.java)
.onPageFinished
.collect {
if (it.expired()) {
return@collect
}
tabs.updateWebTab(it.tabId to it.history)
if (tabs.currentTabId() == it.tabId) {
refreshThumbnail()
}
}
}
activityViewModelProvider.get(OverlayColorFilterViewModel::class.java)
.newColor
.observe(this, {
updateColorFilter()
})
tabListViewModel = activityViewModelProvider.get(TabListViewModel::class.java)
tabListViewModel
?.saveEditorTab
?.observe(
this,
Observer {
val currentTab = tabs.currentTab() as? EditorTab ?: return@Observer
currentTab.setFileInformation(it)
tabs.saveTabList()
}
)
tabListViewModel
?.openNewTab
?.observe(this, { openNewTabFromTabList() })
supportFragmentManager.setFragmentResultListener("clear_tabs", this, { key, result ->
if (result.getBoolean(key).not()) {
return@setFragmentResultListener
}
onClickClear()
})
tabs = TabAdapter({ this }, this::onEmptyTabs)
tabReplacingUseCase = TabReplacingUseCase(
tabs,
::obtainFragment,
{ fragment, animation -> replaceFragment(fragment, animation) },
activityViewModelProvider.get(BrowserFragmentViewModel::class.java),
::refreshThumbnail,
{
CoroutineScope(Dispatchers.IO).launch(disposables) {
runOnUiThread(it)
}
}
)
processShortcut(intent)
onBackPressedUseCase = OnBackPressedUseCase(
tabListUseCase,
{ binding.menuStub.root?.isVisible == true },
menuViewModel,
pageSearchPresenter,
{ floatingPreview },
tabs,
::onEmptyTabs,
tabReplacingUseCase,
supportFragmentManager
)
registerReceiver(musicPlayerBroadcastReceiver, IntentFilter("jp.toastkid.music.action.open"))
supportFragmentManager.addOnBackStackChangedListener {
val findFragment = findFragment()
if (findFragment !is TabUiFragment && supportFragmentManager.backStackEntryCount == 0) {
finish()
}
}
}
private fun invokeSearchWithClip(colorPair: ColorPair) {
searchWithClip = SearchWithClip(
applicationContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager,
binding.content,
colorPair,
browserViewModel,
preferenceApplier
)
searchWithClip.invoke()
}
private fun obtainFragment(fragmentClass: Class<out Fragment>) =
supportFragmentManager.findFragmentByTag(fragmentClass.canonicalName)
?: fragmentClass.newInstance()
private fun initializeHeaderViewModel() {
val headerViewModel = ViewModelProvider(this).get(AppBarViewModel::class.java)
headerViewModel.content.observe(this, Observer { view ->
if (view == null) {
return@Observer
}
binding.toolbarContent.removeAllViews()
if (view.parent != null) {
(view.parent as? ViewGroup)?.removeAllViews()
}
if (view.layoutParams != null) {
binding.toolbar.layoutParams.height = view.layoutParams.height
}
binding.toolbarContent.addView(view, 0)
})
headerViewModel.visibility.observe(this, { isVisible ->
if (isVisible) appBarVisibilityUseCase.show() else appBarVisibilityUseCase.hide()
})
}
private fun initializeMenuViewModel() {
menuViewModel = ViewModelProvider(this).get(MenuViewModel::class.java)
MenuBinder(this, menuViewModel, binding.menuStub, binding.menuSwitch)
musicPlayerUseCase = MusicPlayerUseCase(mediaPermissionRequestLauncher)
val menuUseCase = MenuUseCase({ this }, menuViewModel, contentViewModel, musicPlayerUseCase)
menuUseCase.observe()
}
private fun initializeContentViewModel() {
contentViewModel = ViewModelProvider(this).get(ContentViewModel::class.java)
contentViewModel?.fragmentClass?.observe(this, Observer {
val fragmentClass = it?.getContentIfNotHandled() ?: return@Observer
replaceFragment(obtainFragment(fragmentClass), withAnimation = true, withSlideIn = true)
})
contentViewModel?.fragment?.observe(this, Observer {
val fragment = it?.getContentIfNotHandled() ?: return@Observer
replaceFragment(fragment, withAnimation = true, withSlideIn = false)
})
contentViewModel?.snackbar?.observe(this, Observer {
val snackbarEvent = it.getContentIfNotHandled() ?: return@Observer
if (snackbarEvent.actionLabel == null) {
Toaster.snackShort(
binding.content,
snackbarEvent.message,
preferenceApplier.colorPair()
)
return@Observer
}
Toaster.withAction(
binding.content,
snackbarEvent.message,
snackbarEvent.actionLabel ?: "",
{ snackbarEvent.action() },
preferenceApplier.colorPair()
)
})
contentViewModel?.snackbarRes?.observe(this, Observer {
val messageId = it?.getContentIfNotHandled() ?: return@Observer
Toaster.snackShort(binding.content, messageId, preferenceApplier.colorPair())
})
contentViewModel?.toTop?.observe(this, {
(findFragment() as? ContentScrollable)?.toTop()
})
contentViewModel?.toBottom?.observe(this, {
(findFragment() as? ContentScrollable)?.toBottom()
})
contentViewModel?.share?.observe(this, Observer {
if (it.hasBeenHandled) {
return@Observer
}
it.getContentIfNotHandled()
(findFragment() as? CommonFragmentAction)?.share()
})
contentViewModel?.webSearch?.observe(this, {
when (val fragment = findFragment()) {
is BrowserFragment -> {
val titleAndUrl = fragment.getTitleAndUrl()
replaceFragment(SearchFragmentFactoryUseCase().invoke(titleAndUrl))
}
else ->
contentViewModel?.nextFragment(SearchFragment::class.java)
}
})
contentViewModel?.openPdf?.observe(this, {
openPdfTabFromStorage()
})
contentViewModel?.openEditorTab?.observe(this, {
openEditorTab()
})
contentViewModel?.switchPageSearcher?.observe(this, {
pageSearchPresenter.switch()
})
contentViewModel?.switchTabList?.observe(this, Observer {
it?.getContentIfNotHandled() ?: return@Observer
switchTabList()
})
contentViewModel?.refresh?.observe(this, {
refresh()
})
contentViewModel?.newArticle?.observe(this, Observer {
val titleAndOnBackground = it?.getContentIfNotHandled() ?: return@Observer
tabs.openNewArticleTab(titleAndOnBackground.first, titleAndOnBackground.second)
if (titleAndOnBackground.second) {
contentViewModel?.snackShort(
getString(R.string.message_tab_open_background, titleAndOnBackground.first)
)
} else {
replaceToCurrentTab()
}
})
contentViewModel?.openArticleList?.observe(this, {
tabs.openArticleList()
replaceToCurrentTab()
})
contentViewModel?.openCalendar?.observe(this, {
tabs.openCalendar()
replaceToCurrentTab()
})
}
override fun onNewIntent(passedIntent: Intent) {
super.onNewIntent(passedIntent)
processShortcut(passedIntent)
}
/**
* Process intent shortcut.
*
* @param calledIntent
*/
private fun processShortcut(calledIntent: Intent) {
LauncherIntentUseCase(
RandomWikipediaUseCase(
contentViewModel,
this::openNewWebTab,
{ id, param -> getString(id, param) }
),
this::openNewWebTab,
{ openEditorTab(FileExtractorFromUri(this, it)) },
::search,
{
preferenceApplier.getDefaultSearchEngine()
?: SearchCategory.getDefaultCategoryName()
},
{ replaceFragment(obtainFragment(it)) },
ElseCaseUseCase(
tabs::isEmpty,
::openNewTab,
{ supportFragmentManager.findFragmentById(R.id.content) },
{ replaceToCurrentTab(false) }
)
).invoke(calledIntent)
}
private fun search(category: String?, query: String?) {
if (category.isNullOrEmpty() || query.isNullOrEmpty()) {
return
}
SearchAction(this, category, query).invoke()
}
private fun openNewWebTab(uri: Uri) {
tabs.openNewWebTab(uri.toString())
replaceToCurrentTab(true)
}
/**
* Replace with passed fragment.
*
* @param fragment {@link BaseFragment} instance
*/
private fun replaceFragment(
fragment: Fragment,
withAnimation: Boolean = true,
withSlideIn: Boolean = false
) {
fragmentReplacingUseCase.invoke(fragment, withAnimation, withSlideIn)
}
/**
* Replace visibilities for current tab.
*
* @param withAnimation for suppress redundant animation.
*/
private fun replaceToCurrentTab(withAnimation: Boolean = true) {
tabReplacingUseCase.invoke(withAnimation)
}
private fun refreshThumbnail() {
CoroutineScope(Dispatchers.Default).launch(disposables) {
runOnUiThread {
val findFragment = findFragment()
if (findFragment !is TabUiFragment) {
return@runOnUiThread
}
tabs.saveNewThumbnail(binding.content)
}
}
}
override fun onBackPressed() {
onBackPressedUseCase.invoke()
}
private fun findFragment() = supportFragmentManager.findFragmentById(R.id.content)
override fun onResume() {
super.onResume()
refresh()
menuViewModel?.onResume()
floatingPreview?.onResume()
tabs.setCount()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
ClippingUrlOpener()(binding.content) { browserViewModel?.open(it) }
}
/**
* Refresh toolbar and background.
*/
private fun refresh() {
val colorPair = preferenceApplier.colorPair()
ToolbarColorApplier()(binding.toolbar, colorPair)
WindowOptionColorApplier()(window, colorPair)
RecentAppColoringUseCase(
::getString,
{ resources },
::setTaskDescription,
Build.VERSION.SDK_INT
).invoke(preferenceApplier.color)
menuSwitchColorApplier(colorPair)
backgroundImageLoaderUseCase.invoke(binding.background, preferenceApplier.backgroundImagePath)
updateColorFilter()
}
private fun updateColorFilter() {
ForegroundColorFilterUseCase(preferenceApplier).invoke(binding.foreground)
floatingPreview?.onResume()
}
/**
* Open PDF from storage.
*/
private fun openPdfTabFromStorage() {
requestPermissionForOpenPdfTab.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
}
/**
* Open Editor tab.
*/
private fun openEditorTab(path: String? = null) {
tabs.openNewEditorTab(path)
replaceToCurrentTab()
}
/**
* Switch tab list visibility.
*/
private fun switchTabList() {
if (tabListUseCase == null) {
tabListUseCase = TabListUseCase(supportFragmentManager, this::refreshThumbnail)
}
tabListUseCase?.switch()
}
/**
* Action on empty tabs.
*/
private fun onEmptyTabs() {
tabListUseCase?.dismiss()
openNewTab()
}
private fun onClickClear() {
tabs.clear()
onEmptyTabs()
}
override fun onCloseOnly() {
tabListUseCase?.dismiss()
}
override fun onCloseTabListDialogFragment(lastTabId: String) {
if (lastTabId != tabs.currentTabId()) {
replaceToCurrentTab()
}
}
override fun onOpenEditor() = openEditorTab()
override fun onOpenPdf() = openPdfTabFromStorage()
override fun openNewTabFromTabList() {
openNewTab()
}
private fun openNewTab() {
when (StartUp.findByName(preferenceApplier.startUp)) {
StartUp.SEARCH -> {
replaceFragment(obtainFragment(SearchFragment::class.java))
}
StartUp.BROWSER -> {
tabs.openNewWebTab()
replaceToCurrentTab(true)
}
StartUp.BOOKMARK -> {
replaceFragment(obtainFragment(BookmarkFragment::class.java))
}
}
}
override fun tabIndexFromTabList() = tabs.index()
override fun currentTabIdFromTabList() = tabs.currentTabId()
override fun replaceTabFromTabList(tab: Tab) {
tabs.replace(tab)
(obtainFragment(BrowserFragment::class.java) as? BrowserFragment)?.stopSwipeRefresherLoading()
}
override fun getTabByIndexFromTabList(position: Int): Tab? = tabs.getTabByIndex(position)
override fun closeTabFromTabList(position: Int) {
tabs.closeTab(position)
(obtainFragment(BrowserFragment::class.java) as? BrowserFragment)?.stopSwipeRefresherLoading()
}
override fun getTabAdapterSizeFromTabList(): Int = tabs.size()
override fun swapTabsFromTabList(from: Int, to: Int) = tabs.swap(from, to)
override fun tabIndexOfFromTabList(tab: Tab): Int = tabs.indexOf(tab)
override fun onCreateOptionsMenu(menu: android.view.Menu?): Boolean {
menuInflater.inflate(R.menu.main_fab_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.open_tabs -> {
switchTabList()
true
}
R.id.setting -> {
(obtainFragment(SettingFragment::class.java) as? SettingFragment)?.let {
val currentFragment = findFragment()
it.setFrom(currentFragment?.javaClass)
replaceFragment(it, withAnimation = true, withSlideIn = true)
}
true
}
R.id.reset_menu_position -> {
menuViewModel?.resetPosition()
true
}
R.id.menu_exit -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
override fun onPause() {
super.onPause()
floatingPreview?.onPause()
tabs.saveTabList()
}
override fun onDestroy() {
tabs.dispose()
disposables.cancel()
searchWithClip.dispose()
pageSearchPresenter.dispose()
floatingPreview?.dispose()
GlobalWebViewPool.dispose()
activityResultLauncher?.unregister()
requestPermissionForOpenPdfTab.unregister()
downloadPermissionRequestLauncher.unregister()
unregisterReceiver(musicPlayerBroadcastReceiver)
supportFragmentManager.clearFragmentResultListener("clear_tabs")
super.onDestroy()
}
companion object {
/**
* Layout ID.
*/
@LayoutRes
private const val LAYOUT_ID = R.layout.activity_main
}
}
| epl-1.0 | e1eda0d51278757c8d2cd6ce7368933b | 33.799472 | 105 | 0.641823 | 5.45 | false | false | false | false |
albertoruibal/karballo | karballo-jvm/src/test/kotlin/karballo/BaseTest.kt | 1 | 2138 | package karballo
import karballo.bitboard.AttacksInfo
import karballo.evaluation.CompleteEvaluator
import karballo.evaluation.Evaluator
import karballo.search.SearchEngine
import karballo.search.SearchParameters
import karballo.util.JvmPlatformUtils
import karballo.util.Utils
import org.junit.Assert.assertTrue
abstract class BaseTest {
constructor() {
Utils.instance = JvmPlatformUtils()
}
fun getEval(fen: String): Int {
val attacksInfo = AttacksInfo()
val evaluator = CompleteEvaluator()
evaluator.debug = true
val board = Board()
board.fen = fen
return evaluator.evaluate(board, attacksInfo)
}
/**
* Compares the eval of two fens
*/
fun compareEval(fenBetter: String, fenWorse: String, requiredDifference: Int) {
println("*\n* Comparing two board evaluations (first must be better for white):\n*")
val valueBetter = getEval(fenBetter)
val valueWorse = getEval(fenWorse)
println("valueBetter = " + valueBetter)
println("valueWorse = " + valueWorse)
assertTrue(valueBetter > valueWorse + requiredDifference)
}
fun getSearchQS(fen: String): Int {
val search = SearchEngine(Config())
search.board.fen = fen
try {
return search.quiescentSearch(0, -Evaluator.MATE, Evaluator.MATE)
} catch (e: Exception) {
e.printStackTrace()
}
return 0
}
fun getSearchScore(fen: String, depth: Int): Long {
val search = SearchEngine(Config())
search.debug = true
val searchParams = SearchParameters()
search.board.fen = fen
searchParams.depth = depth
search.go(searchParams)
return search.bestMoveScore.toLong()
}
fun getSearchBestMoveSan(fen: String, depth: Int): String {
val search = SearchEngine(Config())
search.debug = true
val searchParams = SearchParameters()
search.board.fen = fen
searchParams.depth = depth
search.go(searchParams)
return Move.toSan(search.board, search.bestMove)
}
}
| mit | d7f24df0e39261ea77812cef38d1d214 | 29.112676 | 92 | 0.651076 | 4.310484 | false | false | false | false |
consp1racy/android-commons | commons/src/main/java/android/arch/lifecycle/XpViewModel.kt | 1 | 4232 | package android.arch.lifecycle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import net.xpece.androidx.lifecycle.activityViewModel as activityViewModelImpl
import net.xpece.androidx.lifecycle.lazyActivityViewModel as lazyActivityViewModelImpl
import net.xpece.androidx.lifecycle.lazyViewModel as lazyViewModelImpl
import net.xpece.androidx.lifecycle.viewModel as viewModelImpl
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"viewModel",
imports = ["net.xpece.androidx.lifecycle.viewModel"]
)
)
inline fun <reified T : ViewModel> FragmentActivity.viewModel() =
viewModelImpl<T>()
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"viewModel",
imports = ["net.xpece.androidx.lifecycle.viewModel"]
)
)
inline fun <reified T : ViewModel> Fragment.viewModel() =
viewModelImpl<T>()
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"activityViewModel",
imports = ["net.xpece.androidx.lifecycle.activityViewModel"]
)
)
inline fun <reified T : ViewModel> Fragment.activityViewModel() =
activityViewModelImpl<T>()
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"viewModel",
imports = ["net.xpece.androidx.lifecycle.viewModel"]
)
)
inline fun <reified T : ViewModel> FragmentActivity.viewModel(factory: ViewModelProvider.Factory) =
viewModelImpl<T>(factory)
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"viewModel",
imports = ["net.xpece.androidx.lifecycle.viewModel"]
)
)
inline fun <reified T : ViewModel> Fragment.viewModel(factory: ViewModelProvider.Factory) =
viewModelImpl<T>(factory)
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"activityViewModel",
imports = ["net.xpece.androidx.lifecycle.activityViewModel"]
)
)
inline fun <reified T : ViewModel> Fragment.activityViewModel(factory: ViewModelProvider.Factory) =
activityViewModelImpl<T>(factory)
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"lazyViewModel",
imports = ["net.xpece.androidx.lifecycle.lazyViewModel"]
)
)
inline fun <reified T : ViewModel> FragmentActivity.lazyViewModel(
crossinline factory: () -> ViewModelProvider.Factory
) = lazyViewModelImpl<T>(factory)
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"lazyViewModel",
imports = ["net.xpece.androidx.lifecycle.lazyViewModel"]
)
)
inline fun <reified T : ViewModel> FragmentActivity.lazyViewModel() =
lazyViewModelImpl<T>()
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"lazyViewModel",
imports = ["net.xpece.androidx.lifecycle.lazyViewModel"]
)
)
inline fun <reified T : ViewModel> Fragment.lazyViewModel(
crossinline factory: () -> ViewModelProvider.Factory
) = lazyViewModelImpl<T>(factory)
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"lazyViewModel",
imports = ["net.xpece.androidx.lifecycle.lazyViewModel"]
)
)
inline fun <reified T : ViewModel> Fragment.lazyViewModel() =
lazyViewModelImpl<T>()
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"lazyActivityViewModel",
imports = ["net.xpece.androidx.lifecycle.lazyActivityViewModel"]
)
)
inline fun <reified T : ViewModel> Fragment.lazyActivityViewModel(
crossinline factory: () -> ViewModelProvider.Factory
) = lazyActivityViewModelImpl<T>(factory)
@Deprecated(
"This extension function is not available when using Jetifier.",
ReplaceWith(
"lazyActivityViewModel",
imports = ["net.xpece.androidx.lifecycle.lazyActivityViewModel"]
)
)
inline fun <reified T : ViewModel> Fragment.lazyActivityViewModel() =
lazyActivityViewModelImpl<T>()
| apache-2.0 | 8a2d4d221f4a95406dd7353002ac5ba0 | 31.305344 | 99 | 0.719754 | 4.506922 | false | false | false | false |
appfoundry/fastlane-android-example | sample/app/src/main/kotlin/be/vergauwen/simon/androidretaindata/core/di/ServiceModule.kt | 1 | 1447 | package be.vergauwen.simon.androidretaindata.core.di
import be.vergauwen.simon.androidretaindata.BuildConfig
import be.vergauwen.simon.androidretaindata.core.data.RxDataRepository
import be.vergauwen.simon.androidretaindata.core.service.GithubAPI
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
@Module
open class ServiceModule {
val URI = "https://api.github.com"
@ApplicationScope
@Provides
open fun provideRestAdapter(): Retrofit {
val logging = HttpLoggingInterceptor();
if (BuildConfig.DEBUG) {
logging.level = HttpLoggingInterceptor.Level.BODY;
} else {
logging.level = HttpLoggingInterceptor.Level.NONE;
}
val httpClient = OkHttpClient.Builder();
httpClient.interceptors().add(logging)
return Retrofit.Builder().baseUrl(URI)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClient.build())
.build()
}
@ApplicationScope
@Provides
open fun provideGithubAPI(retrofit: Retrofit): GithubAPI = retrofit.create(GithubAPI::class.java)
@ApplicationScope
@Provides
open fun provideDataRepository(githubAPI: GithubAPI): RxDataRepository = RxDataRepository(githubAPI)
} | mit | ec627a522a4613b8565d0249b5b3e558 | 29.166667 | 102 | 0.778162 | 4.593651 | false | false | false | false |
Zhuinden/simple-stack | samples/community-samples/simple-stack-example-kotlin-community-sample/src/main/java/com/community/simplestackkotlindaggerexample/screens/users/UsersFragment.kt | 1 | 3727 | package com.community.simplestackkotlindaggerexample.screens.users
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.community.simplestackkotlindaggerexample.R
import com.community.simplestackkotlindaggerexample.application.Injector
import com.community.simplestackkotlindaggerexample.core.schedulers.SchedulerProvider
import com.community.simplestackkotlindaggerexample.data.api.ApiService
import com.community.simplestackkotlindaggerexample.data.database.User
import com.community.simplestackkotlindaggerexample.databinding.FragmentUsersBinding
import com.community.simplestackkotlindaggerexample.utils.clearIfNotDisposed
import com.community.simplestackkotlindaggerexample.utils.hide
import com.community.simplestackkotlindaggerexample.utils.onTextChanged
import com.community.simplestackkotlindaggerexample.utils.show
import com.zhuinden.simplestackextensions.fragments.KeyedFragment
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import io.realm.Realm
import io.realm.kotlin.where
import javax.inject.Inject
class UsersFragment : KeyedFragment(R.layout.fragment_users) {
private val compositeDisposable = CompositeDisposable()
@Inject
lateinit var apiService: ApiService
@Inject
lateinit var schedulerProvider: SchedulerProvider
private lateinit var realm: Realm
private lateinit var usersAdapter: UsersAdapter
override fun onAttach(context: Context) {
super.onAttach(context)
Injector.get().inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentUsersBinding.bind(view)
realm = Realm.getDefaultInstance()
usersAdapter = UsersAdapter(realm.where<User>().findAllAsync())
binding.listContacts.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
binding.listContacts.adapter = usersAdapter
binding.textUserSearch.onTextChanged { username ->
val query = realm.where<User>().run {
if (username.isNotEmpty()) {
return@run this.contains("userName", username)
} else {
this
}
}
usersAdapter.updateData(query.findAllAsync())
}
fun loadUsers() {
binding.loadingView.root.show()
compositeDisposable += apiService
.getAllUsers()
.subscribeOn(schedulerProvider.io())
.doOnNext { userResponse ->
val users = userResponse.result.map { user -> User.createFromUser(user) }
Realm.getDefaultInstance().use { r ->
r.executeTransaction { realm ->
realm.insertOrUpdate(users)
}
}
}
.observeOn(schedulerProvider.ui())
.doFinally { binding.loadingView.root.hide() }
.subscribeBy(
onNext = {
println("Saved users to Realm.")
},
onError = { e ->
e.printStackTrace()
},
onComplete = {
}
)
}
loadUsers()
}
override fun onDestroyView() {
compositeDisposable.clearIfNotDisposed()
super.onDestroyView()
realm.close()
}
} | apache-2.0 | 709bd36d1c6aaf0adffadbd543527e23 | 34.504762 | 103 | 0.657633 | 5.604511 | false | false | false | false |
talhacohen/android | app/src/main/java/com/etesync/syncadapter/ui/setup/DetectConfigurationFragment.kt | 1 | 4739 | /*
* 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.setup
import android.app.Dialog
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v4.app.LoaderManager
import android.support.v4.content.AsyncTaskLoader
import android.support.v4.content.Loader
import android.support.v7.app.AlertDialog
import com.etesync.syncadapter.App
import com.etesync.syncadapter.R
import com.etesync.syncadapter.ui.DebugInfoActivity
import com.etesync.syncadapter.ui.setup.BaseConfigurationFinder.Configuration
class DetectConfigurationFragment : DialogFragment(), LoaderManager.LoaderCallbacks<Configuration> {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val progress = ProgressDialog(activity)
progress.setTitle(R.string.login_configuration_detection)
progress.setMessage(getString(R.string.login_querying_server))
progress.isIndeterminate = true
progress.setCanceledOnTouchOutside(false)
isCancelable = false
return progress
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loaderManager.initLoader(0, arguments, this)
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Configuration> {
return ServerConfigurationLoader(context!!, args!!.getParcelable(ARG_LOGIN_CREDENTIALS) as LoginCredentials)
}
override fun onLoadFinished(loader: Loader<Configuration>, data: Configuration?) {
if (data != null) {
if (data.isFailed)
// no service found: show error message
fragmentManager!!.beginTransaction()
.add(NothingDetectedFragment.newInstance(data.logs), null)
.commitAllowingStateLoss()
else
// service found: continue
fragmentManager!!.beginTransaction()
.replace(android.R.id.content, EncryptionDetailsFragment.newInstance(data))
.addToBackStack(null)
.commitAllowingStateLoss()
} else
App.log.severe("Configuration detection failed")
dismissAllowingStateLoss()
}
override fun onLoaderReset(loader: Loader<Configuration>) {}
class NothingDetectedFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(activity!!)
.setTitle(R.string.login_configuration_detection)
.setIcon(R.drawable.ic_error_dark)
.setMessage(R.string.login_wrong_username_or_password)
.setNeutralButton(R.string.login_view_logs) { dialog, which ->
val intent = Intent(activity, DebugInfoActivity::class.java)
intent.putExtra(DebugInfoActivity.KEY_LOGS, arguments!!.getString(KEY_LOGS))
startActivity(intent)
}
.setPositiveButton(android.R.string.ok) { dialog, which ->
// dismiss
}
.create()
}
companion object {
private val KEY_LOGS = "logs"
fun newInstance(logs: String): NothingDetectedFragment {
val args = Bundle()
args.putString(KEY_LOGS, logs)
val fragment = NothingDetectedFragment()
fragment.arguments = args
return fragment
}
}
}
internal class ServerConfigurationLoader(context: Context, val credentials: LoginCredentials) : AsyncTaskLoader<Configuration>(context) {
override fun onStartLoading() {
forceLoad()
}
override fun loadInBackground(): Configuration? {
return BaseConfigurationFinder(context, credentials).findInitialConfiguration()
}
}
companion object {
protected val ARG_LOGIN_CREDENTIALS = "credentials"
fun newInstance(credentials: LoginCredentials): DetectConfigurationFragment {
val frag = DetectConfigurationFragment()
val args = Bundle(1)
args.putParcelable(ARG_LOGIN_CREDENTIALS, credentials)
frag.arguments = args
return frag
}
}
}
| gpl-3.0 | e8a7873c4232cd350cf8ae25656f1651 | 37.504065 | 141 | 0.64886 | 5.315376 | false | true | false | false |
ntemplon/legends-of-omterra | core/src/com/jupiter/europa/entity/Families.kt | 1 | 2310 | /*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.jupiter.europa.entity
import com.badlogic.ashley.core.Family
import com.jupiter.europa.entity.component.*
/**
* @author Nathan Templon
*/
public object Families {
// Constants
public val abilitied: Family = Family.all(javaClass<AbilityComponent>()).get()
public val attributed: Family = Family.all(javaClass<AttributesComponent>()).get()
public val classed: Family = Family.all(javaClass<CharacterClassComponent>()).get()
public val collidables: Family = Family.all(javaClass<CollisionComponent>()).get()
public val affectables: Family = Family.all(javaClass<EffectsComponent>()).get()
public val positionables: Family = Family.all(javaClass<PositionComponent>(), javaClass<SizeComponent>()).get()
public val raced: Family = Family.all(javaClass<RaceComponent>()).get()
public val renderables: Family = Family.all(javaClass<RenderComponent>()).get()
public val resourced: Family = Family.all(javaClass<ResourceComponent>()).get()
public val walkables: Family = Family.all(javaClass<PositionComponent>(), javaClass<SizeComponent>(), javaClass<WalkComponent>(), javaClass<MovementResourceComponent>()).get()
}
| mit | dc777dac538e5e46452090eecd61bbb5 | 47.125 | 179 | 0.752381 | 4.511719 | false | false | false | false |
italoag/qksms | presentation/src/main/java/com/moez/QKSMS/common/widget/PreferenceView.kt | 3 | 3316 | /*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.widget
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.LinearLayoutCompat
import com.moez.QKSMS.R
import com.moez.QKSMS.common.util.extensions.resolveThemeAttribute
import com.moez.QKSMS.common.util.extensions.resolveThemeColorStateList
import com.moez.QKSMS.common.util.extensions.setVisible
import com.moez.QKSMS.injection.appComponent
import kotlinx.android.synthetic.main.preference_view.view.*
class PreferenceView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : LinearLayoutCompat(context, attrs) {
var title: String? = null
set(value) {
field = value
if (isInEditMode) {
findViewById<TextView>(R.id.titleView).text = value
} else {
titleView.text = value
}
}
var summary: String? = null
set(value) {
field = value
if (isInEditMode) {
findViewById<TextView>(R.id.summaryView).run {
text = value
setVisible(value?.isNotEmpty() == true)
}
} else {
summaryView.text = value
summaryView.setVisible(value?.isNotEmpty() == true)
}
}
init {
if (!isInEditMode) {
appComponent.inject(this)
}
View.inflate(context, R.layout.preference_view, this)
setBackgroundResource(context.resolveThemeAttribute(R.attr.selectableItemBackground))
orientation = HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
icon.imageTintList = context.resolveThemeColorStateList(android.R.attr.textColorSecondary)
context.obtainStyledAttributes(attrs, R.styleable.PreferenceView).run {
title = getString(R.styleable.PreferenceView_title)
summary = getString(R.styleable.PreferenceView_summary)
// If there's a custom view used for the preference's widget, inflate it
getResourceId(R.styleable.PreferenceView_widget, -1).takeIf { it != -1 }?.let { id ->
View.inflate(context, id, widgetFrame)
}
// If an icon is being used, set up the icon view
getResourceId(R.styleable.PreferenceView_icon, -1).takeIf { it != -1 }?.let { id ->
icon.setVisible(true)
icon.setImageResource(id)
}
recycle()
}
}
} | gpl-3.0 | d97e18c5e275372a307c8470083caacc | 33.552083 | 98 | 0.648673 | 4.573793 | false | false | false | false |
weibaohui/korm | src/main/kotlin/com/sdibt/korm/core/extension/DateTime.kt | 1 | 2602 | /*
* 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 com.sdibt.korm.core.extension
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.*
/**
* Usage:
* User: weibaohui
* Date: 2017/2/16
* Time: 09:42
*/
// 01. java.util.Date --> java.time.LocalDateTime
fun Date.UDateToLocalDateTime():LocalDateTime {
val instant = this.toInstant()
val zone = ZoneId.systemDefault()
return LocalDateTime.ofInstant(instant, zone)
}
// 02. java.util.Date --> java.time.LocalDate
//fun UDateToLocalDate() {
// val date = java.util.Date()
// val instant = date.toInstant()
// val zone = ZoneId.systemDefault()
// val localDateTime = LocalDateTime.ofInstant(instant, zone)
// val localDate = localDateTime.toLocalDate()
//}
//
//// 03. java.util.Date --> java.time.LocalTime
//fun UDateToLocalTime() {
// val date = java.util.Date()
// val instant = date.toInstant()
// val zone = ZoneId.systemDefault()
// val localDateTime = LocalDateTime.ofInstant(instant, zone)
// val localTime = localDateTime.toLocalTime()
//}
// 04. java.time.LocalDateTime --> java.util.Date
fun LocalDateTime.toDate(): Date {
val zone = ZoneId.systemDefault()
val instant = this.atZone(zone).toInstant()
val date = Date.from(instant)
return date
}
// 05. java.time.LocalDate --> java.util.Date
fun LocalDate.toDate(): Date {
val zone = ZoneId.systemDefault()
val instant = this.atStartOfDay().atZone(zone).toInstant()
val date = Date.from(instant)
return date
}
//
//// 06. java.time.LocalTime --> java.util.Date
//fun LocalTimeToUdate() {
// val localTime = LocalTime.now()
// val localDate = LocalDate.now()
// val localDateTime = LocalDateTime.of(localDate, localTime)
// val zone = ZoneId.systemDefault()
// val instant = localDateTime.atZone(zone).toInstant()
// val date = Date.from(instant)
//}
| apache-2.0 | 2e01191e10cf34812935eb6b98c8142d | 28.908046 | 76 | 0.720215 | 3.644258 | false | false | false | false |
jara0705/PolyShareByKotlin | kotlin_myshare/src/main/java/com/jara/kotlin_myshare/channel/ShareByWeChatK.kt | 1 | 8969 | package com.jara.kotlin_myshare.channel
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import com.jara.kotlin_myshare.R
import com.jara.kotlin_myshare.bean.Constant
import com.jara.kotlin_myshare.bean.ShareEntity
import com.jara.kotlin_myshare.http.Network
import com.jara.kotlin_myshare.interfaces.OnShareListener
import com.jara.kotlin_myshare.utils.ManifestUtil
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.*
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.reactivex.subscribers.DefaultSubscriber
import okhttp3.ResponseBody
import java.io.ByteArrayOutputStream
import java.io.File
/**
* Created by jara on 2017-9-19.
*/
class ShareByWeChatK(context: Context) : ShareBaseK(context) {
var channel: Int? = null
var entity: ShareEntity? = null
var listener: OnShareListener? = null
var iwxapi: IWXAPI? = null
var receiver = WeChatShareReceiver()
constructor(context: Context, channel: Int) : this(context) {
this.context = context.applicationContext
this.channel = channel
iwxapi = WXAPIFactory.createWXAPI(context.applicationContext, ManifestUtil.getWeixinKey(this.context))
}
override fun share(entity: ShareEntity, listener: OnShareListener) {
this.entity = entity
this.listener = listener
if (null == entity)
return
start()
}
fun start() {
if (iwxapi!!.isWXAppInstalled) {
val imgUrl = entity!!.imgUrl
if (!TextUtils.isEmpty(imgUrl)) {
if (imgUrl!!.startsWith("http")) {
getNetImage(imgUrl)
} else {
if (entity!!.isShareBigImg) {
shareImg(getLocalBitmap(imgUrl), listener)
} else {
send(getLocalBitmap(imgUrl))
}
}
} else if (entity!!.drawableId != 0) {
var drawable: BitmapDrawable? = null
try {
drawable = ContextCompat.getDrawable(context, entity!!.drawableId) as BitmapDrawable?
} catch (e: Exception) {
e.printStackTrace()
}
if (null != drawable) {
send(drawable.bitmap)
} else {
send()
}
} else {
send()
}
} else {
if (null != listener) {
listener!!.onShare(channel!!, Constant.SHARE_STATUS_FAILED)
}
}
}
fun getLocalBitmap(path: String): Bitmap {
val file = File(path)
if (file.exists()) {
try {
return BitmapFactory.decodeFile(path)
} catch (e: Exception) {
e.printStackTrace()
}
}
return BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_share_default)
}
fun send(bitmap: Bitmap? = null) {
val req = SendMessageToWX.Req()
req.transaction = System.currentTimeMillis().toString()
req.message = buildWXM(bitmap)
if (channel == Constant.SHARE_CHANNEL_WEIXIN_FRIEND) {
req.scene = SendMessageToWX.Req.WXSceneSession
} else if (channel == Constant.SHARE_CHANNEL_WEIXIN_CIRCLE) {
req.scene = SendMessageToWX.Req.WXSceneTimeline
}
iwxapi!!.sendReq(req)
}
fun buildWXM(bitmap: Bitmap?): WXMediaMessage {
val wxMediaMessage = WXMediaMessage()
wxMediaMessage.title = entity!!.title
wxMediaMessage.description = entity!!.content
if (TextUtils.isEmpty(entity!!.url)) {
wxMediaMessage.mediaObject = WXTextObject(entity!!.content)
} else {
if (null != bitmap) {
wxMediaMessage.setThumbImage(getWxShareBitmap(bitmap))
} else {
val defaultBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.ic_share_default)
if (null != defaultBitmap) {
wxMediaMessage.setThumbImage(getWxShareBitmap(defaultBitmap))
}
}
wxMediaMessage.mediaObject = WXWebpageObject(entity!!.url)
}
return wxMediaMessage
}
fun getWxShareBitmap(bitmap: Bitmap?): Bitmap {
val scale: Float = Math.min(150 / bitmap!!.width.toFloat(), 150 / bitmap.height.toFloat())
return Bitmap.createScaledBitmap(bitmap, (scale * bitmap.width).toInt(), (scale * bitmap.height).toInt(), false)
}
fun registerWeChatReceiver() {
val filter = IntentFilter(Constant.ACTION_WEIXIN_CALLBACK)
context.registerReceiver(receiver, filter)
}
fun unregisterWeChatReceiver() {
if (null != context && null != receiver) {
context.unregisterReceiver(receiver)
}
}
fun getNetImage(imgUrl: String) {
Network.getService()!!.getImage(imgUrl)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DefaultSubscriber<ResponseBody>() {
override fun onComplete() {
}
override fun onError(t: Throwable?) {
}
override fun onNext(r: ResponseBody?) {
val stream = r!!.byteStream()
val bitmap = BitmapFactory.decodeStream(stream)
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.WEBP, 100, baos)
baos.close()
if (entity!!.isShareBigImg) {
shareImg(bitmap, listener)
} else {
send(bitmap)
}
}
})
}
inner class WeChatShareReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent!!.hasExtra(Constant.EXTRA_WEIXIN_RESULT)) {
val errCode = intent.getIntExtra(Constant.EXTRA_WEIXIN_RESULT, BaseResp.ErrCode.ERR_USER_CANCEL)
val resultCode = if (errCode == BaseResp.ErrCode.ERR_OK) Activity.RESULT_OK else Activity.RESULT_CANCELED
if (resultCode == Activity.RESULT_OK) {
if (null != listener) {
listener!!.onShare(channel!!, Constant.SHARE_STATUS_COMPLETE)
}
} else {
if (null != listener) {
listener!!.onShare(channel!!, Constant.SHARE_STATUS_FAILED)
}
}
}
}
}
companion object {
@JvmField
val THUMB_SIZE = 250
}
fun shareImg(bitmap: Bitmap?, listener: OnShareListener?) {
if (null == bitmap) {
listener?.onShare(channel!!, Constant.SHARE_STATUS_FAILED)
return
}
if (iwxapi!!.isWXAppInstalled) {
if (iwxapi!!.isWXAppSupportAPI) {
val wxMediaMessage = WXMediaMessage()
wxMediaMessage.mediaObject = WXImageObject(bitmap)
var width = bitmap.width
var height = bitmap.height
while (width * height > THUMB_SIZE * THUMB_SIZE) {
width /= 2
height /= 2
}
val thumbBmp = Bitmap.createScaledBitmap(bitmap, width, height, true)
try {
val baos = ByteArrayOutputStream()
thumbBmp.compress(Bitmap.CompressFormat.JPEG, 85, baos)
wxMediaMessage.thumbData = baos.toByteArray()
baos.close()
} catch (e: Exception) {
e.printStackTrace()
}
val req = SendMessageToWX.Req()
req.transaction = System.currentTimeMillis().toString()
req.message = wxMediaMessage
when (channel) {
Constant.SHARE_CHANNEL_WEIXIN_FRIEND -> SendMessageToWX.Req.WXSceneSession
Constant.SHARE_CHANNEL_WEIXIN_CIRCLE -> SendMessageToWX.Req.WXSceneTimeline
}
iwxapi!!.sendReq(req)
}
} else {
listener?.onShare(channel!!, Constant.SHARE_STATUS_FAILED)
}
}
} | mit | 7f3fafbbbc0813403a152232d3f6bbbd | 37.008475 | 121 | 0.565838 | 4.801392 | false | false | false | false |
importre/popular | app/src/main/kotlin/io/github/importre/popular/api/Popular.kt | 1 | 1275 | package io.github.importre.popular.api
import com.squareup.okhttp.OkHttpClient
import io.github.importre.popular.BuildConfig
import retrofit.RequestInterceptor
import retrofit.RestAdapter
import retrofit.client.OkClient
public class Popular {
companion object {
public val CLIENT_ID: String = ""
public val restAdapter: RestAdapter
public val service: PopularService
init {
val client = OkHttpClient()
val logLevel = getLogLevel()
val endPoint = "https://api.instagram.com"
val interceptor = RequestInterceptor { request ->
request.addQueryParam("client_id", CLIENT_ID)
}
restAdapter = RestAdapter.Builder()
.setEndpoint(endPoint)
.setLogLevel(logLevel)
.setRequestInterceptor(interceptor)
.setClient(OkClient(client)).build()
service = restAdapter.create<PopularService>(javaClass<PopularService>())
}
private fun getLogLevel(): RestAdapter.LogLevel {
return if (BuildConfig.DEBUG) {
RestAdapter.LogLevel.FULL
} else {
RestAdapter.LogLevel.NONE
}
}
}
}
| mit | d295a7ff0d03924f55023ef88e82a889 | 28.651163 | 85 | 0.6 | 5.448718 | false | false | false | false |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/business/browser/BrowserActivity.kt | 1 | 2347 | package me.sweetll.tucao.business.browser
import android.content.Context
import android.content.Intent
import androidx.databinding.DataBindingUtil
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import androidx.appcompat.widget.Toolbar
import me.sweetll.tucao.R
import me.sweetll.tucao.base.BaseActivity
import me.sweetll.tucao.databinding.ActivityBrowserBinding
class BrowserActivity : BaseActivity() {
lateinit var binding: ActivityBrowserBinding
companion object {
val ARG_URL = "url"
fun intentTo(context: Context, url: String) {
val intent = Intent(context, BrowserActivity::class.java)
intent.putExtra(ARG_URL, url)
context.startActivity(intent)
}
}
override fun getStatusBar(): View = binding.statusBar
override fun getToolbar(): Toolbar = binding.toolbar
override fun initView(savedInstanceState: Bundle?) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_browser)
val url: String = intent.getStringExtra(ARG_URL)
binding.webView.loadUrl(url)
binding.webView.settings.javaScriptEnabled = true
binding.webView.settings.javaScriptCanOpenWindowsAutomatically = true
binding.webView.settings.databaseEnabled = true
binding.webView.settings.domStorageEnabled = true
binding.webView.setWebViewClient(object: WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
return false
}
})
binding.webView.setWebChromeClient(object: WebChromeClient() {
override fun onReceivedTitle(view: WebView?, title: String?) {
super.onReceivedTitle(view, title)
supportActionBar?.let {
it.title = title
}
}
})
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && binding.webView.canGoBack()) {
binding.webView.goBack()
return true
}
return super.onKeyDown(keyCode, event)
}
override fun initToolbar() {
super.initToolbar()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
}
| mit | f730e7c4754b847c79bca7cb1d86fbc2 | 31.150685 | 106 | 0.671496 | 5.036481 | false | false | false | false |
dexbleeker/hamersapp | hamersapp/src/main/java/nl/ecci/hamers/ui/activities/HamersActivity.kt | 1 | 2704 | package nl.ecci.hamers.ui.activities
import android.annotation.SuppressLint
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import androidx.core.content.ContextCompat
import androidx.appcompat.app.AppCompatActivity
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import kotlinx.android.synthetic.main.element_toolbar.*
import kotlinx.android.synthetic.main.row_detailview.view.*
import kotlinx.android.synthetic.main.row_imageview.view.*
import kotlinx.android.synthetic.main.row_singleview.view.*
import nl.ecci.hamers.R
import nl.ecci.hamers.utils.Utils.toHtml
@SuppressLint("Registered")
abstract class HamersActivity : AppCompatActivity() {
var prefs: SharedPreferences? = null
var gson: Gson = GsonBuilder().setDateFormat(MainActivity.dbDF.toPattern()).create()
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
prefs = PreferenceManager.getDefaultSharedPreferences(this)
}
open fun initToolbar() {
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
fun newSingleRow(title: String, viewGroup: ViewGroup): View {
val view = layoutInflater.inflate(R.layout.row_singleview, viewGroup, false)
view.row_single_title.text = title
return view
}
fun newDetailRow(title: String, description: String?, viewGroup: ViewGroup): View {
val view = layoutInflater.inflate(R.layout.row_detailview, viewGroup, false)
view.row_detail_title.text = title
view.row_detail_description.text = description
return view
}
fun fillDetailRow(view: View, title: String, description: String?, html: Boolean = false) {
view.row_detail_title.text = title
if (html)
view.row_detail_description.text = toHtml(description)
else
view.row_detail_description.text = description
}
fun fillImageRow(view: View, title: String, description: String, imageId: Int) {
view.row_imageview_title_textview.text = title
view.row_imageview_subtitle_textview.text = description
view.row_imageview_image.setImageDrawable(ContextCompat.getDrawable(this, imageId))
}
}
| gpl-3.0 | 747d6d757861cd5658cb91bdf58226a8 | 34.578947 | 95 | 0.716346 | 4.491694 | false | false | false | false |
EasySpringBoot/picture-crawler | src/main/kotlin/com/easy/kotlin/picturecrawler/entity/Image.kt | 1 | 999 | package com.easy.kotlin.picturecrawler.entity
import java.util.*
import javax.persistence.*
@Entity
@Table(indexes = arrayOf(Index(name = "idx_category", unique = false, columnList = "category")))
class Image {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = -1
@Version
var version: Int = 0
@Column(length = 100)
var category: String = ""
var isFavorite: Int = 0
@Column(length = 255, nullable = false)
var url: String = ""
var gmtCreated: Date = Date()
var gmtModified: Date = Date()
var isDeleted: Int = 0 //1 Yes 0 No
var deletedDate: Date = Date()
@Lob
var imageBlob: ByteArray = byteArrayOf()
/* 0-Baidu 1-Gank */
var sourceType: Int = 0
override fun toString(): String {
return "Image(id=$id, version=$version, category='$category', isFavorite=$isFavorite, url='$url', gmtCreated=$gmtCreated, gmtModified=$gmtModified, isDeleted=$isDeleted, deletedDate=$deletedDate)"
}
}
| apache-2.0 | 8ec6c171486ff30803ce0e4a3f36b3f9 | 27.542857 | 204 | 0.655656 | 3.842308 | false | false | false | false |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/UselessPostfixExpressionSpec.kt | 2 | 3471 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class UselessPostfixExpressionSpec : Spek({
val subject by memoized { UselessPostfixExpression() }
describe("check several types of postfix increments") {
it("overrides the incremented integer") {
val code = """
fun f() {
var i = 0
i = i-- // invalid
i = 1 + i++ // invalid
i = i++ + 1 // invalid
}"""
assertThat(subject.compileAndLint(code)).hasSize(3)
}
it("does not override the incremented integer") {
val code = """
fun f() {
var i = 0
var j = 0
j = i++
}"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("returns no incremented value") {
val code = """
fun f(): Int {
var i = 0
var j = 0
if (i == 0) return 1 + j++
return i++
}"""
assertThat(subject.compileAndLint(code)).hasSize(2)
}
it("should not report field increments") {
val code = """
class Test {
private var runningId: Long = 0
fun increment() {
runningId++
}
fun getId(): Long {
return runningId++
}
}
class Foo(var i: Int = 0) {
fun getIdAndIncrement(): Int {
return i++
}
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("should detect properties shadowing fields that are incremented") {
val code = """
class Test {
private var runningId: Long = 0
fun getId(): Long {
var runningId: Long = 0
return runningId++
}
}
class Foo(var i: Int = 0) {
fun foo(): Int {
var i = 0
return i++
}
}
"""
assertThat(subject.compileAndLint(code)).hasSize(2)
}
}
describe("Only ++ and -- postfix operators should be considered") {
it("should not report !! in a return statement") {
val code = """
val str: String? = ""
fun f1(): String {
return str!!
}
fun f2(): Int {
return str!!.count()
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
it("should not report !! in a standalone expression") {
val code = """
fun f() {
val str: String? = ""
str!!
}
"""
assertThat(subject.compileAndLint(code)).isEmpty()
}
}
})
| apache-2.0 | 9cfde120e7b3dcb3b27be4d13f824ad4 | 28.666667 | 78 | 0.403342 | 5.643902 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/shop_type/AddShopType.kt | 1 | 1212 | package de.westnordost.streetcomplete.quests.shop_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddShopType() : OsmFilterQuestType<Boolean>() {
override val elementFilter = "nodes, ways, relations with shop=yes and !amenity and !leisure"
override val commitMessage = "Specify shop type"
override val icon = R.drawable.ic_quest_label
override fun getTitle(tags: Map<String, String>): Int {
val hasName = tags.containsKey("name") || tags.containsKey("brand")
return if (hasName) R.string.quest_shopType_name_title
else R.string.quest_shopType_title
}
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
}
override val wikiLink = "Tag:shop=yes"
override val questTypeAchievements: List<QuestTypeAchievement>
get() = listOf()
}
| gpl-3.0 | 2066b6ff5be69100a4bdb376852cad1b | 39.4 | 97 | 0.759901 | 4.643678 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/visiblequests/QuestPresetsController.kt | 1 | 1862 | package de.westnordost.streetcomplete.data.visiblequests
import java.util.concurrent.CopyOnWriteArrayList
import javax.inject.Inject
import javax.inject.Singleton
@Singleton class QuestPresetsController @Inject constructor(
private val questPresetsDao: QuestPresetsDao,
private val selectedQuestPresetStore: SelectedQuestPresetStore
): QuestPresetsSource {
private val listeners = CopyOnWriteArrayList<QuestPresetsSource.Listener>()
override var selectedId: Long
get() = selectedQuestPresetStore.get()
set(value) {
selectedQuestPresetStore.set(value)
onSelectedQuestPresetChanged()
}
override val selectedQuestPresetName: String? get() =
questPresetsDao.getName(selectedId)
fun add(presetName: String): Long {
val presetId = questPresetsDao.add(presetName)
onAddedQuestPreset(presetId, presetName)
return presetId
}
fun delete(presetId: Long) {
if (presetId == selectedId) {
selectedId = 0
}
questPresetsDao.delete(presetId)
onDeletedQuestPreset(presetId)
}
override fun getAll(): List<QuestPreset> =
questPresetsDao.getAll()
/* listeners */
override fun addListener(listener: QuestPresetsSource.Listener) {
listeners.add(listener)
}
override fun removeListener(listener: QuestPresetsSource.Listener) {
listeners.remove(listener)
}
private fun onSelectedQuestPresetChanged() {
listeners.forEach { it.onSelectedQuestPresetChanged() }
}
private fun onAddedQuestPreset(presetId: Long, presetName: String) {
listeners.forEach { it.onAddedQuestPreset(QuestPreset(presetId, presetName)) }
}
private fun onDeletedQuestPreset(presetId: Long) {
listeners.forEach { it.onDeletedQuestPreset(presetId) }
}
}
| gpl-3.0 | 26d66e5fcc2b5192e98dbe1f9c27bc37 | 31.103448 | 86 | 0.705156 | 5.073569 | false | false | false | false |
wleroux/fracturedskies | src/main/kotlin/com/fracturedskies/api/block/Block.kt | 1 | 1375 | package com.fracturedskies.api.block
import kotlin.reflect.KClass
import kotlin.reflect.full.safeCast
class Block {
val type: BlockType
private val data: Map<KClass<*>, Any?>
constructor(type: BlockType) {
this.type = type
this.data = type.supportedProperties().map { property ->
property to type.defaultValue(property)
}.toMap()
}
private constructor(type: BlockType, data: Map<KClass<*>, Any?>) {
this.type = type
this.data = data
}
fun <T: Any> has(property: KClass<T>): Boolean {
return get(property) != null
}
operator fun <T: Any> get(property: KClass<T>): T? {
return property.safeCast(this.data[property])
}
fun <T: Any> with(value: T): Block {
if (!type.supportedProperties().contains(value::class))
throw IllegalArgumentException("Block Type '$type' does not support property '${value::class.simpleName}'.")
if (value == get(value::class)) return this
return Block(type, data.toMutableMap().apply {
set(value::class, value)
})
}
fun <T: Any> without(property: KClass<T>): Block {
val defaultValue = type.defaultValue(property)
if (defaultValue == get(property)) return this
if (!has(property)) return this
return Block(type, data.toMutableMap().apply {
remove(property)
})
}
override fun toString(): String {
return type.toString()
}
}
| unlicense | b93035b36088913523cde9233a5167e3 | 28.255319 | 114 | 0.661818 | 3.884181 | false | false | false | false |
youkai-app/Youkai | app/src/main/kotlin/app/youkai/ui/common/view/ScrollAwareFabBehavior.kt | 1 | 1766 | package app.youkai.ui.common.view
import android.content.Context
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
/**
* Shows/hides FAB based on scroll.
*
* Source: http://stackoverflow.com/a/31383724/984061 (Java)
*/
class ScrollAwareFabBehavior(context: Context, attrs: AttributeSet) : FloatingActionButton.Behavior(context, attrs) {
override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton,
directTargetChild: View, target: View, nestedScrollAxes: Int): Boolean {
return nestedScrollAxes ==
ViewCompat.SCROLL_AXIS_VERTICAL
|| super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes)
}
override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton,
target: View, dxConsumed: Int, dyConsumed: Int,
dxUnconsumed: Int, dyUnconsumed: Int) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
if (dyConsumed > 0 && child.visibility == VISIBLE) {
child.hide(object : FloatingActionButton.OnVisibilityChangedListener() {
override fun onHidden(fab: FloatingActionButton?) {
fab?.visibility = INVISIBLE
}
})
} else if (dyConsumed < 0 && child.visibility != VISIBLE) {
child.show()
}
}
} | gpl-3.0 | 46446855547fb61c3635a4f995927b94 | 43.175 | 117 | 0.679502 | 5.194118 | false | false | false | false |
hubme/WorkHelperApp | app/src/test/java/com/king/app/workhelper/coroutine/CoroutineCancelAndTimeout.kt | 1 | 6657 | package com.king.app.workhelper.coroutine
import kotlinx.coroutines.*
import org.junit.Test
/**
* 协程取消和超时。
* https://www.kotlincn.net/docs/reference/coroutines/cancellation-and-timeouts.html
*
* @author VanceKing
* @since 2022/4/23
*/
class CoroutineCancelAndTimeout {
@Test
fun cancel_1() = runBlocking {
val job = launch {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
}
delay(1300L) // 延迟一段时间
println("main: I'm tired of waiting!")
job.cancel() // 取消该作业
job.join() // 等待作业执行结束
println("main: Now I can quit.")
/*output:
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
main: Now I can quit.
*/
}
@Test
fun cancel_2() = runBlocking {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 5) { // 一个执行计算的循环,只是为了占用 CPU
// 每秒打印消息两次
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
}
}
delay(1300L) // 等待一段时间
println("main: I'm tired of waiting!")
job.cancelAndJoin() // 取消一个作业并且等待它结束。但 launch 并不会立即停止,还是会持续打印
println("main: Now I can quit.")
/*output:
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
job: I'm sleeping 3 ...
job: I'm sleeping 4 ...
main: Now I can quit.
*/
}
@Test
fun cancel_2_1() = runBlocking {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (isActive) { // 可以被取消的计算循环
// 每秒打印消息两次
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
}
}
delay(1300L) // 等待一段时间
println("main: I'm tired of waiting!")
job.cancelAndJoin() // 取消一个作业并且等待它结束。
println("main: Now I can quit.")
/*output:
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
main: Now I can quit.
*/
}
@Test
fun cancel_3() = runBlocking {
val job = launch {
try {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
} finally {
println("job: I'm running finally")
}
}
delay(1300L) // 延迟一段时间
println("main: I'm tired of waiting!")
job.cancelAndJoin() // 取消该作业并且等待它结束
println("main: Now I can quit.")
/*output:
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
job: I'm running finally
main: Now I can quit.
*/
}
@Test
fun cancel_3_1() = runBlocking {
val job = launch {
try {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
} finally {
delay(1000L)
//下面一行不会打印
println("job: I'm running finally")
}
}
delay(1300L) // 延迟一段时间
println("main: I'm tired of waiting!")
job.cancelAndJoin() // 取消该作业并且等待它结束
println("main: Now I can quit.")
/*output:
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
main: Now I can quit.
*/
}
@Test
fun cancel_3_2() = runBlocking {
val job = launch {
try {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
} finally {
withContext(NonCancellable) {
println("job: I'm running finally")
delay(1000L)
println("job: And I've just delayed for 1 sec because I'm non-cancellable")
}
}
}
delay(1300L) // 延迟一段时间
println("main: I'm tired of waiting!")
job.cancelAndJoin() // 取消该作业并等待它结束
println("main: Now I can quit.")
/*output:
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
job: I'm running finally
job: And I've just delayed for 1 sec because I'm non-cancellable
main: Now I can quit.
*/
}
@Test
fun timeout_1() = runBlocking {
withTimeout(1300L) {
repeat(1000) {
println("I'm sleeping $it ...")
delay(500L)
}
}
}
@Test
fun timeout_1_1() = runBlocking {
try {
withTimeout(1300L) {
repeat(1000) {
println("I'm sleeping $it ...")
delay(500L)
}
}
} catch (e: TimeoutCancellationException) {
println("超时异常信息:$e")
}
/*
output:
I'm sleeping 0 ...
I'm sleeping 1 ...
I'm sleeping 2 ...
超时异常信息:kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1300 ms
*/
}
@Test
fun timeout_2() = runBlocking {
val result = withTimeoutOrNull(1300L) {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
"Done" // 在它运行得到结果之前取消它
}
println("Result is $result")
}
} | apache-2.0 | ea4ddd7898500cbc52c58c946da2dff1 | 26.453744 | 95 | 0.457872 | 4.238776 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/editor/ShiftTracker.kt | 1 | 1887 | package nl.hannahsten.texifyidea.editor
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import java.awt.event.KeyEvent
import java.awt.event.KeyListener
import javax.swing.JComponent
/**
* Tracks the shift key.
*
* @author Hannah Schellekens
*/
object ShiftTracker : KeyListener, TypedHandlerDelegate() {
/**
* `true` if the shift key is pressed, `false` if the shift key is not pressed.
*/
private var shift = false
/**
* Set of all components that have been tracked.
*/
private var registered: MutableSet<JComponent> = HashSet()
/**
* Setsup the shift tracker.
*/
@JvmStatic
fun setup(component: JComponent) {
if (registered.contains(component)) {
return
}
component.addKeyListener(this)
registered.add(component)
}
/**
* Checks if the shift key is pressed.
*
* @return `true` when shift is pressed, `false` when shift is not pressed.
*/
@JvmStatic
fun isShiftPressed(): Boolean = shift
override fun beforeCharTyped(c: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result {
setup(editor.contentComponent)
return super.beforeCharTyped(c, project, editor, file, fileType)
}
override fun keyTyped(e: KeyEvent?) {
// Do nothing.
}
override fun keyPressed(e: KeyEvent?) {
if (e?.keyCode == KeyEvent.VK_SHIFT) {
shift = true
}
}
override fun keyReleased(e: KeyEvent?) {
if (e?.keyCode == KeyEvent.VK_SHIFT) {
shift = false
}
}
fun unload() {
registered.forEach { it.removeKeyListener(this) }
}
} | mit | 08a82e06406c086d430a3183ea5731a0 | 24.513514 | 120 | 0.643349 | 4.318078 | false | false | false | false |
GDG-Nantes/devfest-android | app/src/main/kotlin/com/gdgnantes/devfest/android/viewmodel/FiltersViewModel.kt | 1 | 941 | package com.gdgnantes.devfest.android.viewmodel
import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.support.v4.util.ArraySet
class FiltersViewModel(application: Application) : AndroidViewModel(application) {
private val _filters: MutableLiveData<Set<Filter>> = MutableLiveData()
fun isFilter(filter: Filter) = filter in _filters.value ?: emptySet()
fun hasFilters() = !(_filters.value?.isEmpty() ?: true)
fun toggleFilter(filter: Filter) {
val newFilters = ArraySet(_filters.value)
if (isFilter(filter)) {
newFilters.remove(filter)
} else {
newFilters.add(filter)
}
_filters.value = newFilters
}
fun clear() {
_filters.value = emptySet()
}
val filters: LiveData<Set<Filter>>
get() = _filters
} | apache-2.0 | 554652cf07ffc69cd2c9188f4303d0a4 | 25.914286 | 82 | 0.68119 | 4.277273 | false | false | false | false |
colriot/anko | dsl/testData/functional/gridlayout-v7/LayoutsTest.kt | 2 | 2511 | private val defaultInit: Any.() -> Unit = {}
open class _GridLayout(ctx: Context): android.support.v7.widget.GridLayout(ctx) {
fun <T: View> T.lparams(
rowSpec: android.support.v7.widget.GridLayout.Spec?,
columnSpec: android.support.v7.widget.GridLayout.Spec?,
init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.GridLayout.LayoutParams(rowSpec!!, columnSpec!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
fun <T: View> T.lparams(
init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.GridLayout.LayoutParams()
layoutParams.init()
[email protected] = layoutParams
return this
}
fun <T: View> T.lparams(
params: android.view.ViewGroup.LayoutParams?,
init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.GridLayout.LayoutParams(params!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
fun <T: View> T.lparams(
params: android.view.ViewGroup.MarginLayoutParams?,
init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.GridLayout.LayoutParams(params!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
fun <T: View> T.lparams(
source: android.support.v7.widget.GridLayout.LayoutParams?,
init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.GridLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
fun <T: View> T.lparams(
context: android.content.Context?,
attrs: android.util.AttributeSet?,
init: android.support.v7.widget.GridLayout.LayoutParams.() -> Unit = defaultInit
): T {
val layoutParams = android.support.v7.widget.GridLayout.LayoutParams(context!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
} | apache-2.0 | f2ee85a970a5e019175f1532a4a468fd | 37.646154 | 101 | 0.643568 | 4.428571 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/filesystem/ftp/NetCopyClientUtils.kt | 1 | 10627 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.filesystem.ftp
import androidx.annotation.VisibleForTesting
import androidx.annotation.WorkerThread
import com.amaze.filemanager.application.AppConfig
import com.amaze.filemanager.fileoperations.filesystem.DOESNT_EXIST
import com.amaze.filemanager.fileoperations.filesystem.FolderState
import com.amaze.filemanager.fileoperations.filesystem.WRITABLE_ON_REMOTE
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.AT
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.COLON
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.SLASH
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.SSH_URI_PREFIX
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.getConnection
import com.amaze.filemanager.filesystem.ssh.SFtpClientTemplate
import com.amaze.filemanager.utils.SmbUtil
import io.reactivex.Maybe
import io.reactivex.Scheduler
import io.reactivex.schedulers.Schedulers
import net.schmizz.sshj.sftp.SFTPClient
import org.apache.commons.net.ftp.FTPClient
import org.apache.commons.net.ftp.FTPReply
import org.slf4j.LoggerFactory
import java.io.IOException
import java.net.URLDecoder
import java.security.GeneralSecurityException
import java.security.KeyPair
object NetCopyClientUtils {
@JvmStatic
private val LOG = LoggerFactory.getLogger(NetCopyClientUtils::class.java)
/**
* Lambda to determine the [Scheduler] to use.
* Default is [Schedulers.io] while [Schedulers.single] is used when thread safety is required.
*/
@JvmStatic
var getScheduler: (NetCopyClient<*>) -> Scheduler = {
if (it.isRequireThreadSafety()) {
Schedulers.single()
} else {
Schedulers.io()
}
}
// Allow test cases to override the Scheduler to use, or deadlocks will occur
// because tests are run in parallel
@VisibleForTesting set
/**
* Execute the given NetCopyClientTemplate.
*
* This template pattern is borrowed from Spring Framework, to simplify code on operations
* using SftpClientTemplate.
*
* @param template [NetCopyClientTemplate] to execute
* @param <T> Type of return value
* @return Template execution results
*/
@WorkerThread
fun <ClientType, T> execute(
template: NetCopyClientTemplate<ClientType, T>
): T? {
var client = getConnection<ClientType>(extractBaseUriFrom(template.url))
if (client == null) {
client = getConnection(template.url)
}
var retval: T? = null
if (client != null) {
retval = runCatching {
Maybe.fromCallable {
template.execute(client)
}.subscribeOn(getScheduler.invoke(client)).blockingGet()
}.onFailure {
LOG.error("Error executing template method", it)
}.also {
if (template.closeClientOnFinish) {
tryDisconnect(client)
}
}.getOrNull()
}
return retval
}
/**
* Convenience method to call [SmbUtil.getSmbEncryptedPath] if the given
* SSH URL contains the password (assuming the password is encrypted).
*
* @param fullUri SSH URL
* @return SSH URL with the password (if exists) encrypted
*/
fun encryptFtpPathAsNecessary(fullUri: String): String {
val prefix = fullUri.substring(0, fullUri.indexOf("://") + 3)
val uriWithoutProtocol: String = fullUri.substring(prefix.length)
return if (uriWithoutProtocol.substringBefore(AT).indexOf(COLON) > 0) {
SmbUtil.getSmbEncryptedPath(
AppConfig.getInstance(),
fullUri
).replace("\n", "")
} else {
fullUri
}
}
/**
* Convenience method to call [SmbUtil.getSmbDecryptedPath] if the given
* SSH URL contains the password (assuming the password is encrypted).
*
* @param fullUri SSH URL
* @return SSH URL with the password (if exists) decrypted
*/
fun decryptFtpPathAsNecessary(fullUri: String): String? {
val prefix = fullUri.substring(0, fullUri.indexOf("://") + 3)
val uriWithoutProtocol: String = fullUri.substring(prefix.length)
return try {
if (uriWithoutProtocol.lastIndexOf(COLON) > 0) SmbUtil.getSmbDecryptedPath(
AppConfig.getInstance(),
fullUri
) else fullUri
} catch (e: IOException) {
LOG.error("Error decrypting path", e)
fullUri
} catch (e: GeneralSecurityException) {
LOG.error("Error decrypting path", e)
fullUri
}
}
/**
* Convenience method to extract the Base URL from the given SSH URL.
*
*
* For example, given `ssh://user:[email protected]:22/home/user/foo/bar`, this
* method returns `ssh://user:[email protected]:22`.
*
* @param fullUri Full SSH URL
* @return The remote path part of the full SSH URL
*/
fun extractBaseUriFrom(fullUri: String): String {
val prefix = fullUri.substring(0, fullUri.indexOf("://") + 3)
val uriWithoutProtocol: String = fullUri.substring(prefix.length)
val credentials: String
val hostAndPath: String
if (uriWithoutProtocol.contains(AT)) {
credentials = uriWithoutProtocol.substring(0, uriWithoutProtocol.lastIndexOf(AT))
hostAndPath = uriWithoutProtocol.substring(uriWithoutProtocol.lastIndexOf(AT) + 1)
} else {
credentials = ""
hostAndPath = uriWithoutProtocol
}
return if (hostAndPath.indexOf(SLASH) == -1) {
fullUri
} else {
val host = hostAndPath.substring(0, hostAndPath.indexOf(SLASH))
val credentialsLen = if (credentials == "") {
0
} else {
credentials.length + 1
}
fullUri.substring(
0,
prefix.length + credentialsLen + host.length
)
}
}
/**
* Convenience method to extract the remote path from the given SSH URL.
*
*
* For example, given `ssh://user:[email protected]:22/home/user/foo/bar`, this
* method returns `/home/user/foo/bar`.
*
* @param fullUri Full SSH URL
* @return The remote path part of the full SSH URL
*/
fun extractRemotePathFrom(fullUri: String): String {
if (fullUri.contains(AT)) {
val hostPath = fullUri.substring(fullUri.lastIndexOf(AT))
return if (hostPath.indexOf(SLASH) == -1) {
SLASH.toString()
} else {
URLDecoder.decode(
hostPath.substring(hostPath.indexOf(SLASH)),
Charsets.UTF_8.name()
)
}
} else {
val hostAndPath = fullUri.substringAfter("://")
return if (hostAndPath.contains(SLASH)) {
hostAndPath.substring(hostAndPath.indexOf(SLASH))
} else {
SLASH.toString()
}
}
}
/**
* Disconnects the given [NetCopyClient] but wrap all exceptions beneath, so callers are free
* from the hassles of handling thrown exceptions.
*
* @param client [NetCopyClient] instance
*/
private fun tryDisconnect(client: NetCopyClient<*>) {
if (client.isConnectionValid()) {
client.expire()
}
}
/**
* Decide the SSH URL depends on password/selected KeyPair.
*/
@Suppress("LongParameterList")
fun deriveUriFrom(
prefix: String,
hostname: String,
port: Int,
defaultPath: String? = null,
username: String,
password: String? = null,
selectedParsedKeyPair: KeyPair? = null
): String {
// FIXME: should be caller's responsibility
var pathSuffix = defaultPath
if (pathSuffix == null) pathSuffix = SLASH.toString()
return if (selectedParsedKeyPair != null) {
"$prefix$username@$hostname:$port$pathSuffix"
} else if (username == "" && (password == "" || password == null)) {
"$prefix$hostname:$port$pathSuffix"
} else {
"$prefix$username:$password@$hostname:$port$pathSuffix"
}
}
/**
* Check folder existence on remote.
*/
@FolderState
fun checkFolder(path: String): Int {
val template: NetCopyClientTemplate<*, Int> = if (path.startsWith(SSH_URI_PREFIX)) {
object : SFtpClientTemplate<Int>(extractBaseUriFrom(path), false) {
@FolderState
@Throws(IOException::class)
override fun execute(client: SFTPClient): Int {
return if (client.statExistence(extractRemotePathFrom(path)) == null) {
WRITABLE_ON_REMOTE
} else {
DOESNT_EXIST
}
}
}
} else {
object : FtpClientTemplate<Int>(extractBaseUriFrom(path), false) {
override fun executeWithFtpClient(ftpClient: FTPClient): Int {
return if (ftpClient.stat(extractRemotePathFrom(path))
== FTPReply.DIRECTORY_STATUS
) {
WRITABLE_ON_REMOTE
} else {
DOESNT_EXIST
}
}
}
}
return execute(template) ?: DOESNT_EXIST
}
}
| gpl-3.0 | 602d8f16a28c6e58cceb893209e9619d | 36.157343 | 107 | 0.614284 | 4.516362 | false | false | false | false |
jonalmeida/focus-android | app/src/main/java/org/mozilla/focus/fragment/CrashReporterFragment.kt | 1 | 1439 | /* 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 org.mozilla.focus.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_crash_reporter.*
import org.mozilla.focus.R
import org.mozilla.focus.telemetry.TelemetryWrapper
class CrashReporterFragment : Fragment() {
var onCloseTabPressed: ((sendCrashReport: Boolean) -> Unit)? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_crash_reporter, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
TelemetryWrapper.crashReporterOpened()
closeTabButton.setOnClickListener {
val wantsSubmitCrashReport = sendCrashCheckbox.isChecked
TelemetryWrapper.closeTabButtonTapped(wantsSubmitCrashReport)
onCloseTabPressed?.invoke(wantsSubmitCrashReport)
}
}
companion object {
val FRAGMENT_TAG = "crash-reporter"
fun create() = CrashReporterFragment()
}
}
| mpl-2.0 | 4e0dc497e2e68e732fd3f41b6ff6de12 | 32.465116 | 83 | 0.729673 | 4.612179 | false | false | false | false |
renard314/textfairy | app/src/main/java/com/renard/ocr/main_menu/language/LanguageListViewModel.kt | 1 | 5222 | package com.renard.ocr.main_menu.language
import android.app.Application
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations.map
import androidx.lifecycle.Transformations.switchMap
import androidx.lifecycle.viewModelScope
import com.renard.ocr.R
import com.renard.ocr.TextFairyApplication
import com.renard.ocr.main_menu.language.OcrLanguageDataStore.deleteLanguage
import com.renard.ocr.main_menu.language.OcrLanguageDataStore.getInstallStatusFor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class LanguageListViewModel(application: Application) : AndroidViewModel(application) {
private val mDownloadReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val lang = intent.getStringExtra(DownloadBroadCastReceiver.EXTRA_OCR_LANGUAGE)!!
val status = intent.getIntExtra(DownloadBroadCastReceiver.EXTRA_STATUS, -1)
updateLanguageList(lang, status)
}
}
private var mFailedReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val lang = intent.getStringExtra(DownloadBroadCastReceiver.EXTRA_OCR_LANGUAGE)!!
val status = intent.getIntExtra(DownloadBroadCastReceiver.EXTRA_STATUS, -1)
updateLanguageList(lang, status)
}
}
enum class LoadingState {
LOADING, LOADED
}
private val _loading = MutableLiveData<LoadingState>()
val loading: LiveData<LoadingState>
get() = _loading
private val _query = MutableLiveData<String>()
private val _data = MutableLiveData<List<OcrLanguage>>()
val data: LiveData<List<OcrLanguage>>
get() = switchMap(_query) { query ->
if (query.isNullOrBlank()) {
_data
} else {
map(_data) {
it.filter { lang ->
lang.displayText.contains(query, ignoreCase = true)
}
}
}
}
init {
viewModelScope.launch(Dispatchers.IO) {
_loading.postValue(LoadingState.LOADING)
val allOcrLanguages = OcrLanguageDataStore.getAllOcrLanguages(getApplication())
_data.postValue(allOcrLanguages)
_query.postValue("")
_loading.postValue(LoadingState.LOADED)
}
application.registerReceiver(mFailedReceiver, IntentFilter(DownloadBroadCastReceiver.ACTION_INSTALL_FAILED))
application.registerReceiver(mDownloadReceiver, IntentFilter(DownloadBroadCastReceiver.ACTION_INSTALL_COMPLETED))
}
override fun onCleared() {
getApplication<Application>().run {
unregisterReceiver(mDownloadReceiver)
unregisterReceiver(mFailedReceiver)
}
}
fun deleteLanguage(language: OcrLanguage) {
getApplication<TextFairyApplication>().analytics.sendDeleteLanguage(language)
updateLanguage(language) { deleteLanguage(it, getApplication()) }
}
fun startDownload(language: OcrLanguage) {
val application = getApplication<TextFairyApplication>()
application.analytics.sendStartDownload(language)
language.installLanguage(application)
updateLanguage(language) { it.copy(isDownloading = true) }
}
private fun updateLanguageList(lang: String, status: Int) {
updateLanguage(lang) {
when (status) {
DownloadManager.STATUS_SUCCESSFUL -> {
val installStatus = getInstallStatusFor(it.value, getApplication())
it.copy(isDownloading = false, installStatus = installStatus)
}
DownloadManager.STATUS_FAILED -> {
Toast.makeText(
getApplication(),
String.format(
getApplication<Application>().getString(R.string.download_failed),
it.displayText
),
Toast.LENGTH_LONG
).show()
it.copy(isDownloading = false)
}
else -> it
}
}
}
private fun updateLanguage(language: OcrLanguage, update: (OcrLanguage) -> OcrLanguage) {
updateLanguage(language.value, update)
}
private fun updateLanguage(language: String, update: (OcrLanguage) -> OcrLanguage) {
val find = _data.value?.indexOfFirst { it.value == language } ?: -1
if (find != -1) {
val mutableList = _data.value as MutableList
mutableList[find] = update(mutableList[find])
_data.value = _data.value
_query.value = _query.value
}
}
fun filter(query: String) {
_query.value = query
}
} | apache-2.0 | a09d823ce6cc3a572299e19558649195 | 37.404412 | 121 | 0.641325 | 5.079767 | false | false | false | false |
SrirangaDigital/shankara-android | app/src/main/java/co/ideaportal/srirangadigital/shankaraandroid/home/MainActivity.kt | 1 | 4404 | package co.ideaportal.srirangadigital.shankaraandroid.home
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import androidx.viewpager.widget.ViewPager
import co.ideaportal.srirangadigital.shankaraandroid.BaseActivity
import co.ideaportal.srirangadigital.shankaraandroid.DialogCallback
import co.ideaportal.srirangadigital.shankaraandroid.R
import co.ideaportal.srirangadigital.shankaraandroid.db.BookActivityCallback
import co.ideaportal.srirangadigital.shankaraandroid.db.Datasource
import co.ideaportal.srirangadigital.shankaraandroid.db.OpenHelperManager
import co.ideaportal.srirangadigital.shankaraandroid.home.bindings.MainAdapter
import co.ideaportal.srirangadigital.shankaraandroid.home.db.TableControllerRecentBooks
import co.ideaportal.srirangadigital.shankaraandroid.home.rowdata.RecentBookObject
import co.ideaportal.srirangadigital.shankaraandroid.model.Link
import co.ideaportal.srirangadigital.shankaraandroid.search.SearchFragment
import co.ideaportal.srirangadigital.shankaraandroid.util.Utils
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.collections.ArrayList
class MainActivity : BaseActivity(),BookActivityCallback {
companion object {
lateinit var mutableList: MutableList<RecentBookObject>
lateinit var recentBookLinks : ArrayList<Link>
}
private lateinit var mainAdapter: MainAdapter
protected var dataSourceValue: Datasource? = null
private var backPressCount = 0;
private var pos = 0;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initViews()
}
private fun initViews() {
dataSourceValue = OpenHelperManager.getDataSource(this)
readRecentBookData()
mainAdapter = MainAdapter(supportFragmentManager,this@MainActivity)
vpPages.adapter = mainAdapter
val searchFragment = mainAdapter.getItem(3) as SearchFragment
tabNavigation.setupWithViewPager(vpPages)
// Iterate over all tabs and set the custom view
for (i in 0 until tabNavigation.tabCount) {
val tab = tabNavigation.getTabAt(i)
tab?.customView = getTabView(i)
}
vpPages.addOnPageChangeListener(object: ViewPager.OnPageChangeListener{
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
pos = position;
if(position!=3){
mainAdapter.clearSearch()
}
}
})
}
private fun readRecentBookData() {
mutableList = TableControllerRecentBooks(this).read()
recentBookLinks = ArrayList()
for (recentBookObject in MainActivity.mutableList){
recentBookLinks.add(dataSource.getLink(recentBookObject.id))
}
}
override fun getDataSource(): Datasource? {
return dataSourceValue
}
override fun currentLanguage(): String {
return preference
}
private fun getTabView(position :Int) : View{
val imageResId = intArrayOf(R.drawable.ic_home, R.drawable.ic_book,R.drawable.ic_bookmark,R.drawable.ic_search)
val view = LayoutInflater.from(this@MainActivity).inflate(R.layout.item_tabs,null)
val imageView = view.findViewById<ImageView>(R.id.ivTab)
imageView.setImageResource(imageResId[position])
return view
}
override fun onBackPressed() {
if(backPressCount==0 && pos!=0) {
backPressCount++;
vpPages.setCurrentItem(0, true);
}
else {
Utils.showDialog("Are you sure you want to exit?",this,"Alert!") {
backPressCount = 0
super.onBackPressed()
}
}
}
override fun closeDrawer() {
}
override fun updateBookMarkMenu(isShow: Boolean) {
}
override fun updatePageNumber(pageNo: String?) {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
readRecentBookData()
}
}
| gpl-2.0 | 463d99d3b094fa9886a49fdaa1300a83 | 31.382353 | 119 | 0.702543 | 4.942761 | false | false | false | false |
nemerosa/ontrack | buildSrc/src/main/kotlin/net/nemerosa/ontrack/gradle/RemoteAcceptanceTest.kt | 1 | 1630 | package net.nemerosa.ontrack.gradle
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
/**
* Launching acceptance tests
*/
open class RemoteAcceptanceTest : DefaultTask() {
@Input
var disableSsl = false
@Input
var acceptanceContext = "all"
@Input
var acceptanceJar = project.properties["acceptanceJar"] as String
@Input
var acceptanceUrl: String = "http://localhost:8080"
@Input
var acceptanceUrlFn: (() -> String)? = null
@Input
var acceptancePassword = "admin"
@Input
var acceptanceTimeout = 120
@Input
var acceptanceImplicitWait = 5
@TaskAction
fun launch() {
// URL
val url = when {
acceptanceUrlFn != null -> acceptanceUrlFn!!()
else -> acceptanceUrl
}
// Logging
logger.info("Acceptance library at $acceptanceJar")
logger.info("Application at $url")
// Running the tests
project.exec {
workingDir(project.projectDir)
executable("java")
args = listOf(
"-jar",
acceptanceJar,
"--ontrack.acceptance.url=$url",
"--ontrack.acceptance.admin=$acceptancePassword",
"--ontrack.acceptance.disable-ssl=$disableSsl",
"--ontrack.acceptance.context=$acceptanceContext",
"--ontrack.acceptance.timeout=$acceptanceTimeout",
"--ontrack.acceptance.implicit-wait=$acceptanceImplicitWait"
)
}
}
} | mit | 94893b8647187e3307b953a03604e38c | 25.306452 | 80 | 0.580368 | 4.88024 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/widget/WidgetRollerShutterFactory.kt | 1 | 2403 | package treehou.se.habit.ui.widget
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import se.treehou.ng.ohcommunicator.connector.models.OHLinkedPage
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import se.treehou.ng.ohcommunicator.connector.models.OHWidget
import se.treehou.ng.ohcommunicator.services.IServerHandler
import treehou.se.habit.R
import treehou.se.habit.connector.Constants
import treehou.se.habit.ui.adapter.WidgetAdapter
import treehou.se.habit.util.logging.Logger
import javax.inject.Inject
class WidgetRollerShutterFactory @Inject constructor() : WidgetFactory {
@Inject lateinit var logger: Logger
@Inject lateinit var server: OHServer
@Inject lateinit var page: OHLinkedPage
@Inject lateinit var serverHandler: IServerHandler
override fun createViewHolder(parent: ViewGroup): WidgetAdapter.WidgetViewHolder {
val context = parent.context
val view = LayoutInflater.from(context).inflate(R.layout.widget_roller_shutter, parent, false)
return RollerShutterWidgetViewHolder(view)
}
inner class RollerShutterWidgetViewHolder(view: View) : WidgetBaseHolder(view, server, page) {
val rollershutterButtonUp: ImageView = itemView.findViewById(R.id.rollerShutterButtonUp)
val rollershutterButtonStop: ImageView = itemView.findViewById(R.id.rollerShutterButtonStop)
val rollershutterButtonDown: ImageView = itemView.findViewById(R.id.rollerShutterButtonDown)
init {
setupClickListener()
}
private fun setupClickListener() {
rollershutterButtonUp.setOnClickListener {
if (widget.item != null) {
serverHandler.sendCommand(widget.item.name, Constants.COMMAND_UP)
}
}
rollershutterButtonStop.setOnClickListener {
if (widget.item != null) {
serverHandler.sendCommand(widget.item.getName(), Constants.COMMAND_STOP)
}
}
rollershutterButtonDown.setOnClickListener {
if (widget.item != null) {
serverHandler.sendCommand(widget.item.getName(), Constants.COMMAND_DOWN)
}
}
}
}
companion object {
const val TAG = "WidgetSwitchFactory"
}
} | epl-1.0 | 0be1d09b02228544373a21a546054de9 | 36.5625 | 102 | 0.699126 | 4.621154 | false | false | false | false |
RuntimeModels/chazm | chazm-model/src/main/kotlin/runtimemodels/chazm/model/entity/SpecificationGoalEvent.kt | 2 | 1287 | package runtimemodels.chazm.model.entity
import runtimemodels.chazm.api.entity.SpecificationGoal
import runtimemodels.chazm.api.entity.SpecificationGoalId
import runtimemodels.chazm.api.id.UniqueId
import runtimemodels.chazm.model.event.AbstractEvent
import runtimemodels.chazm.model.event.EventType
import runtimemodels.chazm.model.message.M
import java.util.*
import javax.inject.Inject
/**
* The [SpecificationGoalEvent] class indicates that there is an update about an [SpecificationGoal].
*
* @author Christopher Zhong
* @since 7.0.0
*/
open class SpecificationGoalEvent @Inject internal constructor(
category: EventType,
goal: SpecificationGoal
) : AbstractEvent(category) {
/**
* Returns a [UniqueId] that represents a [SpecificationGoal].
*
* @return a [UniqueId].
*/
val id: SpecificationGoalId = goal.id
override fun equals(other: Any?): Boolean {
if (other is SpecificationGoalEvent) {
return super.equals(other) && id == other.id
}
return false
}
override fun hashCode(): Int = Objects.hash(category, id)
override fun toString(): String = M.EVENT_WITH_1_ID[super.toString(), id]
companion object {
private const val serialVersionUID = 602095857291387756L
}
}
| apache-2.0 | e657ad18795517b1aad0730e3a93b793 | 28.25 | 101 | 0.718726 | 4.29 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/utils/ContentResolverUtil.kt | 1 | 3541 | /*
* Copyright (c) 2020 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.utils
import android.content.ContentResolver
import android.database.sqlite.SQLiteException
import android.net.Uri
import android.provider.MediaStore
import android.webkit.MimeTypeMap
import androidx.annotation.CheckResult
import timber.log.Timber
import java.io.File
import java.lang.Exception
import java.lang.IllegalStateException
import java.util.*
object ContentResolverUtil {
/** Obtains the filename from the url. Throws if all methods return exception */
@JvmStatic
@CheckResult
fun getFileName(contentResolver: ContentResolver, uri: Uri): String {
try {
val filename = getFilenameViaDisplayName(contentResolver, uri)
if (filename != null) {
return filename
}
} catch (e: Exception) {
Timber.w(e, "getFilenameViaDisplayName")
}
// let this one throw
val filename = getFilenameViaMimeType(contentResolver, uri)
if (filename != null) {
return filename
}
throw IllegalStateException(String.format("Unable to obtain valid filename from uri: %s", uri))
}
@CheckResult
private fun getFilenameViaMimeType(contentResolver: ContentResolver, uri: Uri): String? {
// value: "png" when testing
var extension: String? = null
// Check uri format to avoid null
if (uri.scheme != null && uri.scheme == ContentResolver.SCHEME_CONTENT) {
// If scheme is a content
val mime = MimeTypeMap.getSingleton()
extension = mime.getExtensionFromMimeType(contentResolver.getType(uri))
} else {
// If scheme is a File
// This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
if (uri.path != null) {
extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(File(uri.path as String)).toString().lowercase(Locale.ROOT))
}
}
return if (extension == null) {
null
} else "image.$extension"
}
@CheckResult
private fun getFilenameViaDisplayName(contentResolver: ContentResolver, uri: Uri): String? {
// 7748: android.database.sqlite.SQLiteException: no such column: _display_name (code 1 SQLITE_ERROR[1]): ...
try {
contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null).use { c ->
if (c != null) {
c.moveToNext()
return c.getString(0)
}
}
} catch (e: SQLiteException) {
Timber.w(e, "getFilenameViaDisplayName ContentResolver query failed.")
}
return null
}
}
| gpl-3.0 | a37457e3d344beb8be939e2d87f431eb | 38.786517 | 176 | 0.655182 | 4.634817 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/TextInputDialog.kt | 1 | 2917 | package org.wikipedia.views
import android.content.Context
import android.content.DialogInterface
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.core.widget.doOnTextChanged
import org.wikipedia.R
import org.wikipedia.databinding.DialogTextInputBinding
class TextInputDialog constructor(context: Context) : AlertDialog(context) {
interface Callback {
fun onShow(dialog: TextInputDialog)
fun onTextChanged(text: CharSequence, dialog: TextInputDialog)
fun onSuccess(text: CharSequence, secondaryText: CharSequence)
fun onCancel()
}
private var binding = DialogTextInputBinding.inflate(LayoutInflater.from(context))
private lateinit var watcher: TextWatcher
var callback: Callback? = null
init {
setView(binding.root)
binding.textInputContainer.isErrorEnabled = true
setButton(BUTTON_POSITIVE, context.getString(R.string.text_input_dialog_ok_button_text)) { _: DialogInterface, _: Int ->
callback?.onSuccess(binding.textInput.text.toString(), binding.secondaryTextInput.text.toString())
}
setButton(BUTTON_NEGATIVE, context.getString(R.string.text_input_dialog_cancel_button_text)) { _: DialogInterface, _: Int ->
callback?.onCancel()
}
setOnShowListener {
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
callback?.onShow(this@TextInputDialog)
}
}
fun setText(text: CharSequence?, select: Boolean) {
binding.textInput.setText(text)
if (select) {
binding.textInput.selectAll()
}
}
fun setSecondaryText(text: CharSequence?) {
binding.secondaryTextInput.setText(text)
}
fun showSecondaryText(show: Boolean): TextInputDialog {
binding.secondaryTextInputContainer.visibility = if (show) View.VISIBLE else View.GONE
return this
}
fun setHint(@StringRes id: Int) {
binding.textInput.hint = context.resources.getString(id)
}
fun setSecondaryHint(@StringRes id: Int) {
binding.secondaryTextInputContainer.hint = context.resources.getString(id)
}
fun setError(text: CharSequence?) {
binding.textInputContainer.error = text
}
fun setPositiveButtonEnabled(enabled: Boolean) {
getButton(BUTTON_POSITIVE).isEnabled = enabled
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
watcher = binding.textInput.doOnTextChanged { text, _, _, _ ->
callback?.onTextChanged(text ?: "", this)
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
binding.textInput.removeTextChangedListener(watcher)
}
}
| apache-2.0 | 89f0b1012217ac5b1dac4099eec07b2f | 33.317647 | 132 | 0.699691 | 4.837479 | false | false | false | false |
congwiny/KotlinBasic | src/main/kotlin/operator/overloading/DelegatedProperties02.kt | 1 | 3246 | package operator.overloading
import java.beans.PropertyChangeListener
import java.beans.PropertyChangeSupport
import kotlin.properties.Delegates
import kotlin.reflect.KProperty
/**
* Reusing property accessor logic: Delegated Properties
* 重用属性访问的逻辑:委托属性
**/
fun main(args: Array<String>) {
val p = People("congwiny", 28, 2000)
p.addPropertyChangeListener(PropertyChangeListener { event ->
println("Property ${event.propertyName} changed " +
"from ${event.oldValue} to ${event.newValue}")
})
p.age = 29
p.salary = 3000
//---------------------
val p2 = People2("congwiny", 29, 3000)
p2.addPropertyChangeListener(PropertyChangeListener { event ->
println("Property ${event.propertyName} changed " +
"from ${event.oldValue} to ${event.newValue}")
})
p2.age = 30
p2.salary = 4000
}
class People2(
val name: String, age: Int, salary: Int
) : PropertyChangeAware() {
private val observer = { prop: KProperty<*>, oldValue: Int, newValue: Int ->
changeSupport.firePropertyChange(prop.name, oldValue, newValue)
}
/**
* 你不用手动去实现可观察的属性逻辑,可以使用Kotlin 标准库,
* 它已经包含了类似于ObservableProperty的类
*/
var age: Int by Delegates.observable(age, observer) //使用Delegates.observable来实现属性修改的通知
var salary: Int by Delegates.observable(salary, observer)
}
class People(
val name: String, age: Int, salary: Int
) : PropertyChangeAware() {
/**
* 通过关键字by, Kotlin编译器会自动执行之前版本的代码中手动完成的操作。
*
* by 右边的表达式不一定是新创建的实例,也可以是函数调用、另一个属性或
* 任何其他表达式,只要这个表达式的值,是能够被编译器用正确的参数类型来调用getValue和setValue的对象。
*
* 与其他约定一样,getValue和setValue可以是对象自己声明的方法或扩展函数。
*
* 这里只展示了如何使用类型为Int 的委托属性。委托属性机制其实是通用的,适用于任何其他类型。
*/
var age: Int by ObservableProperty(age, changeSupport)
var salary: Int by ObservableProperty(salary, changeSupport)
}
/**
* 见识Kotlin 委托属性的神奇了。来看看代码变短多少?
*/
class ObservableProperty(
var propValue: Int, val changeSupport: PropertyChangeSupport
) {
/**
* 1.按照约定的需要,getValue和setValue函数被标记了operator。
*
* 2.这些函数加了两个参数: 一个用于接收属性的实例,用来设置或读取属性,
* 另一个用于表示属性本身。这个属性类型为KProperty。
*
* 3.把name属性从主构造方法中删除了,因为现在已经可以通过KProperty访问属性名称。
**/
operator fun getValue(p: People, prop: KProperty<*>): Int = propValue
operator fun setValue(p: People, prop: KProperty<*>, newValue: Int) {
val oldValue = propValue
propValue = newValue
changeSupport.firePropertyChange(prop.name, oldValue, newValue)
}
} | apache-2.0 | a6ec072b27791fc33fd9b47c5b37a2d2 | 28.183908 | 90 | 0.674153 | 3.486264 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/LiveEventEmbedProperties.kt | 1 | 621 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* LiveEvent embed properties data.
*
* @param width The width used to generate the fixed HTML embed code.
* @param height The height used to generate the fixed HTML embed code.
* @param sourceUri The source URL used to generate the fixed HTML embed code.
*/
@JsonClass(generateAdapter = true)
data class LiveEventEmbedProperties(
@Json(name = "width")
val width: Long? = null,
@Json(name = "height")
val height: Long? = null,
@Json(name = "source_url")
val sourceUri: String? = null
)
| mit | 689e0535237a00ff8fec11cc4c33ea2f | 24.875 | 78 | 0.708535 | 3.786585 | false | false | false | false |
AndroidX/androidx | constraintlayout/constraintlayout-compose/integration-tests/macrobenchmark-target/src/main/java/androidx/constraintlayout/compose/integration/macrobenchmark/target/common/components/SearchBar.kt | 3 | 3841 | /*
* 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
*
* 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.constraintlayout.compose.integration.macrobenchmark.target.common.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Preview
@Composable
private fun SearchBarPreview() {
Column(
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
SearchBar(Modifier.fillMaxWidth())
OutlinedSearchBar(Modifier.fillMaxWidth())
}
}
@Composable
fun SearchBar(
modifier: Modifier = Modifier,
backgroundColor: Color = Color.LightGray
) {
CommonSearchBar(
modifier = modifier,
outlined = false,
borderOrBackgroundColor = backgroundColor
)
}
@Composable
fun OutlinedSearchBar(
modifier: Modifier = Modifier,
borderColor: Color = Color.LightGray
) {
CommonSearchBar(
modifier = modifier,
outlined = true,
borderOrBackgroundColor = borderColor
)
}
@Composable
private fun CommonSearchBar(
modifier: Modifier,
outlined: Boolean,
borderOrBackgroundColor: Color
) {
var placeholder: String by remember { mutableStateOf("Search...") }
val backgroundModifier = if (outlined) {
Modifier.border(BorderStroke(2.dp, borderOrBackgroundColor), RoundedCornerShape(32.dp))
} else {
Modifier.background(borderOrBackgroundColor, RoundedCornerShape(32.dp))
}
OutlinedTextField(
modifier = modifier
.then(backgroundModifier)
.onFocusChanged {
placeholder = if (it.isFocused) {
"I'm not implemented yet!"
} else {
"Search..."
}
},
value = "",
onValueChange = { _ ->
},
placeholder = {
Text(text = placeholder, maxLines = 1, overflow = TextOverflow.Clip)
},
trailingIcon = {
Icon(imageVector = Icons.Default.Search, contentDescription = null)
},
singleLine = true,
colors = TextFieldDefaults.textFieldColors(
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
backgroundColor = Color.Transparent,
)
)
} | apache-2.0 | cc6cc22c4b661b1d9b7410201be09848 | 31.837607 | 95 | 0.712835 | 4.771429 | false | false | false | false |
lnds/9d9l | desafio4/kotlin/src/main/kotlin/huffman/HuffTree.kt | 1 | 2652 | package huffman
val maxSymbols = 256
/**
* Build HuffmanTree from frequency table of symbols
* Created by ediaz on 5/21/17.
*/
abstract class HuffTree(val frequency : Int)
class HuffLeaf(frequency: Int, val symbol: Char) : HuffTree(frequency) {
fun symbolIndex(): Int = symbol.toInt() and 0xFFFF
}
class HuffNode(val left: HuffTree, val right: HuffTree) : HuffTree(left.frequency+right.frequency)
class HuffHeap {
var heap = arrayOfNulls<HuffTree>(maxSymbols+1)
var last = 0
fun insert(tree:HuffTree) {
if (full()) {
throw ArrayIndexOutOfBoundsException()
}
last++
heap[last] = tree
var j = last
while (j > 1){
if (heap[j]!!.frequency < heap[j/2]!!.frequency) {
val tmp = heap[j]!!
heap[j] = heap[j / 2]!!
heap[j / 2] = tmp
}
j /= 2
}
}
fun full() = last == maxSymbols
fun empty() = last == 0
fun size() = last
fun extract() : HuffTree {
if (empty()) {
throw ArrayIndexOutOfBoundsException()
}
val min = heap[1]!!
heap[1] = heap[last]
last--
var j = 1
while (2*j <= last) {
var k = 2*j
if (k+1 <= last && heap[k+1]!!.frequency < heap[k]!!.frequency) {
k++
}
if (heap[j]!!.frequency < heap[k]!!.frequency) {
break
}
val tmp = heap[j]!!
heap[j] = heap[k]
heap[k] = tmp
j = k
}
return min
}
}
fun buildTree(freqs : IntArray) : HuffTree {
val heap = HuffHeap()
freqs.forEachIndexed { sym, freq ->
if (freq > 0) {
heap.insert(HuffLeaf(freq, sym.toChar()))
}
}
while (heap.size() > 1) {
val a = heap.extract()
val b = heap.extract()
heap.insert(HuffNode(a, b))
}
return heap.extract()
}
fun buildCodes(tree: HuffTree) : Array<String> {
val prefix = StringBuffer()
val codes = Array<String>(maxSymbols, {""})
buildCodes(tree, codes, prefix)
return codes
}
fun buildCodes(tree : HuffTree, codes: Array<String>, prefix : StringBuffer) {
when (tree) {
is HuffLeaf -> codes[tree.symbolIndex()] = prefix.toString()
is HuffNode -> {
prefix.append('0')
buildCodes(tree.left, codes, prefix)
prefix.deleteCharAt(prefix.lastIndex)
prefix.append('1')
buildCodes(tree.right, codes, prefix)
prefix.deleteCharAt(prefix.lastIndex)
}
}
} | mit | 52ae6ca1ac3d7114a174e73c48729ae7 | 22.6875 | 98 | 0.517345 | 3.74048 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/exercise-solutions/card-game/part-03/user-collections/src/main/kotlin/org/tsdes/advanced/exercises/cardgame/usercollections/RestAPI.kt | 1 | 3440 | package org.tsdes.advanced.exercises.cardgame.usercollections
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.tsdes.advanced.exercises.cardgame.usercollections.db.UserService
import org.tsdes.advanced.exercises.cardgame.usercollections.dto.Command
import org.tsdes.advanced.exercises.cardgame.usercollections.dto.PatchResultDto
import org.tsdes.advanced.exercises.cardgame.usercollections.dto.PatchUserDto
import org.tsdes.advanced.exercises.cardgame.usercollections.dto.UserDto
import java.lang.IllegalArgumentException
@Api(value = "/api/user-collections", description = "Operations on card collections owned by users")
@RequestMapping(
path = ["/api/user-collections"],
produces = [(MediaType.APPLICATION_JSON_VALUE)]
)
@RestController
class RestAPI(
private val userService: UserService
) {
@ApiOperation("Retrieve card collection information for a specific user")
@GetMapping(path = ["/{userId}"])
fun getUserInfo(
@PathVariable("userId") userId: String
) : ResponseEntity<UserDto>{
val user = userService.findByIdEager(userId)
if(user == null){
return ResponseEntity.notFound().build()
}
return ResponseEntity.status(200).body(DtoConverter.transform(user))
}
@ApiOperation("Create a new user, with the given id")
@PutMapping(path = ["/{userId}"])
fun createUser(
@PathVariable("userId") userId: String
): ResponseEntity<Void>{
val ok = userService.registerNewUser(userId)
return if(!ok) ResponseEntity.status(400).build()
else ResponseEntity.status(201).build()
}
@ApiOperation("Execute a command on a user's collection, like for example buying/milling cards")
@PatchMapping(
path = ["/{userId}"],
consumes = [(MediaType.APPLICATION_JSON_VALUE)]
)
fun patchUser(
@PathVariable("userId") userId: String,
@RequestBody dto: PatchUserDto
): ResponseEntity<PatchResultDto>{
if(dto.command == null){
return ResponseEntity.status(400).build()
}
if(dto.command == Command.OPEN_PACK){
val ids = try {
userService.openPack(userId)
} catch (e: IllegalArgumentException){
return ResponseEntity.status(400).build()
}
return ResponseEntity.status(200).body(PatchResultDto().apply { cardIdsInOpenedPack.addAll(ids) })
}
val cardId = dto.cardId
?: return ResponseEntity.status(400).build()
if(dto.command == Command.BUY_CARD){
try{
userService.buyCard(userId, cardId)
} catch (e: IllegalArgumentException){
return ResponseEntity.status(400).build()
}
return ResponseEntity.status(200).body(PatchResultDto())
}
if(dto.command == Command.MILL_CARD){
try{
userService.millCard(userId, cardId)
} catch (e: IllegalArgumentException){
return ResponseEntity.status(400).build()
}
return ResponseEntity.status(200).body(PatchResultDto())
}
return ResponseEntity.status(400).build()
}
} | lgpl-3.0 | d35a8fbcbe750c6fc4a5eee575c50c99 | 34.84375 | 110 | 0.653779 | 4.751381 | false | false | false | false |
androidx/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/FragmentManagerTest.kt | 3 | 11041 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.app
import androidx.fragment.app.test.FragmentTestActivity
import androidx.fragment.test.R
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.testutils.withActivity
import androidx.testutils.withUse
import com.google.common.truth.Truth.assertThat
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.Assert.fail
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
class FragmentManagerTest {
@get:Rule
val rule = DetectLeaksAfterTestSuccess()
@Test
fun addRemoveFragmentOnAttachListener() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
supportFragmentManager
}
val fragmentBefore = StrictFragment()
val fragmentDuring = StrictFragment()
val fragmentAfter = StrictFragment()
val attachedFragments = mutableListOf<Fragment>()
val listener = FragmentOnAttachListener { _, fragment ->
attachedFragments.add(fragment)
}
fm.beginTransaction()
.add(fragmentBefore, "before")
.commit()
executePendingTransactions()
fm.addFragmentOnAttachListener(listener)
fm.beginTransaction()
.add(fragmentDuring, "during")
.commit()
executePendingTransactions()
fm.removeFragmentOnAttachListener(listener)
fm.beginTransaction()
.add(fragmentAfter, "after")
.commit()
executePendingTransactions()
assertThat(attachedFragments).containsExactly(fragmentDuring)
}
}
@Test
fun removeReentrantFragmentOnAttachListener() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
supportFragmentManager
}
val fragmentDuring = StrictFragment()
val fragmentAfter = StrictFragment()
val attachedFragments = mutableListOf<Fragment>()
fm.addFragmentOnAttachListener(object : FragmentOnAttachListener {
override fun onAttachFragment(
fragmentManager: FragmentManager,
fragment: Fragment
) {
attachedFragments.add(fragment)
fragmentManager.removeFragmentOnAttachListener(this)
}
})
fm.beginTransaction()
.add(fragmentDuring, "during")
.commit()
executePendingTransactions()
fm.beginTransaction()
.add(fragmentAfter, "after")
.commit()
executePendingTransactions()
assertThat(attachedFragments).containsExactly(fragmentDuring)
}
}
@Test
fun findFragmentChildFragment() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val parentFragment = StrictViewFragment(R.layout.scene1)
val childFragment = StrictViewFragment(R.layout.fragment_a)
fm.beginTransaction()
.add(R.id.fragmentContainer, parentFragment)
.setReorderingAllowed(false)
.commit()
executePendingTransactions()
parentFragment.childFragmentManager.beginTransaction()
.add(R.id.squareContainer, childFragment)
.setReorderingAllowed(false)
.commit()
executePendingTransactions(parentFragment.childFragmentManager)
val parentRootView = parentFragment.requireView()
val childRootView = childFragment.requireView()
assertThat(FragmentManager.findFragment<Fragment>(parentRootView))
.isEqualTo(parentFragment)
assertThat(FragmentManager.findFragment<Fragment>(childRootView))
.isEqualTo(childFragment)
fm.beginTransaction()
.remove(parentFragment)
.commit()
executePendingTransactions()
// Check that even after removal, findFragment still returns the right Fragment
assertThat(FragmentManager.findFragment<Fragment>(parentRootView))
.isEqualTo(parentFragment)
assertThat(FragmentManager.findFragment<Fragment>(childRootView))
.isEqualTo(childFragment)
}
}
@Test
fun findFragmentManagerChildFragment() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val parentFragment = StrictViewFragment(R.layout.scene1)
val childFragment = StrictViewFragment(R.layout.fragment_a)
fm.beginTransaction()
.add(R.id.fragmentContainer, parentFragment)
.setReorderingAllowed(false)
.commit()
executePendingTransactions()
parentFragment.childFragmentManager.beginTransaction()
.add(R.id.squareContainer, childFragment)
.setReorderingAllowed(false)
.commit()
executePendingTransactions(parentFragment.childFragmentManager)
val parentChildFragmentManager = parentFragment.childFragmentManager
val parentRootView = parentFragment.requireView()
val childChildFragmentManager = childFragment.childFragmentManager
val childRootView = childFragment.requireView()
assertThat(FragmentManager.findFragmentManager(parentRootView))
.isEqualTo(parentChildFragmentManager)
assertThat(FragmentManager.findFragmentManager(childRootView))
.isEqualTo(childChildFragmentManager)
fm.beginTransaction()
.remove(parentFragment)
.commit()
executePendingTransactions()
try {
FragmentManager.findFragmentManager(parentRootView)
fail("findFragmentManager on the removed parentRootView should throw")
} catch (expected: IllegalStateException) {
assertThat(expected).hasMessageThat()
.isEqualTo(
"The Fragment $parentFragment that owns View $parentRootView" +
" has already been destroyed. Nested fragments should always use " +
"the child FragmentManager."
)
}
try {
FragmentManager.findFragmentManager(childRootView)
fail("findFragmentManager on the removed childRootView should throw")
} catch (expected: IllegalStateException) {
assertThat(expected).hasMessageThat()
.isEqualTo(
"The Fragment $childFragment that owns View $childRootView" +
" has already been destroyed. Nested fragments should always use " +
"the child FragmentManager."
)
}
}
}
@Test
fun addRemoveReorderingAllowedWithoutExecutePendingTransactions() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
supportFragmentManager
}
val fragment1 = StrictFragment()
val originalWho = fragment1.mWho
withActivity {
fm.beginTransaction()
.add(fragment1, "fragment1")
.setReorderingAllowed(true)
.addToBackStack("stack1")
.commit()
fm.popBackStack()
}
executePendingTransactions()
assertThat(fragment1.mWho).isNotEqualTo(originalWho)
assertThat(fragment1.mFragmentManager).isNull()
assertThat(fm.findFragmentByWho(originalWho)).isNull()
assertThat(fm.findFragmentByWho(fragment1.mWho)).isNull()
}
}
@Test
fun reAddRemovedBeforeAttached() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
supportFragmentManager
}
val fragment1 = StrictFragment()
val originalWho = fragment1.mWho
withActivity {
fm.beginTransaction()
.add(fragment1, "fragment1")
.setReorderingAllowed(true)
.addToBackStack("stack1")
.commit()
fm.popBackStack()
}
executePendingTransactions()
assertThat(fragment1.mWho).isNotEqualTo(originalWho)
assertThat(fragment1.mFragmentManager).isNull()
assertThat(fm.findFragmentByWho(originalWho)).isNull()
assertThat(fm.findFragmentByWho(fragment1.mWho)).isNull()
val afterRemovalWho = fragment1.mWho
fm.beginTransaction()
.add(fragment1, "fragment1")
.setReorderingAllowed(true)
.commit()
executePendingTransactions()
assertThat(fragment1.mWho).isEqualTo(afterRemovalWho)
}
}
@Test
fun popBackStackImmediate() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
supportFragmentManager
}
val fragment1 = StrictFragment()
fm.beginTransaction()
.add(fragment1, "fragment1")
.addToBackStack("stack1")
.commit()
executePendingTransactions()
var popped = false
withActivity {
popped = fm.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
assertThat(popped).isTrue()
}
}
}
| apache-2.0 | 9e37a3a611f5772caa7442ca1c270018 | 35.926421 | 97 | 0.60375 | 6.016894 | false | true | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/psi/elements/ElmLowerPattern.kt | 1 | 2619 | package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import org.elm.lang.core.psi.*
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReference
import org.elm.lang.core.resolve.reference.RecordFieldReference
/**
* A lower-case identifier within a pattern
*
* e.g. the `x` parameter in `f x = 0`
* e.g. `a` and `b` in the declaration `(a, b) = (0, 0)`
*/
class ElmLowerPattern(node: ASTNode) : ElmNamedElementImpl(node, IdentifierCase.LOWER),
ElmReferenceElement, ElmNameDeclarationPatternTag,
ElmFunctionParamTag, ElmPatternChildTag, ElmUnionPatternChildTag {
val identifier: PsiElement
get() = findNotNullChildByType(ElmTypes.LOWER_CASE_IDENTIFIER)
override fun getUseScope(): SearchScope {
/*
* Override IntelliJ's default so that a narrower scope can be returned.
*
* Motivation:
*
* Users frequently rename function parameters. And those parameter
* names are generally very short (e.g. `x`) and/or very common (e.g. `index`).
* IntelliJ's rename refactoring is built on top of "Find Usages" which must
* first search for all strings that match and then resolve each reference
* to see if it actually points at the thing that is being renamed.
*
* The string search is pretty fast since it uses an index, but resolving
* each possible reference can be slow. In the case of function parameters,
* their usages are constrained to just the body of the function. So we can
* drastically reduce the number of candidates by returning a narrower
* `SearchScope` in this case.
*
* Implementation:
*
* We could try and restrict the scope to be as narrow as possible, but
* I'd rather err on the side of caution for now and keep this simple.
* Restricting it just to the containing file is a huge win over scanning
* the entire project.
*
* TODO make more restrictive, being careful to handle all of the cases
*/
return LocalSearchScope(elmFile)
}
override val referenceNameElement: PsiElement
get() = identifier
override val referenceName: String
get() = identifier.text
override fun getReference(): ElmReference {
return RecordFieldReference.fromElement(this) { it.parent as? ElmRecordPattern }
}
}
| mit | da93e81eeba1521497e91f1bc4c45a57 | 39.292308 | 88 | 0.683467 | 4.476923 | false | false | false | false |
sbearcsiro/pdf-service | pdfgen-application/src/main/kotlin/au/org/ala/resources/KtPdfResource.kt | 1 | 3799 | package au.org.ala.resources
import au.org.ala.services.PdfService
import com.codahale.metrics.annotation.Timed
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.util.concurrent.UncheckedExecutionException
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpRequestBase
import org.glassfish.jersey.media.multipart.FormDataContentDisposition
import org.glassfish.jersey.media.multipart.FormDataParam
import org.slf4j.LoggerFactory
import java.io.IOException
import java.io.InputStream
import java.net.URI
import javax.ws.rs.*
import javax.ws.rs.core.Context
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import javax.ws.rs.core.UriInfo
/**
* Disabled because Kotlin adds extra annotations to method parameters, which the Jersey FormDataParam extractor
* can't deal with.
*/
@Path("pdf") class KtPdfResource(private val client: HttpClient, private val service: PdfService, urlCacheSpec: String) {
companion object {
private val log = LoggerFactory.getLogger(KtPdfResource::class.java)
internal fun buildPdfURI(info: UriInfo, hash: String): URI {
return info.baseUriBuilder.path(PdfResource::class.java).path(PdfResource::class.java, "pdf").build(hash)
}
}
private val cache = CacheBuilder.from(urlCacheSpec).build(object: CacheLoader<String,String>() {
override fun load(key: String): String = downloadAndHash(key)
})
@Timed @GET fun generate(@QueryParam("docUrl") docUrl: String?,
@Context info: UriInfo): Response {
if (docUrl == null) throw WebApplicationException(400)
try {
return Response.status(Response.Status.MOVED_PERMANENTLY).location(buildPdfURI(info, cache.getUnchecked(docUrl))).build()
} catch (e: UncheckedExecutionException) {
val c = e.cause
if (c is WebApplicationException)
throw c
else {
log.warn("Caught exception while trying to generate pdf for {}", docUrl, e)
throw WebApplicationException(500)
}
}
}
@Timed @POST @Consumes(MediaType.MULTIPART_FORM_DATA)
fun upload(@FormDataParam("file") file: InputStream,
@FormDataParam("file") contentDispositionHeader: FormDataContentDisposition,
@Context info: UriInfo ): Response {
//if (file == null) throw WebApplicationException(400)
try {
return file.use { Response.status(Response.Status.SEE_OTHER).location(buildPdfURI(info, service.hashAndConvertDocument(it))).build() }
} catch (e: IOException) {
log.error("Error converting file upload: {}", contentDispositionHeader.name, e)
throw WebApplicationException(500)
}
}
@GET @Path("{sha}") @Produces("application/pdf") fun pdf(@PathParam("sha") sha: String): Response {
val file = service.fileForSha(sha)
log.debug("Sending file ${file.absolutePath}")
return Response.ok(file).header("Content-Length", file.length()).build();
}
internal fun downloadAndHash(docUrl: String): String {
return HttpGet(docUrl).use {
val response = client.execute(it)
val status = response.statusLine.statusCode
if (status != 200) {
log.warn("HTTP error $status retrieving $docUrl")
throw WebApplicationException(400)
}
response.entity.content.use { service.hashAndConvertDocument(it) }
}
}
}
fun <T> HttpRequestBase.use(f: (HttpRequestBase) -> T): T {
try {
return f(this)
} finally {
this.reset()
}
} | mpl-2.0 | fcbbb792d753bfad4147125f45f0d135 | 36.623762 | 146 | 0.672019 | 4.239955 | false | false | false | false |
andstatus/andstatus | app/src/androidTest/kotlin/org/andstatus/app/note/ConversationViewLoaderTest.kt | 1 | 2044 | package org.andstatus.app.note
import org.andstatus.app.context.DemoData
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.context.TestSuite
import org.andstatus.app.data.MyQuery
import org.andstatus.app.data.OidEnum
import org.andstatus.app.origin.Origin
import org.andstatus.app.timeline.LoadableListActivity.ProgressPublisher
import org.andstatus.app.util.MyLog
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class ConversationViewLoaderTest : ProgressPublisher {
private var origin: Origin = Origin.EMPTY
private var selectedNoteId: Long = 0
private var progressCounter: Long = 0
@Before
fun setUp() {
MyLog.i(this, "setUp started")
TestSuite.initializeWithData(this)
origin = DemoData.demoData.getMyAccount(DemoData.demoData.conversationAccountName).origin
Assert.assertTrue(origin.isValid)
selectedNoteId = MyQuery.oidToId(OidEnum.NOTE_OID, origin.id, DemoData.demoData.conversationEntryNoteOid)
Assert.assertTrue("Selected note exists", selectedNoteId != 0L)
MyLog.i(this, "setUp ended")
}
@Test
fun testLoad() {
val loader = ConversationLoader.newLoader(
ConversationViewItem.Companion.EMPTY, MyContextHolder.myContextHolder.getNow(), origin, selectedNoteId, false)
progressCounter = 0
loader.load(this)
val list = loader.getList()
Assert.assertTrue("List is empty", list.isNotEmpty())
var indentFound = false
var orderFound = false
for (oMsg in list) {
if (oMsg.indentLevel > 0) {
indentFound = true
}
if (oMsg.mListOrder != 0) {
orderFound = true
}
}
Assert.assertTrue("Indented note found in $list", indentFound)
Assert.assertTrue("Ordered note found in $list", orderFound)
Assert.assertTrue(progressCounter > 0)
}
override fun publish(progress: String?) {
progressCounter++
}
}
| apache-2.0 | 111f0bfa11baa8f57506b4a419063cd3 | 34.859649 | 127 | 0.682975 | 4.492308 | false | true | false | false |
Tvede-dk/CommonsenseAndroidKotlin | base/src/main/kotlin/com/commonsense/android/kotlin/base/extensions/CharExtensions.kt | 1 | 1217 | @file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.base.extensions
import com.commonsense.android.kotlin.base.extensions.collections.*
import kotlin.experimental.*
/**
* Created by Kasper Tvede on 15-04-2018.
* Purpose:
*
*/
inline fun Char.toCase(upperCase: Boolean): Char =
upperCase.mapLazy(this::toUpperCase,
this::toLowerCase)
//TODO in kotlin 1.3 use UByte
inline fun hexCharsToByte(first: Char, second: Char): Short? {
val firstToInt = first.mapFromHexValue()?.toShort() ?: return null
val secondToInt = second.mapFromHexValue()?.toShort() ?: return null
return firstToInt.shl(4) or secondToInt
}
inline fun Char.mapFromHexValue(): Byte? {
val zeroNum = '0'.toByte()
val aNum = 'a'.toByte()
val thisByte = toLowerCase().toByte()
val mapped = isDigit().mapLazy({ thisByte - zeroNum }, { (thisByte - aNum) + 0xa }).toByte()
//if this byte is outside the valid range after transformation then it would not have been valid before, thus its not a "0-9 - a -f" char.
if (mapped < 0 || mapped > 0x0f) {
return null
}
//its in range, return it.
return mapped
}
| mit | f3d68a519ab2565120799b07348ecce0 | 31.891892 | 142 | 0.681183 | 3.756173 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/cabal/highlight/CabalHighlighter.kt | 1 | 1971 | package org.jetbrains.cabal.highlight
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
import gnu.trove.THashMap
import org.jetbrains.cabal.parser.CabalLexer
import org.jetbrains.cabal.parser.CabalTokelTypes
import org.jetbrains.haskell.highlight.HaskellHighlighter
import com.intellij.openapi.editor.HighlighterColors
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
public class CabalHighlighter : SyntaxHighlighterBase() {
companion object {
public val CABAL_STRING_LITERAL: TextAttributesKey = TextAttributesKey.createTextAttributesKey("CABAL_STRING_LITERAL", DefaultLanguageHighlighterColors.STRING)
public val CABAL_COMMENT: TextAttributesKey = TextAttributesKey.createTextAttributesKey("CABAL_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT)
public val CABAL_PROPERTY: TextAttributesKey = TextAttributesKey.createTextAttributesKey("CABAL_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD)
public val CABAL_COLON: TextAttributesKey = TextAttributesKey.createTextAttributesKey("CABAL_COLON", DefaultLanguageHighlighterColors.SEMICOLON)
}
override fun getHighlightingLexer(): Lexer {
return CabalLexer()
}
override fun getTokenHighlights(tokenType: IElementType): Array<TextAttributesKey> {
return SyntaxHighlighterBase.pack(keys1.get(tokenType))
}
private val keys1: MutableMap<IElementType, TextAttributesKey>
init {
keys1 = THashMap<IElementType, TextAttributesKey>()
keys1.put(CabalTokelTypes.STRING, CABAL_STRING_LITERAL)
keys1.put(CabalTokelTypes.END_OF_LINE_COMMENT, CABAL_COMMENT)
keys1.put(CabalTokelTypes.COMMENT, CABAL_COMMENT)
keys1.put(CabalTokelTypes.COLON, CABAL_COLON)
keys1.put(CabalTokelTypes.TAB, HighlighterColors.BAD_CHARACTER)
}
} | apache-2.0 | 3e6db2c9516909a99df1353cedc220eb | 43.818182 | 167 | 0.795028 | 4.704057 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/protocol/ForceCommand.kt | 1 | 1814 | package org.jetbrains.haskell.debugger.protocol
import org.jetbrains.haskell.debugger.parser.LocalBinding
import java.util.Deque
import org.jetbrains.haskell.debugger.parser.GHCiParser
import org.jetbrains.haskell.debugger.HaskellDebugProcess
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.Condition
import org.json.simple.JSONObject
import org.jetbrains.haskell.debugger.parser.JSONConverter
/**
* @author Habibullin Marat
*/
public class ForceCommand(private val bindingName: String, callback: CommandCallback<LocalBinding?>)
: RealTimeCommand<LocalBinding?>(callback) {
override fun getText(): String = ":force $bindingName\n"
override fun parseGHCiOutput(output: Deque<String?>): LocalBinding? = GHCiParser.tryParseAnyPrintCommandOutput(output)
override fun parseJSONOutput(output: JSONObject): LocalBinding? {
val res = JSONConverter.evalResultFromJSON(output)
return LocalBinding(bindingName, res.expressionType, res.expressionValue)
}
public class StandardForceCallback(val localBinding: LocalBinding, val syncObject: Lock, val bindingValueIsSet: Condition,
val debugProcess: HaskellDebugProcess)
: CommandCallback<LocalBinding?>() {
override fun execAfterParsing(result: LocalBinding?) {
syncObject.lock()
try {
if (result != null && result.name != null && result.name == localBinding.name) {
localBinding.value = result.value
} else {
localBinding.value = ""
}
//debugProcess.historyManager.markHistoryFramesAsObsolete()
bindingValueIsSet.signal()
} finally {
syncObject.unlock()
}
}
}
} | apache-2.0 | f03973f9141156551325f82b0633a3d8 | 38.456522 | 126 | 0.681367 | 4.863271 | false | false | false | false |
mitallast/netty-queue | src/main/java/org/mitallast/queue/crdt/routing/RoutingBucket.kt | 1 | 3130 | package org.mitallast.queue.crdt.routing
import io.vavr.collection.HashMap
import io.vavr.collection.Map
import io.vavr.collection.Seq
import io.vavr.collection.Set
import io.vavr.control.Option
import org.mitallast.queue.common.codec.Codec
import org.mitallast.queue.common.codec.Message
import org.mitallast.queue.transport.DiscoveryNode
class RoutingBucket : Message {
val index: Int
val replicas: Map<Long, RoutingReplica>
val resources: Map<Long, Resource>
constructor(index: Int, replicas: Seq<RoutingReplica>, resources: Seq<Resource>) {
this.index = index
this.replicas = replicas.toMap({ it.id }) { it }
this.resources = resources.toMap({ it.id }) { it }
}
@JvmOverloads constructor(index: Int, replicas: Map<Long, RoutingReplica> = HashMap.empty(), resources: Map<Long, Resource> = HashMap.empty()) {
this.index = index
this.replicas = replicas
this.resources = resources
}
fun replicaSeq(): Seq<RoutingReplica> {
return replicas.values()
}
fun replica(member: DiscoveryNode): Option<RoutingReplica> {
return replicas.values().find { replica -> replica.member == member }
}
fun exists(member: DiscoveryNode): Boolean {
return replicas.values().exists { replica -> replica.member == member }
}
fun resourceSeq(): Seq<Resource> {
return resources.values()
}
fun withResource(resource: Resource): RoutingBucket {
return RoutingBucket(
index,
replicas,
resources.put(resource.id, resource)
)
}
fun withoutResource(resource: Long): RoutingBucket {
return RoutingBucket(
index,
replicas,
resources.remove(resource)
)
}
fun hasResource(id: Long): Boolean {
return resources.containsKey(id)
}
fun resource(id: Long): Resource {
return resources.getOrElse(id, null)
}
fun withReplica(member: RoutingReplica): RoutingBucket {
return RoutingBucket(
index,
replicas.put(member.id, member),
resources
)
}
fun filterReplicas(members: Set<DiscoveryNode>): RoutingBucket {
return RoutingBucket(
index,
replicas.filterValues { replica -> members.contains(replica.member) },
resources
)
}
fun withoutReplica(replica: Long): RoutingBucket {
return RoutingBucket(
index,
replicas.remove(replica),
resources
)
}
override fun toString(): String {
return "RoutingBucket{" +
"index=" + index +
", members=" + replicas +
", resources=" + resources +
'}'
}
companion object {
val codec = Codec.of(
::RoutingBucket,
RoutingBucket::index,
RoutingBucket::replicaSeq,
RoutingBucket::resourceSeq,
Codec.intCodec(),
Codec.seqCodec(RoutingReplica.codec),
Codec.seqCodec(Resource.codec)
)
}
}
| mit | 8d9d86989792d3557b7a2d815032caa5 | 26.946429 | 148 | 0.604792 | 4.562682 | false | false | false | false |
luanalbineli/popularmovies | app/src/main/java/com/themovielist/PopularMovieApplication.kt | 1 | 3014 | package com.themovielist
import android.app.Application
import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import com.facebook.common.logging.FLog
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.imagepipeline.core.ImagePipelineConfig
import com.facebook.imagepipeline.listener.RequestListener
import com.facebook.imagepipeline.listener.RequestLoggingListener
import com.squareup.leakcanary.LeakCanary
import com.themovielist.injector.components.ApplicationComponent
import com.themovielist.injector.components.DaggerApplicationComponent
import com.themovielist.injector.modules.ApplicationModule
import com.themovielist.util.tryExecute
import io.reactivex.SingleEmitter
import timber.log.Timber
import java.sql.SQLDataException
class PopularMovieApplication : Application() {
lateinit var applicationComponent: ApplicationComponent
override fun onCreate() {
super.onCreate()
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return
}
// Fresco.
val requestListeners = HashSet<RequestListener>()
requestListeners.add(RequestLoggingListener())
val config = ImagePipelineConfig.newBuilder(this)
.setRequestListeners(requestListeners)
.build()
Fresco.initialize(this, config)
FLog.setMinimumLoggingLevel(FLog.VERBOSE)
// Timber
Timber.plant(Timber.DebugTree())
// LeakCanary
LeakCanary.install(this)
// Dagger2
applicationComponent = DaggerApplicationComponent.builder()
.applicationModule(ApplicationModule(this))
.build()
}
inline fun <T> safeContentResolver(emitter: SingleEmitter<T>, safeFunction: ContentResolver.() -> Unit) {
val contentResolver = contentResolver
if (contentResolver == null) {
emitter.onError(RuntimeException("Cannot get the ContentResolver"))
return
}
safeFunction.invoke(contentResolver)
}
inline fun <T> tryQueryOnContentResolver(emitter: SingleEmitter<T>, cursorInvoker: ContentResolver.() -> Cursor?, safeFunction: Cursor.() -> Unit) {
val contentResolver = contentResolver
if (contentResolver == null) {
emitter.onError(RuntimeException("Cannot get the ContentResolver"))
return
}
val cursor = cursorInvoker.invoke(contentResolver)
if (cursor == null) {
emitter.onError(SQLDataException("An internal error occurred."))
return
}
cursor.tryExecute(emitter, safeFunction)
}
companion object {
fun getApplicationComponent(context: Context): ApplicationComponent {
return (context.applicationContext as PopularMovieApplication).applicationComponent
}
}
}
| apache-2.0 | aed96a0254340f79892fdab3e08735ca | 34.458824 | 152 | 0.703052 | 5.440433 | false | false | false | false |
laurentvdl/sqlbuilder | src/main/kotlin/sqlbuilder/rowhandler/MapRowHandler.kt | 1 | 1590 | package sqlbuilder.rowhandler
import sqlbuilder.PersistenceException
import sqlbuilder.ResultSet
import sqlbuilder.ReturningRowHandler
import sqlbuilder.RowMap
import java.sql.SQLException
import java.util.ArrayList
class MapRowHandler : ReturningRowHandler<List<RowMap>> {
private var columnCount: Int = 0
private var columnNames: List<String?>? = null
val list = ArrayList<RowMap>()
override var result: List<RowMap> = list
override fun handle(set: ResultSet, row: Int): Boolean {
try {
if (columnNames == null) {
// cache meta data
val meta = set.getJdbcResultSet().metaData
columnCount = meta.columnCount
columnNames = (1..columnCount).map { meta.getColumnName(it) }
}
val rowMap = RowMap()
for (i in 0 until columnCount) {
handleColumn(set, rowMap, columnNames!![i], i)
}
handleMap(rowMap)
return true
} catch (e: Throwable) {
throw PersistenceException(e.message, e)
}
}
@Throws(SQLException::class)
private fun handleColumn(set: ResultSet, rowMap: RowMap, columnName: String?, column: Int) {
if (columnName == null) {
throw NullPointerException("no column name found for index $column")
}
val value = set.getJdbcResultSet().getObject(column + 1)
rowMap.put(column, value)
rowMap.put(columnName.trim(), value)
}
private fun handleMap(rowMap: RowMap) {
list.add(rowMap)
}
} | apache-2.0 | a10278cd060a25ee13d12fba8019f341 | 30.196078 | 96 | 0.616352 | 4.491525 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/ReportMessageActivity.kt | 1 | 4966 | package com.habitrpg.android.habitica.ui.activities
import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.Build
import android.os.Build.VERSION_CODES
import android.os.Bundle
import android.view.View
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.navigation.navArgs
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.databinding.ActivityReportMessageBinding
import com.habitrpg.common.habitica.extensions.getThemeColor
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.ui.helpers.dismissKeyboard
import com.habitrpg.common.habitica.helpers.setMarkdown
import javax.inject.Inject
class ReportMessageActivity : BaseActivity() {
private lateinit var binding: ActivityReportMessageBinding
@Inject
lateinit var socialRepository: SocialRepository
private var raisedElevation = 0f
private var messageID: String? = null
private var groupID: String? = null
private var isReporting: Boolean = false
override fun getLayoutResId(): Int {
return R.layout.activity_report_message
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun getContentView(): View {
binding = ActivityReportMessageBinding.inflate(layoutInflater)
return binding.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(binding.toolbar)
supportActionBar?.title = ""
raisedElevation = binding.appBar.elevation
setStatusBarDim(true)
binding.bottomSheet.setOnTouchListener { _, _ -> true }
binding.touchOutside.setOnClickListener { finish() }
binding.reportExplanationTextview.setMarkdown(getString(R.string.report_explanation))
BottomSheetBehavior.from<View>(binding.bottomSheet)
.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
@SuppressLint("SwitchIntDef")
override fun onStateChanged(bottomSheet: View, newState: Int) {
when (newState) {
BottomSheetBehavior.STATE_HIDDEN -> finish()
BottomSheetBehavior.STATE_EXPANDED -> setStatusBarDim(false)
else -> setStatusBarDim(true)
}
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {
// no op
}
})
val args = navArgs<ReportMessageActivityArgs>().value
messageID = args.messageID
groupID = args.groupID
binding.titleTextView.text = getString(R.string.report_message_title, args.profileName)
binding.messageTextView.text = args.text
binding.reportButton.setOnClickListener { reportMessage() }
binding.closeButton.setOnClickListener { finish() }
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
private fun reportMessage() {
if (isReporting) {
return
}
isReporting = true
messageID?.let {
socialRepository.flagMessage(it, binding.additionalInfoEdittext.text.toString(), groupID)
.doOnError { isReporting = false }
.subscribe(
{ finish() },
ExceptionHandler.rx()
)
}
}
private fun setStatusBarDim(dim: Boolean) {
if (dim) {
binding.appBar.elevation = 0f
window.statusBarColor = getThemeColor(R.attr.colorPrimaryDark)
binding.closeButton.visibility = View.GONE
binding.toolbarTitle.setTypeface(null, Typeface.BOLD)
} else {
binding.appBar.elevation = 8f
window.statusBarColor = ContextCompat.getColor(this, R.color.offset_background)
binding.closeButton.visibility = View.VISIBLE
binding.toolbarTitle.setTypeface(null, Typeface.NORMAL)
}
if (Build.VERSION.SDK_INT >= VERSION_CODES.M) {
setSystemBarTheme(dim)
}
}
override fun finish() {
dismissKeyboard()
super.finish()
}
@RequiresApi(api = VERSION_CODES.M)
fun setSystemBarTheme(isDark: Boolean) {
// Fetch the current flags.
val lFlags = window.decorView.systemUiVisibility
// Update the SystemUiVisibility dependening on whether we want a Light or Dark theme.
window.decorView.systemUiVisibility = if (isDark) lFlags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() else lFlags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
}
| gpl-3.0 | 532c1b38165114854c2619df70940e9d | 35.514706 | 163 | 0.671768 | 5.067347 | false | false | false | false |
FelixKlauke/mercantor | client/src/main/kotlin/de/d3adspace/mercantor/client/MercantorDiscoveryClientImpl.kt | 1 | 5031 | package de.d3adspace.mercantor.client
import de.d3adspace.mercantor.client.config.MercantorDiscoveryClientConfig
import de.d3adspace.mercantor.client.exception.NoSuchServiceException
import de.d3adspace.mercantor.client.result.DiscoveryResult
import de.d3adspace.mercantor.client.util.RoundRobinList
import de.d3adspace.mercantor.commons.model.ServiceModel
import de.d3adspace.mercantor.commons.model.ServiceStatus
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.BehaviorSubject
import org.slf4j.LoggerFactory
import java.util.*
import java.util.concurrent.ConcurrentHashMap
/**
* The default implementation of the discovery client.
*/
class MercantorDiscoveryClientImpl(private val mercantorDiscoveryClientConfig: MercantorDiscoveryClientConfig) : MercantorDiscoveryClient {
/**
* The logger of all actions.
*/
private val logger = LoggerFactory.getLogger(MercantorDiscoveryClientImpl::class.java)
/**
* The service loader.
*/
private val serviceLoader: ServiceLoader = ServiceLoader(mercantorDiscoveryClientConfig)
/**
* All currently loaded services.
*/
private val currentServices: MutableMap<String, RoundRobinList<ServiceModel>> = ConcurrentHashMap()
/**
* All currently active agents.
*/
private val currentAgents: MutableMap<UUID, ServiceAgent> = ConcurrentHashMap()
/**
* Discover an instance of the given service.
*/
override fun discoverService(vipAddress: String): Observable<DiscoveryResult> {
logger.info("Discovering service for $vipAddress.")
if (!currentServices.containsKey(vipAddress)) {
logger.info("Didn't find a local copy of services for $vipAddress.")
return fetchServicesAndConstructSingle(vipAddress)
}
val services = currentServices[vipAddress]
if (services == null || services.isEmpty) {
throw NoSuchServiceException("I don't own any services for $vipAddress")
}
val model = services.get()
return BehaviorSubject.createDefault(DiscoveryResult(model.instanceId, model.hostName, model.ipAddress, model.port))
}
private fun fetchServicesAndConstructSingle(vipAddress: String): Observable<DiscoveryResult> {
val fetchServices = fetchServices(vipAddress)
return fetchServices.map {
logger.info("Got an update for $vipAddress.")
if (!currentServices.containsKey(vipAddress)) {
val roundRobinList = RoundRobinList(it.toMutableList())
currentServices.put(vipAddress, roundRobinList)
return@map roundRobinList.get()
}
val roundRobinList = currentServices[vipAddress] ?: throw IllegalStateException()
roundRobinList.setContent(it.toMutableList())
return@map roundRobinList.get()
}.map {
DiscoveryResult(it.instanceId, it.hostName, it.ipAddress, it.port)
}.take(1)
}
/**
* Fetch the instances for the given service.
*/
private fun fetchServices(vipAddress: String): Observable<List<ServiceModel>> {
logger.info("Beginning fetching from remote for $vipAddress.")
val serviceContainer = ServiceContainer(vipAddress, serviceLoader)
return serviceContainer.services
}
/**
* Register a new service instance for the given data.
*/
override fun registerService(vipAddress: String, name: String, host: String, ipAddress: String, port: Int, metaData: Map<String, Any>): Observable<UUID> {
logger.info("Registering service for $vipAddress named $name that can be found at $host or $ipAddress:$port.")
val model = ServiceModel(UUID.randomUUID(), vipAddress, ipAddress, host, port, name, ServiceStatus.STARTING_UP, metaData)
val serviceAgent = ServiceAgent(mercantorDiscoveryClientConfig, model)
val serviceObservable = serviceAgent.registerService()
serviceObservable.subscribeOn(Schedulers.newThread()).subscribe {
model.status = ServiceStatus.UP
serviceAgent.startHeartbeats()
logger.info("Registered service for $vipAddress. It got the instance id ${model.instanceId}")
currentAgents.put(model.instanceId, serviceAgent)
}
return serviceObservable
}
/**
* Unregister the instance behind the given instance id.
*/
override fun unregisterService(instanceId: UUID) {
logger.info("Unregistering service with instance id $instanceId.")
currentAgents[instanceId]?.destroy()
currentAgents.remove(instanceId)
}
override fun reportInvalidService(instanceId: UUID) {
currentServices.values.forEach { currentServiceList ->
currentServiceList.getContent()
.filter { it.instanceId == instanceId }
.forEach { currentServiceList.remove(it) }
}
//TODO: Send corresponding heartbeat?
}
} | mit | 40f41f5ae5ede76ed90fb219ed16b75c | 36.274074 | 158 | 0.697476 | 4.746226 | false | false | false | false |
divinespear/jpa-schema-gradle-plugin | src/main/kotlin/io/github/divinespear/plugin/mock.kt | 1 | 38893 | package io.github.divinespear.plugin
import java.sql.*
import java.util.*
import java.util.concurrent.Executor
class ConnectionMock(
val productName: String,
val majorVersion: Int?,
val minorVersion: Int?
) : Connection {
override fun getMetaData(): DatabaseMetaData = DatabaseMetaDataMock(this)
override fun getAutoCommit(): Boolean = true
override fun setAutoCommit(autoCommit: Boolean) {}
override fun prepareStatement(sql: String?): PreparedStatement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun prepareStatement(sql: String?, resultSetType: Int, resultSetConcurrency: Int): PreparedStatement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun prepareStatement(
sql: String?,
resultSetType: Int,
resultSetConcurrency: Int,
resultSetHoldability: Int
): PreparedStatement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun prepareStatement(sql: String?, autoGeneratedKeys: Int): PreparedStatement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun prepareStatement(sql: String?, columnIndexes: IntArray?): PreparedStatement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun prepareStatement(sql: String?, columnNames: Array<out String>?): PreparedStatement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun rollback() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun rollback(savepoint: Savepoint?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getHoldability(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setNetworkTimeout(executor: Executor?, milliseconds: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun commit() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun <T : Any?> unwrap(iface: Class<T>?): T {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTransactionIsolation(level: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun abort(executor: Executor?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun prepareCall(sql: String?): CallableStatement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun prepareCall(sql: String?, resultSetType: Int, resultSetConcurrency: Int): CallableStatement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun prepareCall(
sql: String?,
resultSetType: Int,
resultSetConcurrency: Int,
resultSetHoldability: Int
): CallableStatement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getClientInfo(name: String?): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getClientInfo(): Properties {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setCatalog(catalog: String?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getWarnings(): SQLWarning {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getCatalog(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setHoldability(holdability: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSchema(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isValid(timeout: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun close() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isClosed(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createNClob(): NClob {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createBlob(): Blob {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createArrayOf(typeName: String?, elements: Array<out Any>?): java.sql.Array {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setReadOnly(readOnly: Boolean) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isWrapperFor(iface: Class<*>?): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun nativeSQL(sql: String?): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createStruct(typeName: String?, attributes: Array<out Any>?): Struct {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setClientInfo(name: String?, value: String?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setClientInfo(properties: Properties?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun releaseSavepoint(savepoint: Savepoint?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createClob(): Clob {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isReadOnly(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createStatement(): Statement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createStatement(resultSetType: Int, resultSetConcurrency: Int): Statement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createStatement(resultSetType: Int, resultSetConcurrency: Int, resultSetHoldability: Int): Statement {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setSavepoint(): Savepoint {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setSavepoint(name: String?): Savepoint {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTypeMap(): MutableMap<String, Class<*>> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun clearWarnings() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTransactionIsolation(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setSchema(schema: String?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getNetworkTimeout(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun setTypeMap(map: MutableMap<String, Class<*>>?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createSQLXML(): SQLXML {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
class DatabaseMetaDataMock(private val connection: ConnectionMock) : DatabaseMetaData {
override fun getConnection() = connection
override fun getDriverName() = connection.productName
override fun getDatabaseProductName() = connection.productName
override fun getDatabaseMajorVersion(): Int = connection.majorVersion ?: 0
override fun getDatabaseMinorVersion(): Int = connection.minorVersion ?: 0
override fun supportsSubqueriesInQuantifieds(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsGetGeneratedKeys(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsCoreSQLGrammar(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxColumnsInIndex(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun insertsAreDetected(type: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsIntegrityEnhancementFacility(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getAttributes(
catalog: String?,
schemaPattern: String?,
typeNamePattern: String?,
attributeNamePattern: String?
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getDatabaseProductVersion(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsOpenStatementsAcrossRollback(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxProcedureNameLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getCatalogTerm(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsCatalogsInDataManipulation(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxUserNameLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getJDBCMajorVersion(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTimeDateFunctions(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsStoredFunctionsUsingCallSyntax(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun autoCommitFailureClosesAllResultSets(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxColumnsInSelect(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getCatalogs(): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun storesLowerCaseQuotedIdentifiers(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsDataDefinitionAndDataManipulationTransactions(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsCatalogsInTableDefinitions(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxColumnsInOrderBy(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getDriverMinorVersion(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun storesUpperCaseIdentifiers(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun nullsAreSortedLow(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsSchemasInIndexDefinitions(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxStatementLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsTransactions(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsResultSetConcurrency(type: Int, concurrency: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isReadOnly(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun usesLocalFiles(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsResultSetType(type: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxConnections(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTables(
catalog: String?,
schemaPattern: String?,
tableNamePattern: String?,
types: Array<out String>?
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsMultipleResultSets(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun dataDefinitionIgnoredInTransactions(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getFunctions(catalog: String?, schemaPattern: String?, functionNamePattern: String?): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSearchStringEscape(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsGroupBy(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxTableNameLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun dataDefinitionCausesTransactionCommit(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsOpenStatementsAcrossCommit(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun ownInsertsAreVisible(type: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSchemaTerm(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isCatalogAtStart(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getFunctionColumns(
catalog: String?,
schemaPattern: String?,
functionNamePattern: String?,
columnNamePattern: String?
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsTransactionIsolationLevel(level: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun nullsAreSortedAtStart(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getPrimaryKeys(catalog: String?, schema: String?, table: String?): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getProcedureTerm(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsANSI92IntermediateSQL(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsOuterJoins(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun <T : Any?> unwrap(iface: Class<T>?): T {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsLikeEscapeClause(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsPositionedUpdate(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsMixedCaseIdentifiers(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsLimitedOuterJoins(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSQLStateType(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSystemFunctions(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxRowSize(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsOpenCursorsAcrossRollback(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTableTypes(): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxTablesInSelect(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun nullsAreSortedHigh(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getURL(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsNamedParameters(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsConvert(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsConvert(fromType: Int, toType: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxStatements(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getProcedureColumns(
catalog: String?,
schemaPattern: String?,
procedureNamePattern: String?,
columnNamePattern: String?
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun allTablesAreSelectable(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getJDBCMinorVersion(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getCatalogSeparator(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSuperTypes(catalog: String?, schemaPattern: String?, typeNamePattern: String?): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxBinaryLiteralLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTypeInfo(): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getVersionColumns(catalog: String?, schema: String?, table: String?): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsMultipleOpenResults(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun deletesAreDetected(type: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsMinimumSQLGrammar(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxColumnsInGroupBy(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getNumericFunctions(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getExtraNameCharacters(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxCursorNameLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun nullsAreSortedAtEnd(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsSchemasInDataManipulation(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSchemas(): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSchemas(catalog: String?, schemaPattern: String?): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsCorrelatedSubqueries(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getDefaultTransactionIsolation(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun locatorsUpdateCopy(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getColumns(
catalog: String?,
schemaPattern: String?,
tableNamePattern: String?,
columnNamePattern: String?
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getCrossReference(
parentCatalog: String?,
parentSchema: String?,
parentTable: String?,
foreignCatalog: String?,
foreignSchema: String?,
foreignTable: String?
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun ownDeletesAreVisible(type: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun othersUpdatesAreVisible(type: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsStatementPooling(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun storesLowerCaseIdentifiers(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsCatalogsInIndexDefinitions(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun ownUpdatesAreVisible(type: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getUDTs(
catalog: String?,
schemaPattern: String?,
typeNamePattern: String?,
types: IntArray?
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getStringFunctions(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxColumnsInTable(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsColumnAliasing(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsSchemasInProcedureCalls(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getClientInfoProperties(): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun usesLocalFilePerTable(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getIdentifierQuoteString(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsFullOuterJoins(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsOrderByUnrelated(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsSchemasInTableDefinitions(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsCatalogsInProcedureCalls(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getUserName(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getBestRowIdentifier(
catalog: String?,
schema: String?,
table: String?,
scope: Int,
nullable: Boolean
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsTableCorrelationNames(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxIndexLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsSubqueriesInExists(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxSchemaNameLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsANSI92EntryLevelSQL(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getDriverVersion(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getPseudoColumns(
catalog: String?,
schemaPattern: String?,
tableNamePattern: String?,
columnNamePattern: String?
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsMixedCaseQuotedIdentifiers(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getProcedures(catalog: String?, schemaPattern: String?, procedureNamePattern: String?): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getDriverMajorVersion(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsANSI92FullSQL(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsAlterTableWithAddColumn(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsResultSetHoldability(holdability: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getColumnPrivileges(
catalog: String?,
schema: String?,
table: String?,
columnNamePattern: String?
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getImportedKeys(catalog: String?, schema: String?, table: String?): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsUnionAll(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getRowIdLifetime(): RowIdLifetime {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun doesMaxRowSizeIncludeBlobs(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsGroupByUnrelated(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getIndexInfo(
catalog: String?,
schema: String?,
table: String?,
unique: Boolean,
approximate: Boolean
): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsSubqueriesInIns(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsStoredProcedures(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getExportedKeys(catalog: String?, schema: String?, table: String?): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsPositionedDelete(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsAlterTableWithDropColumn(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsExpressionsInOrderBy(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxCatalogNameLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsExtendedSQLGrammar(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun othersInsertsAreVisible(type: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun updatesAreDetected(type: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsDataManipulationTransactionsOnly(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsSubqueriesInComparisons(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsSavepoints(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSQLKeywords(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxColumnNameLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun nullPlusNonNullIsNull(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsGroupByBeyondSelect(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsCatalogsInPrivilegeDefinitions(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun allProceduresAreCallable(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSuperTables(catalog: String?, schemaPattern: String?, tableNamePattern: String?): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun generatedKeyAlwaysReturned(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun isWrapperFor(iface: Class<*>?): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun storesUpperCaseQuotedIdentifiers(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getMaxCharLiteralLength(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun othersDeletesAreVisible(type: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsNonNullableColumns(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsUnion(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsDifferentTableCorrelationNames(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsSchemasInPrivilegeDefinitions(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsSelectForUpdate(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsMultipleTransactions(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun storesMixedCaseQuotedIdentifiers(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsOpenCursorsAcrossCommit(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun storesMixedCaseIdentifiers(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTablePrivileges(catalog: String?, schemaPattern: String?, tableNamePattern: String?): ResultSet {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun supportsBatchUpdates(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getResultSetHoldability(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
| apache-2.0 | 127b863d09b250ebc0ce05bf071f702a | 38.525407 | 117 | 0.722392 | 4.845876 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/accounts/ImportAsActivity.kt | 1 | 2181 | package org.walleth.accounts
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_account_type_select.*
import org.walleth.R
import org.walleth.base_activities.BaseSubActivity
import org.walleth.data.*
import org.walleth.data.addresses.AccountKeySpec
class ImportAsActivity : BaseSubActivity() {
private val inSpec by lazy {
getAccountSpecFromIntent().copy(source = "import")
}
private fun getAccountSpecFromIntent() = intent.getParcelableExtra<AccountKeySpec>(EXTRA_KEY_ACCOUNTSPEC)
?: throw(IllegalStateException("Did not have parcleable extra EXTRA_KEY_ACCOUNTSPEC in intent"))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_account_type_select)
supportActionBar?.subtitle = getString(R.string.import_as_subtitle)
recycler.layoutManager = LinearLayoutManager(this)
recycler.adapter = AccountTypeAdapter(ACCOUNT_TYPE_LIST.filter { it.wrapsKey }, inSpec)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && data != null) {
when (requestCode) {
REQUEST_CODE_ENTER_PASSWORD -> {
val pwdExtra = data.getStringExtra(EXTRA_KEY_PWD)
val spec = inSpec.copy(type = ACCOUNT_TYPE_PASSWORD_PROTECTED, pwd = pwdExtra)
setResult(resultCode, data.putExtra(EXTRA_KEY_ACCOUNTSPEC, spec))
}
REQUEST_CODE_ENTER_PIN -> {
val pinExtra = data.getStringExtra(EXTRA_KEY_PIN)
val spec = inSpec.copy(type = ACCOUNT_TYPE_PIN_PROTECTED, pwd = pinExtra)
setResult(resultCode, data.putExtra(EXTRA_KEY_ACCOUNTSPEC, spec))
}
else -> {
setResult(resultCode, data)
}
}
finish()
}
}
}
| gpl-3.0 | 55adcc3a32fd3d19cf4ddbb6197bfba5 | 37.263158 | 109 | 0.654287 | 4.660256 | false | false | false | false |
mtransitapps/parser | src/main/java/org/mtransit/commons/HtmlSymbols.kt | 1 | 3209 | package org.mtransit.commons
import org.mtransit.commons.Constants.EMPTY
import org.mtransit.commons.Constants.SPACE_
@Suppress("unused")
object HtmlSymbols {
private const val C_AIRPLANE = "✈" // ✈ https://unicode-table.com/en/2708/
private const val C_AIRPLANE_ARRIVING = "🛬" // 🛬 https://unicode-table.com/en/1F6EC/
private const val C_AIRPLANE_DEPARTURE = "🛫" // 🛫 https://unicode-table.com/en/1F6EB/
private const val C_AIRPLANE_SMALL = "🛩" // 🛩 https://unicode-table.com/en/1F6E9/
private const val C_DOOR = "🚪" // 🚪 https://unicode-table.com/en/1F6AA/
private const val C_DOWNWARDS_ARROW = "↓" // ↓ https://unicode-table.com/en/2193/
private const val C_HOSPITAL = "🏥" // 🏥 https://unicode-table.com/en/1F3E5/
private const val C_METRO = "🚇" // 🚇 https://unicode-table.com/en/1F687/
private const val C_NATIONAL_PARK = "🏞" // 🏞 https://unicode-table.com/en/1F3DE/
private const val C_ROLLER_COASTER = "🎢" // 🎢 https://unicode-table.com/en/1F3A2/
private const val C_SCHOOL = "🏫" // 🏫 https://unicode-table.com/en/1F3EB/
private const val C_SLOT_MACHINE = "🎰" // 🎰 https://unicode-table.com/en/1F3B0/
private const val C_STADIUM = "🏟" // 🏟 https://unicode-table.com/en/1F3DF/
private const val C_TRAIN = "🚆" // 🚆 https://unicode-table.com/en/1F686/
// @formatter:off
@JvmField // TODO const
val SUBWAY = if (FeatureFlags.F_HTML_POI_NAME) C_METRO else EMPTY
@JvmField // TODO const
val SUBWAY_ = if (FeatureFlags.F_HTML_POI_NAME) SUBWAY + SPACE_ else EMPTY
@JvmField // TODO const
val TRAIN = if (FeatureFlags.F_HTML_POI_NAME) C_TRAIN else EMPTY
@JvmField // TODO const
val TRAIN_ = if (FeatureFlags.F_HTML_POI_NAME) TRAIN + SPACE_ else EMPTY
@JvmField // TODO const
val AIRPORT = if (FeatureFlags.F_HTML_POI_NAME) C_AIRPLANE else EMPTY
@JvmField // TODO const
val AIRPORT_ = if (FeatureFlags.F_HTML_POI_NAME) AIRPORT + SPACE_ else EMPTY
@JvmField // TODO const
val HOSPITAL = if (FeatureFlags.F_HTML_POI_NAME) C_HOSPITAL else EMPTY
@JvmField // TODO const
val HOSPITAL_ = if (FeatureFlags.F_HTML_POI_NAME) HOSPITAL + SPACE_ else EMPTY
@JvmField // TODO const
val SCHOOL = if (FeatureFlags.F_HTML_POI_NAME) C_SCHOOL else EMPTY
@JvmField // TODO const
val SCHOOL_ = if (FeatureFlags.F_HTML_POI_NAME) SCHOOL + SPACE_ else EMPTY
@JvmField // TODO const
val STADIUM = if (FeatureFlags.F_HTML_POI_NAME) C_STADIUM else EMPTY
@JvmField // TODO const
val STADIUM_ = if (FeatureFlags.F_HTML_POI_NAME) STADIUM + SPACE_ else EMPTY
@JvmField // TODO const
val PARK = if (FeatureFlags.F_HTML_POI_NAME) C_NATIONAL_PARK else EMPTY
@JvmField // TODO const
val PARK_ = if (FeatureFlags.F_HTML_POI_NAME) PARK + SPACE_ else EMPTY
@JvmField // TODO const
val ROLLER_COASTER = if (FeatureFlags.F_HTML_POI_NAME) C_ROLLER_COASTER else EMPTY
@JvmField // TODO const
val ROLLER_COASTER_ = if (FeatureFlags.F_HTML_POI_NAME) ROLLER_COASTER + SPACE_ else EMPTY
// @formatter:on
} | apache-2.0 | bd0b0c5f491272a333ab8b93278d6c90 | 46.313433 | 97 | 0.673399 | 3.067764 | false | false | false | false |
Mindera/skeletoid | base/src/main/java/com/mindera/skeletoid/generic/StringUtils.kt | 1 | 711 | package com.mindera.skeletoid.generic
object StringUtils {
/**
* Get the nth index of a substring on a string
*
* @param str The string
* @param substr the substring
* @param index nth ocurrence
* @return The index
*/
@JvmStatic
fun ordinalIndexOf(str: String?, substr: String?, index: Int): Int {
if (str == null || substr == null || index <= 0) {
return -1
}
if (str == substr && index > 1) {
return -1
}
var pos = str.indexOf(substr)
var position = index
while (--position > 0 && pos != -1) {
pos = str.indexOf(substr, pos + 1)
}
return pos
}
} | mit | e4d723b9e3305d6fe440298db61e0680 | 25.37037 | 72 | 0.510549 | 4.086207 | false | false | false | false |
xiprox/Tensuu | app/src/main/java/tr/xip/scd/tensuu/ui/reports/WeeklyPresenter.kt | 1 | 3252 | package tr.xip.scd.tensuu.ui.reports
import io.realm.Sort
import tr.xip.scd.tensuu.App.Companion.context
import tr.xip.scd.tensuu.R
import tr.xip.scd.tensuu.common.ext.*
import tr.xip.scd.tensuu.realm.model.Student
import tr.xip.scd.tensuu.realm.model.StudentFields
import tr.xip.scd.tensuu.common.ui.mvp.RealmPresenter
import java.text.SimpleDateFormat
import java.util.*
import java.util.Calendar.*
class WeeklyPresenter : RealmPresenter<WeeklyView>() {
private var cal = Calendar.getInstance().stripToDate()
fun init() {
view?.setAdapter(
ReportsAdapter(
realm,
cal.strippedTimestamp(),
cal.addChainable(DAY_OF_YEAR, 7).strippedTimestamp().toEndOfTheDay(),
true,
realm.where(Student::class.java)
.findAll()
.sort(
arrayOf(StudentFields.FLOOR,
StudentFields.GRADE,
StudentFields.LAST_NAME,
StudentFields.FIRST_NAME),
arrayOf(Sort.ASCENDING,
Sort.ASCENDING,
Sort.ASCENDING,
Sort.ASCENDING)
),
{ view?.onStudentClicked(it) }
)
)
goToThisWeek()
}
fun shiftStartDayBy(days: Int) {
cal.add(DAY_OF_YEAR, days)
onDataChanged()
}
fun goToThisWeek() {
cal = Calendar.getInstance().stripToDate()
val daysSince = when (cal.dayOfWeek) {
MONDAY -> 0
TUESDAY -> 1
WEDNESDAY -> 2
THURSDAY -> 3
FRIDAY -> 4
SATURDAY -> 5
SUNDAY -> 6
else -> 0
}
shiftStartDayBy(-daysSince)
}
private fun setCurrentWeekText() {
view?.setCurrentWeekText(
context.getString(
R.string.week_of_s,
SimpleDateFormat("MMM d").format(cal.timeInMillis)
)
)
}
private fun reloadData() {
val endCal = GregorianCalendar()
endCal.timeInMillis = cal.timeInMillis
endCal.add(DAY_OF_YEAR, 7)
view?.getAdapter()?.updateDates(
cal.strippedTimestamp(),
endCal.strippedTimestamp().toEndOfTheDay()
)
}
fun onNextWeekClicked() {
shiftStartDayBy(7)
}
fun onCurrentWeekClicked() {
goToThisWeek()
}
fun onPreviousWeekClicked() {
shiftStartDayBy(-7)
}
fun onDataChanged() {
setCurrentWeekText()
reloadData()
}
fun onStudentClicked(student: Student?) {
if (student == null) return
val endCal = GregorianCalendar()
endCal.timeInMillis = cal.timeInMillis
endCal.add(DAY_OF_YEAR, 7)
view?.startStudentActivity(student, cal.timeInMillis, endCal.timeInMillis)
}
} | gpl-3.0 | ba5400c627e86c0d07f10e23db6859de | 29.688679 | 93 | 0.497232 | 4.980092 | false | false | false | false |
just-4-fun/holomorph | src/test/kotlin/just4fun/holomorph/mains/ProductionBig.kt | 1 | 5425 | package just4fun.holomorph.mains
import just4fun.holomorph.*
import just4fun.holomorph.types.LongBasedType
import just4fun.holomorph.types.SchemaType
import just4fun.holomorph.forms.DefaultFactory
import just4fun.holomorph.types.CollectionType
import just4fun.holomorph.types.MapType
import just4fun.holomorph.forms_experimental.JsonFactory
import just4fun.holomorph.forms_experimental.XmlFactory
import org.jetbrains.spek.api.On
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.shouldBeTrue
import java.util.*
import kotlin.reflect.KClass
enum class EnumValues {OK, FAIL }
class ProductionBig: Spek() { init {
given("Schema normal") {
println("${Date(2000000000000)}")
class Simple(val x: Int, var y: String)
class DateType: LongBasedType<Date>(Date::class) {
override fun newInstance(): Date = Date()
override fun fromValue(v: Long): Date? = Date().apply { time = v }
override fun toValue(v: Date?): Long? = v?.time
override fun toString(v: Date?, sequenceSizeLimit: Int): String = v?.time?.toString() ?: "null"
override fun fromEntry(value: String): Date? = Date(value)
}
@Suppress("UNCHECKED_CAST")
class AListType<E: Any>(elementType: Type<E>): CollectionType<ArrayList<E>, E>(ArrayList::class as KClass<ArrayList<E>>, elementType) {
override fun newInstance(): ArrayList<E> = ArrayList()
override fun addElement(e: E?, index: Int, seq: ArrayList<E>): ArrayList<E> = seq.also { (it as ArrayList<E?>) += e }
}
class DateMapType(kt: DateType, mt: DateType): MapType<Date, Date>(kt, mt) {
override fun nameToKey(name: String): Date? = Date(name.toLong())
override fun keyToName(key: Date): String = key.time.toString()
}
Types.run {
//
// defineType(Date::class) { DateType() }
// defineType(ArrayList::class) { et -> AListType(et[0]) }
val dateType = addType(DateType::class) { DateType() }
defineType(MutableMap::class, dateType, dateType) { ts -> DateMapType(ts[0] as DateType, ts[1] as DateType) }
}
open class ObjBase {
open var p0: Long = 100L
open var p1: Int = 100
open var p2: Short = 100
open var p3: Byte = 100
open var p4: Double? = 0.01
open var p5: Float = 0.01f
open var p6: Char = '\u1002'
open var p7: Boolean = true
open var p8: String? = "00Aa"
// var p9: STUB
var p10: Array<String> = arrayOf("qwer", "1234")
var p11: ByteArray = byteArrayOf(1, 2, 3)
var p12: BooleanArray = booleanArrayOf(true, false, true)
var p13: List<Char>? = listOf('a', 'A', '0')
var p14: MutableList<Float> = mutableListOf(0.12f, 12.0f)
var p15: Set<Double>? = setOf(123.01, 0.123)
var p16: MutableSet<Double> = mutableSetOf(123.01, 0.123)
@DefineType(DateType::class)
var p17: Date = Date(1234567890)
var p18: List<Date?>? = listOf(Date(1234), Date(5678))
var p19: Array<Array<String>> = arrayOf(arrayOf("asd", "123"), arrayOf("xyz", "555"))
var p20: Simple = Simple(123, "ABC")
var p21: MutableSet<Simple?>? = mutableSetOf(Simple(123, "ABC"), Simple(344, "XZY"))
var p22: MutableMap<Date, Date?> = mutableMapOf(Date(1L) to Date(1L), Date(2L) to Date(2L))
var p23: MutableMap<String, Any?> = mutableMapOf("k0" to 22, "k1" to listOf("ok", "oops"), "k2" to arrayOf("x", "8"), "k3" to mapOf("a" to 12, 12 to "a"))
var p24: Array<Any?>? = arrayOf(123, "abc", listOf("ok", "oops"), arrayOf("x", "8"), mapOf("a" to 12, 12 to "a"))
@DefineType(AListType::class)
val p25: ArrayList<Simple> = ArrayList<Simple>().apply { add(Simple(1, "abc")) }
val p26 = Triple(true, 1, "ok")
val p27 = EnumValues.FAIL
}
class ObjN: ObjBase()
class ObjC(override var p0: Long, override var p1: Int, override var p2: Short, override var p3: Byte, override var p4: Double?, override var p5: Float, override var p6: Char, override var p7: Boolean, override var p8: String?): ObjBase()
val schN = SchemaType(ObjN::class)
val schC = SchemaType(ObjC::class)
val objN = ObjN()
val objC = ObjC(201L, 202, 203, 104, 20.5, 20.6f, 'S', true, "manual")
fun <O: Any, T: Any> test(on: On, obj: O, schema: SchemaType<O>, providerFactory: EntryProviderFactory<T>, consumerFactory: EntryConsumerFactory<T>, info: String) {
println("TEST:: Obj: ${obj::class.simpleName} ; Prod: ${providerFactory::class.simpleName}; Cons: ${consumerFactory::class.simpleName}")
val prod1 = schema.instanceTo(obj, consumerFactory).valueOrThrow
val obj1 = schema.instanceFrom(prod1, providerFactory).value
// println("Obj1? ${obj1 != null}; Pro1\n$prod1")
on.it(info) {
if (obj1 == null) println("Obj1 is null")
else if (!schema.equal(obj, obj1)) println("Prod\n$prod1\nprod1\n${schema.instanceTo(obj1!!, consumerFactory)}")
shouldBeTrue(schema.equal(obj, obj1))
}
}
on("Json Factoy") {
val factory = JsonFactory
test(this, objN, schN, factory, factory, "without constructor")
test(this, objC, schC, factory, factory, "with constructor")
}
on("Default Factoy") {
val factory = DefaultFactory
test(this, objN, schN, factory, factory, "without constructor")
test(this, objC, schC, factory, factory, "with constructor")
}
on("XML Factoy") {
val factory = XmlFactory
test(this, objN, schN, factory, factory, "without constructor")
test(this, objC, schC, factory, factory, "with constructor")
}
}
}
// todo test extreme cases (empty schema/seq etc)
// todo test Sequence read/write
}
| apache-2.0 | a06cc010634d57ed5c00c1695bc04f40 | 41.054264 | 240 | 0.676129 | 3.103547 | false | true | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/grammar/runtime/data/RuntimeArray.kt | 1 | 3008 | package com.bajdcc.LALR1.grammar.runtime.data
import com.bajdcc.LALR1.grammar.runtime.IRuntimeStatus
import com.bajdcc.LALR1.grammar.runtime.RuntimeException
import com.bajdcc.LALR1.grammar.runtime.RuntimeObject
/**
* 【运行时】运行时数组
*
* @author bajdcc
*/
class RuntimeArray : Cloneable {
private var array = mutableListOf<RuntimeObject>()
val isEmpty: Boolean
get() = array.isEmpty()
constructor()
constructor(obj: RuntimeArray) {
copyFrom(obj)
}
constructor(array: List<RuntimeObject>) {
this.array = array.toMutableList()
}
fun add(obj: RuntimeObject) {
array.add(obj)
}
fun add(arr: RuntimeArray) {
array.addAll(arr.array)
}
fun insert(index: Int, obj: RuntimeObject) {
array.add(index, obj)
}
operator fun set(index: Int, obj: RuntimeObject): Boolean {
if (index >= 0 && index < array.size) {
array[index] = obj
return true
}
return false
}
fun pop(): RuntimeObject? {
return if (array.isEmpty()) {
null
} else array.removeAt(array.size - 1)
}
fun distinct(): RuntimeArray {
return RuntimeArray(array.distinct())
}
operator fun get(index: Int): RuntimeObject {
return if (index >= 0 && index < array.size) {
array[index]
} else RuntimeObject(null)
}
@Throws(RuntimeException::class)
operator fun get(index: Int, status: IRuntimeStatus): RuntimeObject {
if (index >= 0 && index < array.size) {
return array[index]
}
status.err(RuntimeException.RuntimeError.INVALID_INDEX, "array.get")
throw IndexOutOfBoundsException()
}
operator fun contains(obj: RuntimeObject): Boolean {
return array.contains(obj)
}
fun size(): RuntimeObject {
return RuntimeObject(array.size.toLong())
}
fun length(): Int {
return array.size
}
fun remove(index: Int): RuntimeObject {
return if (index >= 0 && index < array.size) {
array.removeAt(index)
} else RuntimeObject(null)
}
fun delete(obj: RuntimeObject): RuntimeObject {
return RuntimeObject(array.remove(obj))
}
fun reverse() {
array.reverse()
}
fun clear() {
array.clear()
}
/**
* 深拷贝
*
* @param obj 原对象
*/
fun copyFrom(obj: RuntimeArray) {
array = obj.array.map{ it.clone() }.toMutableList()
}
fun toList(): List<Any> {
return array.map { it.obj!! }.toList()
}
fun toStringList(): List<String> {
return array.map { it.obj!!.toString() }.toList()
}
public override fun clone(): RuntimeArray {
return super.clone() as RuntimeArray
}
fun getArray(): List<RuntimeObject> {
return array.toList()
}
override fun toString(): String {
return array.size.toString()
}
}
| mit | b604fba124a97958ad372c1343d45a72 | 21.545455 | 76 | 0.586022 | 4.185654 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/android/e2e/testapp/ReadAnimalHostService.kt | 1 | 2675 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.e2e.testapp
// TODO(b/170962663) Disabled due to different ordering after copybara transformations.
/* ktlint-disable import-ordering */
import androidx.lifecycle.Lifecycle
import android.content.Context
import android.content.Intent
import arcs.core.host.ArcHost
import arcs.core.host.HandleManagerFactory
import arcs.core.host.ParticleRegistration
import arcs.core.host.SimpleSchedulerProvider
import arcs.core.host.toRegistration
import arcs.jvm.util.JvmTime
import arcs.sdk.android.labs.host.AndroidHost
import arcs.sdk.android.labs.host.ArcHostService
import arcs.sdk.android.storage.AndroidStorageServiceEndpointManager
import arcs.sdk.android.storage.service.DefaultBindHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.MainScope
/**
* Service wrapping an ArcHost which hosts a particle writing data to a handle.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class ReadAnimalHostService : ArcHostService() {
private val coroutineScope = MainScope()
private val handleManagerFactory = HandleManagerFactory(
SimpleSchedulerProvider(coroutineScope.coroutineContext),
AndroidStorageServiceEndpointManager(
coroutineScope,
DefaultBindHelper(this)
),
JvmTime
)
override val arcHost: ArcHost = MyArcHost(
this,
this.lifecycle,
handleManagerFactory,
::ReadAnimal.toRegistration()
)
override val arcHosts = listOf(arcHost)
@OptIn(ExperimentalCoroutinesApi::class)
class MyArcHost(
context: Context,
lifecycle: Lifecycle,
handleManagerFactory: HandleManagerFactory,
vararg initialParticles: ParticleRegistration
) : AndroidHost(
context = context,
lifecycle = lifecycle,
coroutineContext = Dispatchers.Default,
arcSerializationContext = Dispatchers.Default,
handleManagerFactory = handleManagerFactory,
particles = initialParticles
)
inner class ReadAnimal : AbstractReadAnimal() {
override fun onStart() {
handles.animal.onUpdate {
val name = handles.animal.fetch()?.name ?: ""
val intent = Intent(this@ReadAnimalHostService, TestActivity::class.java)
.apply {
putExtra(TestActivity.RESULT_NAME, name)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
startActivity(intent)
}
}
}
}
| bsd-3-clause | c7aea3db43164233ef0a48804fc133d4 | 29.397727 | 96 | 0.754766 | 4.604131 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.