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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Frederikam/FredBoat | FredBoat/src/main/java/fredboat/agent/CarbonitexAgent.kt | 1 | 3808 | /*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* 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 fredboat.agent
import com.fredboat.sentinel.entities.ShardStatus
import fredboat.config.property.AppConfig
import fredboat.config.property.Credentials
import fredboat.main.BotController
import fredboat.util.SentinelCountingService
import fredboat.util.rest.Http
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.reactive.awaitSingle
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
@Service
class CarbonitexAgent(
private val credentials: Credentials,
private val appConfig: AppConfig,
private val counting: SentinelCountingService
) : FredBoatAgent("carbonitex", 30, TimeUnit.MINUTES) {
public override fun doRun() {
GlobalScope.launch {
sendStats()
}
}
private suspend fun sendStats() {
val allConnected = AtomicBoolean(true)
val shardCounter = AtomicInteger(0)
val counts = counting.getCounts().awaitSingle()
counts.shards.forEach { shard ->
shardCounter.incrementAndGet()
if (shard.shard.status != ShardStatus.CONNECTED) {
allConnected.set(false)
}
}
if (!allConnected.get()) {
log.warn("Skipping posting stats because not all shards are online!")
return
}
if (shardCounter.get() < appConfig.shardCount) {
log.warn("Skipping posting stats because not all shards initialized!")
return
}
try {
BotController.HTTP.post("https://www.carbonitex.net/discord/data/botdata.php",
Http.Params.of(
"key", credentials.carbonKey,
"servercount", counts.guilds.toString()
))
.execute().use { response ->
val content = response.body()!!.string()
if (response.isSuccessful) {
log.info("Successfully posted the bot data to carbonitex.com: {}", content)
} else {
log.warn("Failed to post stats to Carbonitex: {}\n{}", response.toString(), content)
}
}
} catch (e: Exception) {
log.error("An error occurred while posting the bot data to carbonitex.com", e)
}
}
companion object {
private val log = LoggerFactory.getLogger(CarbonitexAgent::class.java)
}
}
| mit | 62031144e4091cac8ebfb6ad88560a0e | 36.70297 | 112 | 0.6552 | 4.76 | false | true | false | false |
pkleimann/livingdoc2 | livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/ScenarioExecution.kt | 1 | 5280 | package org.livingdoc.engine.execution.examples.scenarios
import org.livingdoc.api.fixtures.scenarios.Binding
import org.livingdoc.engine.execution.Result
import org.livingdoc.engine.execution.examples.executeWithBeforeAndAfter
import org.livingdoc.engine.execution.examples.scenarios.model.ScenarioResult
import org.livingdoc.engine.execution.examples.scenarios.model.StepResult
import org.livingdoc.engine.fixtures.FixtureMethodInvoker
import org.livingdoc.engine.fixtures.FixtureMethodInvoker.FixtureMethodInvocationException
import org.livingdoc.repositories.model.scenario.Scenario
import java.lang.reflect.Parameter
internal class ScenarioExecution(
private val fixtureClass: Class<*>,
scenario: Scenario,
document: Any?
) {
private val fixtureModel = ScenarioFixtureModel(fixtureClass)
private val scenario = ScenarioResult.from(scenario)
private val methodInvoker = FixtureMethodInvoker(document)
/**
* Executes the configured [Scenario].
*
* Does not throw any kind of exception. Exceptional state of the execution is packaged inside the [ScenarioResult] in
* the form of different result objects.
*/
fun execute(): ScenarioResult {
try {
assertFixtureIsDefinedCorrectly()
executeScenario()
markScenarioAsSuccessfullyExecuted()
} catch (e: Throwable) {
markScenarioAsExecutedWithException(e)
}
setSkippedStatusForAllUnknownResults()
return scenario
}
private fun assertFixtureIsDefinedCorrectly() {
val errors = ScenarioFixtureChecker.check(fixtureModel)
if (errors.isNotEmpty()) {
throw MalformedScenarioFixtureException(fixtureClass, errors)
}
}
private fun executeScenario() {
val fixture = createFixtureInstance()
executeWithBeforeAndAfter(
before = { invokeBeforeMethods(fixture) },
body = { executeSteps(fixture) },
after = { invokeAfterMethods(fixture) }
)
}
private fun executeSteps(fixture: Any) {
var previousResult: Result = Result.Executed
for (step in scenario.steps) {
if (previousResult == Result.Executed) {
executeStep(fixture, step)
previousResult = step.result
} else {
step.result = Result.Skipped
}
}
}
private fun executeStep(fixture: Any, step: StepResult) {
val result = fixtureModel.getMatchingStepTemplate(step.value)
val method = fixtureModel.getStepMethod(result.template)
val parameterList = method.parameters
.map {
result.variables.getOrElse(
getParameterName(it),
{ error("Missing parameter value: ${getParameterName(it)}") })
}
.toTypedArray()
step.result = invokeExpectingException {
methodInvoker.invoke(method, fixture, parameterList)
}
}
private fun getParameterName(parameter: Parameter): String {
return parameter.getAnnotationsByType(Binding::class.java).firstOrNull()?.value
?: parameter.name
}
private fun invokeExpectingException(function: () -> Unit): Result {
return try {
function.invoke()
Result.Executed
} catch (e: AssertionError) {
Result.Failed(e)
} catch (e: Exception) {
Result.Exception(e)
}
}
private fun createFixtureInstance(): Any {
return fixtureClass.newInstance()
}
private fun invokeBeforeMethods(fixture: Any) {
fixtureModel.beforeMethods.forEach { methodInvoker.invoke(it, fixture) }
}
private fun invokeAfterMethods(fixture: Any) {
val exceptions = mutableListOf<Throwable>()
for (afterMethod in fixtureModel.afterMethods) {
try {
methodInvoker.invoke(afterMethod, fixture)
} catch (e: AssertionError) {
exceptions.add(e)
} catch (e: FixtureMethodInvocationException) {
exceptions.add(e.cause!!)
}
}
if (exceptions.isNotEmpty()) throw AfterMethodExecutionException(exceptions)
}
private fun markScenarioAsSuccessfullyExecuted() {
scenario.result = Result.Executed
}
private fun markScenarioAsExecutedWithException(e: Throwable) {
scenario.result = Result.Exception(e)
}
private fun setSkippedStatusForAllUnknownResults() {
for (step in scenario.steps) {
if (step.result === Result.Unknown) {
step.result = Result.Skipped
}
}
}
internal class MalformedScenarioFixtureException(fixtureClass: Class<*>, errors: List<String>) : RuntimeException(
"The fixture class <$fixtureClass> is malformed: \n${errors.joinToString(
separator = "\n",
prefix = " - "
)}"
)
internal class AfterMethodExecutionException(exceptions: List<Throwable>) :
RuntimeException("One or more exceptions were thrown during execution of @After methods") {
init {
exceptions.forEach { addSuppressed(it) }
}
}
}
| apache-2.0 | aa3648ccafbb998db6b7a57df3146462 | 32.846154 | 122 | 0.643939 | 5.019011 | false | false | false | false |
JetBrains/spek | spek-runtime/src/commonMain/kotlin/org/spekframework/spek2/runtime/scope/Path.kt | 1 | 3050 | package org.spekframework.spek2.runtime.scope
import org.spekframework.spek2.runtime.util.Base64
import org.spekframework.spek2.runtime.util.ClassUtil
import kotlin.reflect.KClass
val Path.isRoot: Boolean
get() {
return name.isEmpty() && parent == null
}
// handles two cases
// classToPath -> discoveryRequest.path
// 1: my.package/MyClass -> my.package/MyClass/description
// 2: my.package/MyClass/description -> my.package/MyClass
fun Path.intersects(path: Path) = this.isParentOf(path) || path.isParentOf(this)
data class Path(val name: String, val parent: Path?) {
private val serialized by lazy {
serialize(this)
}
private val humanReadable by lazy {
serialize(this, false)
}
private val encoded by lazy {
encode(name)
}
fun resolve(name: String) = Path(name, this)
fun isParentOf(path: Path): Boolean {
var current: Path? = path
while (current != null) {
if (current == this) {
return true
}
current = current.parent
}
return false
}
fun serialize(): String = serialized
override fun toString(): String {
return humanReadable
}
companion object {
const val PATH_SEPARATOR = '/'
private fun serialize(path: Path, encoded: Boolean = true): String {
return if (path.parent == null) {
// this will be an empty string
path.name
} else {
val name = if (encoded) {
path.encoded
} else {
path.name
}
"${serialize(path.parent, encoded)}$PATH_SEPARATOR$name".trimStart(PATH_SEPARATOR)
}
}
fun encode(name: String): String {
return Base64.encodeToString(name)
}
fun decode(name: String): String {
return Base64.decodeToString(name)
}
}
}
class PathBuilder(private var parent: Path) {
constructor() : this(ROOT)
fun appendPackage(packageName: String): PathBuilder {
packageName.split('.')
.forEach { part -> append(part) }
return this
}
fun append(name: String): PathBuilder {
parent = Path(name, parent)
return this
}
fun build(): Path = parent
companion object {
val ROOT: Path = Path("", null)
fun from(clz: KClass<*>): PathBuilder {
val (packageName, className) = ClassUtil.extractPackageAndClassNames(clz)
val builder = PathBuilder()
if (packageName.isNotEmpty()) {
builder.appendPackage(packageName)
}
return builder
.append(className)
}
fun parse(path: String): PathBuilder {
var builder = PathBuilder()
path.split(Path.PATH_SEPARATOR)
.forEach { builder = builder.append(Path.decode(it)) }
return builder
}
}
}
| bsd-3-clause | d9d3bb60010982f5497bc34fdbbd5e80 | 24.847458 | 98 | 0.562295 | 4.628225 | false | false | false | false |
Tickaroo/tikxml | processor/src/main/java/com/tickaroo/tikxml/processor/field/access/FieldAccessResolver.kt | 1 | 3576 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tickaroo.tikxml.processor.field.access
import com.squareup.javapoet.CodeBlock
import com.tickaroo.tikxml.processor.generator.CodeGeneratorHelper
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.VariableElement
/**
* Base class. This class just stores info about how to set / read a a field from annotation processing generated code.
* (via getter-setter or same field is directly visible)
* @author Hannes Dorfmann
*/
sealed class FieldAccessResolver {
abstract fun resolveAssignment(assignValue: String, vararg arguments: Any): CodeBlock
abstract fun resolveGetterForReadingXml(): String
abstract fun resolveGetterForWritingXml(): String
/**
* Can't access the underlying field directly, hence we need to use the public getter and setter
*/
class GetterSetterFieldAccessResolver(private val getter: ExecutableElement, private val setter: ExecutableElement) : FieldAccessResolver() {
override fun resolveAssignment(assignValue: String, vararg arguments: Any) =
CodeBlock.builder()
.addStatement("${CodeGeneratorHelper.valueParam}.${setter.simpleName}($assignValue)", *arguments)
.build()
override fun resolveGetterForReadingXml() =
"${CodeGeneratorHelper.valueParam}.${getter.simpleName}()"
override fun resolveGetterForWritingXml() = "${CodeGeneratorHelper.valueParam}.${getter.simpleName}()"
}
/**
* Policy that can access the field directly because it has at least package visibility
*/
class MinPackageVisibilityFieldAccessResolver(private val element: VariableElement) : FieldAccessResolver() {
override fun resolveAssignment(assignValue: String, vararg arguments: Any) =
CodeBlock.builder()
.addStatement("${CodeGeneratorHelper.valueParam}.$element = $assignValue", *arguments)
.build()
override fun resolveGetterForReadingXml() = "${CodeGeneratorHelper.valueParam}.$element"
override fun resolveGetterForWritingXml() = "${CodeGeneratorHelper.valueParam}.$element"
}
/**
* Policy that can access the field directly because it has at least package visibility
*/
class ConstructorAndGetterFieldAccessResolver(private val element: VariableElement, private val getter: ExecutableElement) : FieldAccessResolver() {
override fun resolveAssignment(assignValue: String, vararg arguments: Any) =
CodeBlock.builder()
.addStatement("${CodeGeneratorHelper.valueParam}.$element = $assignValue", *arguments)
.build()
override fun resolveGetterForReadingXml() = "${CodeGeneratorHelper.valueParam}.$element"
override fun resolveGetterForWritingXml() = "${CodeGeneratorHelper.valueParam}.${getter.simpleName}()"
}
} | apache-2.0 | 8a8eb04cefdffc897df34eba39baac69 | 41.082353 | 152 | 0.707215 | 5.065156 | false | false | false | false |
google/ground-android | ground/src/test/java/com/google/android/ground/ui/home/mapcontainer/LoiCardSourceTest.kt | 1 | 5301 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.ui.home.mapcontainer
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.ground.BaseHiltTest
import com.google.android.ground.model.geometry.Coordinate
import com.google.android.ground.model.geometry.LineString
import com.google.android.ground.model.geometry.Point
import com.google.android.ground.model.locationofinterest.LocationOfInterest
import com.google.android.ground.repository.LocationOfInterestRepository
import com.google.android.ground.repository.SurveyRepository
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableSet
import com.google.common.truth.Truth.assertThat
import com.jraska.livedata.TestObserver
import com.sharedtest.FakeData
import dagger.hilt.android.testing.HiltAndroidTest
import io.reactivex.Flowable
import java8.util.Optional
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.robolectric.RobolectricTestRunner
// TODO: Add more test coverage
// 1. Switching survey should update list
// 2. Panning should emit values without having to resubscribe
@HiltAndroidTest
@RunWith(RobolectricTestRunner::class)
class LoiCardSourceTest : BaseHiltTest() {
@Mock lateinit var locationOfInterestRepository: LocationOfInterestRepository
@Mock lateinit var surveyRepository: SurveyRepository
private lateinit var loiCardSource: LoiCardSource
private lateinit var loisTestObserver: TestObserver<List<LocationOfInterest>>
@Before
override fun setUp() {
super.setUp()
Mockito.`when`(surveyRepository.activeSurvey)
.thenReturn(Flowable.just(Optional.of(TEST_SURVEY)))
Mockito.`when`(locationOfInterestRepository.getLocationsOfInterestOnceAndStream(TEST_SURVEY))
.thenReturn(Flowable.just(TEST_LOCATIONS_OF_INTEREST))
loiCardSource = LoiCardSource(surveyRepository, locationOfInterestRepository)
loisTestObserver = TestObserver.test(loiCardSource.locationsOfInterest)
}
@Test
fun testLoiCards_whenBoundsNotAvailable_returnsNothing() {
loisTestObserver.assertNoValue()
}
@Test
fun testLoiCards_whenOutOfBounds_returnsEmptyList() {
val southwest = LatLng(-60.0, -60.0)
val northeast = LatLng(-50.0, -50.0)
loiCardSource.onCameraBoundsUpdated(LatLngBounds(southwest, northeast))
assertThat(loisTestObserver.awaitValue().value()).isEmpty()
}
@Test
fun testLoiCards_whenSomeLOIsInsideBounds_returnsPartialList() {
val southwest = LatLng(-20.0, -20.0)
val northeast = LatLng(-10.0, -10.0)
loiCardSource.onCameraBoundsUpdated(LatLngBounds(southwest, northeast))
assertThat(loisTestObserver.value())
.isEqualTo(listOf(TEST_POINT_OF_INTEREST_1, TEST_AREA_OF_INTEREST_1))
}
@Test
fun testLoiCards_whenAllLOIsInsideBounds_returnsCompleteList() {
val southwest = LatLng(-20.0, -20.0)
val northeast = LatLng(20.0, 20.0)
loiCardSource.onCameraBoundsUpdated(LatLngBounds(southwest, northeast))
assertThat(loisTestObserver.value())
.isEqualTo(
listOf(
TEST_POINT_OF_INTEREST_1,
TEST_POINT_OF_INTEREST_2,
TEST_POINT_OF_INTEREST_3,
TEST_AREA_OF_INTEREST_1,
TEST_AREA_OF_INTEREST_2
)
)
}
companion object {
private val COORDINATE_1 = Coordinate(-20.0, -20.0)
private val COORDINATE_2 = Coordinate(0.0, 0.0)
private val COORDINATE_3 = Coordinate(20.0, 20.0)
private val TEST_SURVEY = FakeData.SURVEY
private val TEST_POINT_OF_INTEREST_1 = createPoint("1", COORDINATE_1)
private val TEST_POINT_OF_INTEREST_2 = createPoint("2", COORDINATE_2)
private val TEST_POINT_OF_INTEREST_3 = createPoint("3", COORDINATE_3)
private val TEST_AREA_OF_INTEREST_1 =
createPolygon("4", ImmutableList.of(COORDINATE_1, COORDINATE_2))
private val TEST_AREA_OF_INTEREST_2 =
createPolygon("5", ImmutableList.of(COORDINATE_2, COORDINATE_3))
private val TEST_LOCATIONS_OF_INTEREST =
ImmutableSet.of(
TEST_POINT_OF_INTEREST_1,
TEST_POINT_OF_INTEREST_2,
TEST_POINT_OF_INTEREST_3,
TEST_AREA_OF_INTEREST_1,
TEST_AREA_OF_INTEREST_2
)
private fun createPoint(id: String, coordinate: Coordinate) =
FakeData.LOCATION_OF_INTEREST.copy(
id = id,
geometry = Point(coordinate),
surveyId = TEST_SURVEY.id
)
private fun createPolygon(id: String, coordinates: ImmutableList<Coordinate>) =
FakeData.AREA_OF_INTEREST.copy(
id = id,
geometry = LineString(coordinates),
surveyId = TEST_SURVEY.id
)
}
}
| apache-2.0 | 7729fb49b51a20257ccfdedcf3c8b515 | 34.10596 | 97 | 0.741181 | 3.75691 | false | true | false | false |
google/glance-experimental-tools | appwidget-viewer/src/main/java/com/google/android/glance/tools/viewer/ui/theme/Type.kt | 1 | 1184 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.glance.tools.viewer.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
internal val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
)
| apache-2.0 | 87189fb37aee2d92fd41470043921353 | 33.823529 | 75 | 0.739865 | 4.154386 | false | false | false | false |
cdietze/klay | src/main/kotlin/klay/core/StubPlatform.kt | 1 | 3406 | package klay.core
import klay.core.json.JsonImpl
/**
* A stub implementation of [Platform] that provides implementations of those services that
* can be usefully implemented for unit tests, and throws [UnsupportedOperationException] for
* the rest. This can usefully be extended in tests to provide test implementations for just the
* aspects of the platform that are needed to support the code under test.
*
* The services that are implemented are:
* * [.type] - reports [Platform.Type.STUB]
* * [.time] - returns current time
* * [.invokeLater] - invokes the supplied action immediately on the calling thread
* * [.input] - allows listener registration, never generates events
* * [.log] - writes logs to `stdout`
* * [.json] - provides full JSON parsing and formatting
* * [.storage] - maintains an in-memory storage map
*
*/
class StubPlatform : Platform() {
override val storage = object : Storage {
private val _data = HashMap<String, String>()
override fun setItem(key: String, data: String) {
_data.put(key, data)
}
override fun removeItem(key: String) {
_data.remove(key)
}
override fun getItem(key: String): String? {
return _data[key]
}
override fun startBatch(): Storage.Batch {
return BatchImpl(this)
}
override fun keys(): Iterable<String> {
return _data.keys
}
override val isPersisted: Boolean
get() = true
}
override val input = Input(this)
override val log = object : Log() {
override fun logImpl(level: Log.Level, msg: String, e: Throwable?) {
val prefix: String
when (level) {
Log.Level.DEBUG -> prefix = "D: "
Log.Level.INFO -> prefix = ""
Log.Level.WARN -> prefix = "W: "
Log.Level.ERROR -> prefix = "E: "
}
println()
println(prefix + msg)
e?.printStackTrace()
}
}
override val exec = object : Exec.Default(this) {
override fun isMainThread() = true
override fun invokeLater(action: () -> Unit) {
action()
} // now is later!
}
override val json: Json = JsonImpl()
private val start = currentTimeMillis()
override fun type(): Platform.Type {
return Platform.Type.STUB
}
override fun time(): Double {
return currentTimeMillis().toDouble()
}
override fun tick(): Int {
return (currentTimeMillis() - start).toInt()
}
override fun openURL(url: String) {
throw UnsupportedOperationException()
}
override val assets: Assets
get() = throw UnsupportedOperationException()
override val audio: Audio
get() = throw UnsupportedOperationException()
override val graphics: Graphics
get() = throw UnsupportedOperationException()
override val net: Net
get() = throw UnsupportedOperationException()
}
expect fun StubPlatform.currentTimeMillis(): Long
/** Print the stacktrace of the throwable if platform can, noop if not available. */
expect fun Throwable.printStackTrace()
/** Append the stacktrace of the throwable to the given `appendable` if platform can, noop if not available. */
expect fun Throwable.printStackTrace(appendable: Appendable)
| apache-2.0 | 0f045241925cabab552d5ed17e9ab478 | 30.537037 | 111 | 0.620376 | 4.608931 | false | false | false | false |
alexfu/androidautoversion | src/main/kotlin/com/github/alexfu/AndroidAutoVersionPlugin.kt | 1 | 4738 | package com.github.alexfu
import com.android.build.gradle.AppPlugin
import com.android.build.gradle.LibraryPlugin
import com.github.alexfu.VersionType.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonConfiguration
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.TaskProvider
import java.io.File
private typealias VersionFile = File
private const val LOG_TAG = "[AndroidAutoVersion]"
class AndroidAutoVersionPlugin : Plugin<Project> {
private lateinit var project: Project
private lateinit var version: Version
private lateinit var versionFile: VersionFile
private val json by lazy { Json(JsonConfiguration.Stable) }
override fun apply(project: Project) {
this.project = project
val isAppPlugin = project.plugins.findPlugin(AppPlugin::class.java) != null
val isLibraryPlugin = project.plugins.findPlugin(LibraryPlugin::class.java) != null
check(!isAppPlugin || !isLibraryPlugin) {
"'com.android.application' or 'com.android.library' plugin required."
}
setUp()
createTasks()
}
private fun setUp() {
versionFile = project.file("version")
if (!versionFile.exists()) {
info("Version file does not exist, auto generating a default one.")
Version().writeTo(versionFile)
}
version = versionFile.read()
project.extensions.create("androidAutoVersion", AndroidAutoVersionExtension::class.java, version.versionName, version.buildNumber)
}
private fun createTasks() {
registerTask(
name = "bumpBuild",
description = "Increases build number by 1",
exec = { incrementVersion(BUILD) }
)
val bumpPatchTask = registerTask(
name = "bumpPatch",
description = "Increases patch version by 1",
exec = { incrementVersion(PATCH) }
)
val bumpMinorTask = registerTask(
name = "bumpMinor",
description = "Increases minor version by 1 and zeroes out patch version",
exec = { incrementVersion(MINOR) }
)
val bumpMajorTask = registerTask(
name = "bumpMajor",
description = "Increases major version by 1, zeroes out minor and patch version",
exec = { incrementVersion(MAJOR) }
)
registerTask(
name = "versionPatch",
description = "Executes bumpPatch and commits the changes to git",
dependencies = listOf(bumpPatchTask),
exec = ::commitToGit
)
registerTask(
name = "versionMinor",
description = "Executes bumpMinor and commits the changes to git",
dependencies = listOf(bumpMinorTask),
exec = ::commitToGit
)
registerTask(
name = "versionMajor",
description = "Executes bumpMajor and commits the changes to git",
dependencies = listOf(bumpMajorTask),
exec = ::commitToGit
)
}
private fun incrementVersion(type: VersionType) {
version = version.increment(type)
version.writeTo(versionFile)
}
private fun commitToGit() {
project.exec { setCommandLine("git", "add", versionFile.absolutePath) }
project.exec { setCommandLine("git", "commit", "-m", "Update to $version") }
project.exec { setCommandLine("git", "tag", "v$version") }
}
private fun registerTask(name: String, description: String, dependencies: Iterable<TaskProvider<Task>>? = null, exec: () -> Unit): TaskProvider<Task> {
return project.tasks.register(name) {
group = "AndroidAutoVersion"
setDescription(description)
if (dependencies != null) {
setDependsOn(dependencies)
}
doLast { exec() }
}
}
private fun warn(message: String, error: Throwable?) {
if (error == null) {
project.logger.warn("$LOG_TAG $message")
} else {
project.logger.warn("$LOG_TAG $message", error)
}
}
private fun info(message: String) {
project.logger.info("$LOG_TAG $message")
}
private fun VersionFile.read(): Version {
if (!exists()) return Version()
return try {
json.parse(Version.serializer(), readText())
} catch (error: Error) {
warn("Error reading version file, falling back to default", error)
Version()
}
}
private fun Version.writeTo(file: VersionFile) {
file.writeText(json.stringify(Version.serializer(), this))
}
}
| mit | 3aab863804e24b32f2f10f326b47aa3a | 33.333333 | 155 | 0.617138 | 4.636008 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/features/timer/TimerActivity.kt | 1 | 1898 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.features.timer
import android.os.Bundle
import androidx.fragment.app.Fragment
import de.dreier.mytargets.base.activities.ChildActivityBase
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.utils.Utils
class TimerActivity : ChildActivityBase() {
private var childFragment: Fragment? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
// Create the fragment only when the activity is created for the first time.
// ie. not after orientation changes
childFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG)
if (childFragment == null) {
childFragment = instantiateFragment()
childFragment?.arguments = intent?.extras
}
supportFragmentManager.beginTransaction()
.replace(android.R.id.content, childFragment!!, FRAGMENT_TAG)
.commit()
}
}
override fun onResume() {
super.onResume()
Utils.setShowWhenLocked(this, SettingsManager.timerKeepAboveLockscreen)
}
fun instantiateFragment(): Fragment {
return TimerFragment()
}
companion object {
private const val FRAGMENT_TAG = "fragment"
}
}
| gpl-2.0 | 528200d3dcf18657624a92f829881a94 | 31.724138 | 88 | 0.691781 | 4.891753 | false | false | false | false |
esafirm/android-playground | app/src/main/java/com/esafirm/androidplayground/flipper/MockStorage.kt | 1 | 3153 | package com.esafirm.androidplayground.flipper
import android.content.SharedPreferences
import com.facebook.flipper.plugins.network.NetworkReporter
import com.google.gson.Gson
import java.util.*
interface MockStorage {
fun put(info: PartialRequestInfo, response: NetworkReporter.ResponseInfo)
fun get(info: PartialRequestInfo): NetworkReporter.ResponseInfo?
fun contains(info: PartialRequestInfo): Boolean
fun clear()
}
interface MockAdapter<TARGET> {
fun serializeInfo(info: PartialRequestInfo): TARGET
fun serializerResponse(response: NetworkReporter.ResponseInfo): TARGET
fun deserializeInfo(target: TARGET): PartialRequestInfo
fun deserializeResponse(target: TARGET): NetworkReporter.ResponseInfo
}
class MemoryMockStorage : MockStorage {
private val map: MutableMap<PartialRequestInfo, NetworkReporter.ResponseInfo> = HashMap(0)
override fun put(info: PartialRequestInfo, response: NetworkReporter.ResponseInfo) {
if (!map.containsKey(info)) {
map[info] = response
}
}
override fun get(info: PartialRequestInfo) = map[info]
override fun contains(info: PartialRequestInfo) = map.containsKey(info)
override fun clear() {
map.clear()
}
}
class MockJsonAdapter(private val gson: Gson) : MockAdapter<String> {
override fun serializeInfo(info: PartialRequestInfo): String {
return gson.toJson(info)
}
override fun serializerResponse(response: NetworkReporter.ResponseInfo): String {
return gson.toJson(response)
}
override fun deserializeInfo(target: String): PartialRequestInfo {
return gson.fromJson(target, PartialRequestInfo::class.java)
}
override fun deserializeResponse(target: String): NetworkReporter.ResponseInfo {
return gson.fromJson(target, NetworkReporter.ResponseInfo::class.java)
}
}
class PreferencesBackedMockStorage(
private val pref: SharedPreferences,
private val adapter: MockAdapter<String>,
private val memoryMockStorage: MockStorage = MemoryMockStorage()
) : MockStorage {
override fun put(info: PartialRequestInfo, response: NetworkReporter.ResponseInfo) {
memoryMockStorage.put(info, response)
pref.edit()
.putString(adapter.serializeInfo(info), adapter.serializerResponse(response))
.apply()
}
override fun get(info: PartialRequestInfo): NetworkReporter.ResponseInfo? {
val responseInfo = memoryMockStorage.get(info)
return responseInfo ?: getPref(info)
}
private fun getPref(info: PartialRequestInfo): NetworkReporter.ResponseInfo? {
val key = adapter.serializeInfo(info)
val result = pref.getString(key, null)
return result?.let { adapter.deserializeResponse(result) }
}
override fun contains(info: PartialRequestInfo): Boolean {
return when (val memoryResult = memoryMockStorage.contains(info)) {
true -> memoryResult
false -> pref.contains(adapter.serializeInfo(info))
}
}
override fun clear() {
memoryMockStorage.clear()
pref.edit().clear().apply()
}
} | mit | 4bd892f8f05fc53e01c09aea14ae977f | 31.515464 | 94 | 0.715826 | 4.536691 | false | false | false | false |
google/intellij-community | platform/platform-tests/testSrc/com/intellij/openapi/roots/impl/SdkInProjectFileIndexTest.kt | 1 | 5848 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.roots.impl
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.junit5.RunInEdt
import com.intellij.testFramework.junit5.TestApplication
import com.intellij.testFramework.rules.ProjectModelExtension
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
@TestApplication
@RunInEdt
class SdkInProjectFileIndexTest {
@JvmField
@RegisterExtension
val projectModel: ProjectModelExtension = ProjectModelExtension()
private val fileIndex
get() = ProjectFileIndex.getInstance(projectModel.project)
private lateinit var module: Module
private lateinit var sdkRoot: VirtualFile
@BeforeEach
fun setUp() {
module = projectModel.createModule()
sdkRoot = projectModel.baseProjectDir.newVirtualDirectory("sdk")
}
@Test
fun `sdk roots`() {
val sdkSourcesRoot = projectModel.baseProjectDir.newVirtualDirectory("sdk-sources")
val sdkDocRoot = projectModel.baseProjectDir.newVirtualDirectory("sdk-docs")
val sdk = projectModel.addSdk {
it.addRoot(sdkRoot, OrderRootType.CLASSES)
it.addRoot(sdkSourcesRoot, OrderRootType.SOURCES)
it.addRoot(sdkDocRoot, OrderRootType.DOCUMENTATION)
}
ModuleRootModificationUtil.setModuleSdk(module, sdk)
assertTrue(fileIndex.isInProject(sdkRoot))
assertTrue(fileIndex.isInLibrary(sdkRoot))
assertTrue(fileIndex.isInLibraryClasses(sdkRoot))
assertFalse(fileIndex.isInLibrarySource(sdkRoot))
assertTrue(fileIndex.isInProject(sdkSourcesRoot))
assertTrue(fileIndex.isInLibrary(sdkSourcesRoot))
assertFalse(fileIndex.isInLibraryClasses(sdkSourcesRoot))
assertTrue(fileIndex.isInLibrarySource(sdkSourcesRoot))
assertFalse(fileIndex.isInProject(sdkDocRoot))
}
@Test
fun `add and remove dependency on module SDK`() {
val sdk = projectModel.addSdk {
it.addRoot(sdkRoot, OrderRootType.CLASSES)
}
assertFalse(fileIndex.isInProject(sdkRoot))
ModuleRootModificationUtil.setModuleSdk(module, sdk)
assertTrue(fileIndex.isInProject(sdkRoot))
ModuleRootModificationUtil.setModuleSdk(module, null)
assertFalse(fileIndex.isInProject(sdkRoot))
}
@Test
fun `add and remove dependency on project SDK`() {
val sdk = projectModel.addSdk {
it.addRoot(sdkRoot, OrderRootType.CLASSES)
}
setProjectSdk(sdk)
ModuleRootModificationUtil.setModuleSdk(module, null)
assertFalse(fileIndex.isInProject(sdkRoot))
ModuleRootModificationUtil.setSdkInherited(module)
assertTrue(fileIndex.isInProject(sdkRoot))
ModuleRootModificationUtil.setModuleSdk(module, projectModel.addSdk("different"))
assertFalse(fileIndex.isInProject(sdkRoot))
}
@Test
fun `add and remove SDK referenced from module`() {
val sdk = projectModel.createSdk("unresolved") {
it.addRoot(sdkRoot, OrderRootType.CLASSES)
}
ModuleRootModificationUtil.modifyModel(module) {
it.setInvalidSdk(sdk.name, sdk.sdkType.name)
true
}
doTestSdkAddingAndRemoving(sdk)
}
@Test
fun `add and remove project SDK inherited in module`() {
val sdk = projectModel.createSdk("unresolved") {
it.addRoot(sdkRoot, OrderRootType.CLASSES)
}
runWriteActionAndWait {
ProjectRootManager.getInstance(projectModel.project).setProjectSdkName(sdk.name, sdk.sdkType.name)
}
ModuleRootModificationUtil.setSdkInherited(module)
doTestSdkAddingAndRemoving(sdk)
}
private fun doTestSdkAddingAndRemoving(sdk: Sdk) {
assertFalse(fileIndex.isInProject(sdkRoot))
projectModel.addSdk(sdk)
assertTrue(fileIndex.isInProject(sdkRoot))
removeSdk(sdk)
assertFalse(fileIndex.isInProject(sdkRoot))
}
@Test
fun `add and remove root from module SDK`() {
val sdk = projectModel.addSdk()
ModuleRootModificationUtil.setModuleSdk(module, sdk)
doTestSdkModifications(sdk)
}
@Test
fun `add and remove root from project SDK`() {
val sdk = projectModel.addSdk()
setProjectSdk(sdk)
ModuleRootModificationUtil.setSdkInherited(module)
doTestSdkModifications(sdk)
}
private fun removeSdk(sdk: Sdk) {
runWriteActionAndWait {
ProjectJdkTable.getInstance().removeJdk(sdk)
}
}
private fun setProjectSdk(sdk: Sdk) {
runWriteActionAndWait {
ProjectRootManager.getInstance(projectModel.project).projectSdk = sdk
}
}
private fun doTestSdkModifications(sdk: Sdk) {
assertFalse(fileIndex.isInProject(sdkRoot))
projectModel.modifySdk(sdk) {
it.addRoot(sdkRoot, OrderRootType.CLASSES)
}
assertTrue(fileIndex.isInProject(sdkRoot))
projectModel.modifySdk(sdk) {
it.removeRoot(sdkRoot, OrderRootType.CLASSES)
}
assertFalse(fileIndex.isInProject(sdkRoot))
}
@Test
internal fun `project SDK in project without modules`() {
val sdk = projectModel.addSdk {
it.addRoot(sdkRoot, OrderRootType.CLASSES)
}
setProjectSdk(sdk)
ModuleRootModificationUtil.setModuleSdk(module, null)
assertFalse(fileIndex.isInProject(sdkRoot))
projectModel.removeModule(module)
assertTrue(fileIndex.isInProject(sdkRoot))
}
} | apache-2.0 | cdadbbf0ccf5aa9d9890a929f1eb99af | 31.137363 | 120 | 0.760602 | 4.593873 | false | true | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/to/LinkTest.kt | 2 | 3440 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.to
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import org.apache.causeway.client.kroviz.handler.ActionHandler
import org.apache.causeway.client.kroviz.snapshots.demo2_0_0.Response2Handler
import org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0.ACTIONS_CREATE
import kotlin.test.*
class LinkTest {
@Test
fun testParse() {
//given
val jsonStr = """{
"rel": "R",
"href": "H",
"method": "GET",
"type": "TY",
"title": "TI"
}"""
// when
val link: Link = Json.decodeFromString(jsonStr)
// then
assertEquals("R", link.rel)
}
@Test
fun testArgumentsCanHaveEmptyKeys() {
val href = "href"
val arg = Argument(href)
val args = mutableMapOf<String, Argument?>()
args.put("", arg)
val l = Link(arguments = args, href = href)
// then
val arguments = l.argMap()!!
val a = arguments[""]
assertEquals("href", a!!.key)
}
@Test
fun testFindRelation() {
//given
var rel: Relation?
//when
rel = Relation.find("menuBars")
//then
assertEquals(Relation.MENU_BARS, rel)
//when
rel = Relation.find("self")
//then
assertEquals(Relation.SELF, rel)
//when
rel = Relation.find("services")
//then
assertEquals(Relation.SERVICES, rel)
}
@Test
fun testFindParsedLinkEnums() {
//given
val map = Response2Handler.map
//when
map.forEach { rh ->
val jsonStr = rh.key.str
val ro = rh.value.parse(jsonStr)
if (ro is WithLinks) {
val links = ro.links
links.forEach { l ->
try {
l.relation()
l.representation()
} catch (e: NullPointerException) {
console.log(l.href)
fail("${rh.key} Relation/Represention of $l fails")
}
}
}
}
//then
assertTrue(true, "no exception in loop")
}
@Test
fun testSimpleType() {
//given
val jsonStr = ACTIONS_CREATE.str
val action = ActionHandler().parse(jsonStr) as Action
val link = action.getSelfLink()
//when
val actual = link.simpleType()
//then
assertSame("object-action", actual)
}
}
| apache-2.0 | 23856d71cb48ae00e2df87c81a21ede4 | 28.152542 | 81 | 0.570058 | 4.359949 | false | true | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RestrictedRetentionForExpressionAnnotationFactory.kt | 2 | 5642 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
object RestrictedRetentionForExpressionAnnotationFactory : KotlinIntentionActionsFactory() {
private val sourceRetention = "${StandardNames.FqNames.annotationRetention.asString()}.${AnnotationRetention.SOURCE.name}"
private val sourceRetentionAnnotation = "@${StandardNames.FqNames.retention.asString()}($sourceRetention)"
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return emptyList()
val containingClass = annotationEntry.containingClass() ?: return emptyList()
val retentionAnnotation = containingClass.annotation(StandardNames.FqNames.retention)
val targetAnnotation = containingClass.annotation(StandardNames.FqNames.target)
val expressionTargetArgument = if (targetAnnotation != null) findExpressionTargetArgument(targetAnnotation) else null
return listOfNotNull(
if (expressionTargetArgument != null) RemoveExpressionTargetFix(expressionTargetArgument) else null,
if (retentionAnnotation == null) AddSourceRetentionFix(containingClass) else ChangeRetentionToSourceFix(retentionAnnotation)
)
}
private fun KtClass.annotation(fqName: FqName): KtAnnotationEntry? {
return annotationEntries.firstOrNull {
it.typeReference?.text?.endsWith(fqName.shortName().asString()) == true
&& analyze()[BindingContext.TYPE, it.typeReference]?.constructor?.declarationDescriptor?.fqNameSafe == fqName
}
}
private fun findExpressionTargetArgument(targetAnnotation: KtAnnotationEntry): KtValueArgument? {
val valueArgumentList = targetAnnotation.valueArgumentList ?: return null
if (targetAnnotation.lambdaArguments.isNotEmpty()) return null
for (valueArgument in valueArgumentList.arguments) {
val argumentExpression = valueArgument.getArgumentExpression() ?: continue
if (argumentExpression.text.contains(KotlinTarget.EXPRESSION.toString())) {
return valueArgument
}
}
return null
}
private class AddSourceRetentionFix(element: KtClass) : KotlinQuickFixAction<KtClass>(element) {
override fun getText() = KotlinBundle.message("add.source.retention")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val added = element.addAnnotationEntry(KtPsiFactory(element).createAnnotationEntry(sourceRetentionAnnotation))
ShortenReferences.DEFAULT.process(added)
}
}
private class ChangeRetentionToSourceFix(retentionAnnotation: KtAnnotationEntry) :
KotlinQuickFixAction<KtAnnotationEntry>(retentionAnnotation) {
override fun getText() = KotlinBundle.message("change.existent.retention.to.source")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val retentionAnnotation = element ?: return
val psiFactory = KtPsiFactory(retentionAnnotation)
val added = if (retentionAnnotation.valueArgumentList == null) {
retentionAnnotation.add(psiFactory.createCallArguments("($sourceRetention)")) as KtValueArgumentList
} else {
if (retentionAnnotation.valueArguments.isNotEmpty()) {
retentionAnnotation.valueArgumentList?.removeArgument(0)
}
retentionAnnotation.valueArgumentList?.addArgument(psiFactory.createArgument(sourceRetention))
}
if (added != null) {
ShortenReferences.DEFAULT.process(added)
}
}
}
private class RemoveExpressionTargetFix(expressionTargetArgument: KtValueArgument) :
KotlinQuickFixAction<KtValueArgument>(expressionTargetArgument) {
override fun getText() = KotlinBundle.message("remove.expression.target")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val expressionTargetArgument = element ?: return
val argumentList = expressionTargetArgument.parent as? KtValueArgumentList ?: return
if (argumentList.arguments.size == 1) {
val annotation = argumentList.parent as? KtAnnotationEntry ?: return
annotation.delete()
} else {
argumentList.removeArgument(expressionTargetArgument)
}
}
}
}
| apache-2.0 | f887ff5d76282bb9c7a30b099da3f57e | 48.06087 | 158 | 0.72368 | 5.642 | false | false | false | false |
google/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/tests/testData/unknownPropertyType/after/gen/UnknownPropertyTypeEntityImpl.kt | 1 | 6149 | package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import java.util.Date
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class UnknownPropertyTypeEntityImpl(val dataSource: UnknownPropertyTypeEntityData) : UnknownPropertyTypeEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val date: Date
get() = dataSource.date
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: UnknownPropertyTypeEntityData?) : ModifiableWorkspaceEntityBase<UnknownPropertyTypeEntity>(), UnknownPropertyTypeEntity.Builder {
constructor() : this(UnknownPropertyTypeEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity UnknownPropertyTypeEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDateInitialized()) {
error("Field UnknownPropertyTypeEntity#date should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as UnknownPropertyTypeEntity
this.entitySource = dataSource.entitySource
this.date = dataSource.date
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var date: Date
get() = getEntityData().date
set(value) {
checkModificationAllowed()
getEntityData().date = value
changedProperty.add("date")
}
override fun getEntityData(): UnknownPropertyTypeEntityData = result ?: super.getEntityData() as UnknownPropertyTypeEntityData
override fun getEntityClass(): Class<UnknownPropertyTypeEntity> = UnknownPropertyTypeEntity::class.java
}
}
class UnknownPropertyTypeEntityData : WorkspaceEntityData<UnknownPropertyTypeEntity>() {
lateinit var date: Date
fun isDateInitialized(): Boolean = ::date.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<UnknownPropertyTypeEntity> {
val modifiable = UnknownPropertyTypeEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): UnknownPropertyTypeEntity {
return getCached(snapshot) {
val entity = UnknownPropertyTypeEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return UnknownPropertyTypeEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return UnknownPropertyTypeEntity(date, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as UnknownPropertyTypeEntityData
if (this.entitySource != other.entitySource) return false
if (this.date != other.date) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as UnknownPropertyTypeEntityData
if (this.date != other.date) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + date.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + date.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.date?.let { collector.addDataToInspect(it) }
collector.sameForAllEntities = true
}
}
| apache-2.0 | d44321ea505c2bac977792d68ed9c1ff | 31.026042 | 157 | 0.734266 | 5.384413 | false | false | false | false |
thomasgalvin/Featherfall | src/main/kotlin/galvin/ff/Passwords.kt | 1 | 7131 | package galvin.ff
import org.mindrot.jbcrypt.BCrypt
import java.io.IOException
import java.security.cert.X509Certificate
import java.security.cert.CertificateFactory
import java.io.FileInputStream
import java.io.File
fun validate( password: String?, hash: String? ): Boolean{
if( password == null || isBlank(password) ){
return false
}
if( hash == null || isBlank(hash) ){
return false
}
return BCrypt.checkpw( password, hash )
}
fun hash( password: String): String{
return BCrypt.hashpw( password, BCrypt.gensalt() )
}
data class PasswordValidation( val passwordEmpty: Boolean = false,
val passwordTooShort: Boolean = false,
val tooFewLowerCase: Boolean = false,
val tooFewUpperCase: Boolean = false,
val tooFewDigits: Boolean = false,
val tooFewSpecialCharacters: Boolean = false,
val repeatedCharacters: Boolean = false,
val foundOnBlacklist: Boolean = false,
val passwordMismatch: Boolean = false ){
fun invalidPassword(): Boolean{
return passwordEmpty
|| passwordTooShort
|| tooFewLowerCase
|| tooFewUpperCase
|| tooFewDigits
|| tooFewSpecialCharacters
|| repeatedCharacters
|| foundOnBlacklist
|| passwordMismatch
}
}
data class PasswordRequirements(val minLength: Int = 0,
val minLowerCase: Int = 0,
val minUpperCase: Int = 0,
val minDigits: Int = 0,
val minSpecialCharacters: Int = 0,
val repeatedCharactersAllowed: Boolean = true,
val validatedAgainstBlacklist: Boolean = true ){
private val badPasswordFile = "galvin/ff/bad-passwords.txt"
private val badPasswords = mutableMapOf<String, Boolean>()
fun validate( password: String ): PasswordValidation {
val chars = password.toCharArray()
val foundOnBlacklist = if(!validatedAgainstBlacklist) false else foundOnBlacklist(password)
val repeatedCharacters = if(!repeatedCharactersAllowed) repeatedCharacters(chars) else false
return PasswordValidation(
passwordEmpty = isBlank(password),
passwordTooShort = tooShort(password),
tooFewLowerCase = tooFewLowerCase(chars),
tooFewUpperCase = tooFewUpperCase(chars),
tooFewDigits = tooFewDigits(chars),
tooFewSpecialCharacters = tooFewSpecialCharacters(chars),
repeatedCharacters = repeatedCharacters,
foundOnBlacklist = foundOnBlacklist )
}
private fun tooShort( password: String ): Boolean{
return password.length < minLength
}
private fun tooFewLowerCase(chars: CharArray): Boolean {
val count = chars.count { Character.isLowerCase(it) }
return count < minLowerCase
}
private fun tooFewUpperCase(chars: CharArray): Boolean {
val count = chars.count { Character.isUpperCase(it) }
return count < minUpperCase
}
private fun tooFewDigits(chars: CharArray): Boolean {
val count = chars.count { Character.isDigit(it) }
return count < minDigits
}
private fun tooFewSpecialCharacters(chars: CharArray): Boolean {
val count = chars.count { !Character.isAlphabetic(it.toInt()) && !Character.isDigit(it) }
return count < minSpecialCharacters
}
private fun repeatedCharacters(chars: CharArray): Boolean {
if (chars.size < 2) {
return false
}
var previous = chars[0]
for (i in 1 until chars.size) {
if (previous == chars[i]) {
return true
}
previous = chars[i]
}
return false
}
private fun foundOnBlacklist(password: String): Boolean {
doLoadBlacklist()
return badPasswords.containsKey(password)
}
private fun doLoadBlacklist() {
synchronized(this) {
if (badPasswords.isEmpty()) {
try {
val lines = loadBlacklist()
for (line in lines) {
badPasswords[line] = java.lang.Boolean.TRUE
}
} catch (ioe: IOException) {
ioe.printStackTrace()
println("Unable to load password blacklist" )
}
}
}
}
fun loadBlacklist(): List<String> {
val list = loadResourceAndReadLines(badPasswordFile)
val badPasswords = list.filter { !isBlank(it) && !it.startsWith("#") }
return badPasswords
}
}
fun parsePKI( x509: X509Certificate ): CertificateData{
val serialNumber = if(x509.serialNumber == null) "" else "${x509.serialNumber}"
val tokens = getDistinguishedNameTokens(x509.subjectX500Principal.name)
return CertificateData(
credential = getCredentialID(x509),
serialNumber = serialNumber,
distinguishedName = x509.subjectX500Principal.name,
countryCode = neverNull( tokens["countryName"] ),
citizenship = neverNull( tokens["COUNTRY_OF_CITIZENSHIP"] )
)
}
fun getCredentialID( x509: X509Certificate ): String{
val hash = x509.issuerX500Principal.hashCode()
val serial = x509.serialNumber
val credentialName = getCredentialName( x509 )
return "$hash::$serial::$credentialName"
}
fun getCredentialName( x509: X509Certificate ): String{
val distinguishedName = x509.subjectX500Principal.name
val nameIndex = distinguishedName.indexOf( "CN=" )
if( nameIndex < 0 ) return distinguishedName
val separatorIndex = distinguishedName.indexOf(',', nameIndex)
return if (separatorIndex < 0) {
distinguishedName.substring(nameIndex + 3)
} else {
distinguishedName.substring(nameIndex + 3, separatorIndex)
}
}
fun getDistinguishedNameTokens( dn: String ): Map<String, String>{
val result = mutableMapOf<String, String>()
val tokens = dn.split( "," )
for( token in tokens ){
if( token.contains("=") ){
val nameValue = token.split(",")
if( nameValue.size == 2){
result[ nameValue[0] ] = nameValue[1]
}
}
}
return result
}
fun loadCertificateFromFile(file: File): X509Certificate {
val stream = FileInputStream(file)
val certFactory = CertificateFactory.getInstance("X.509")
val cert = certFactory.generateCertificate(stream) as X509Certificate
stream.close()
return cert
}
data class CertificateData( val credential: String = "", val serialNumber: String = "", val distinguishedName: String = "",
val countryCode: String = "", val citizenship: String = "" )
| apache-2.0 | a68974a038030db160d7f7e00bdfb977 | 34.128079 | 123 | 0.597392 | 4.857629 | false | false | false | false |
vhromada/Catalog | core/src/main/kotlin/com/github/vhromada/catalog/validator/impl/PictureValidatorImpl.kt | 1 | 1271 | package com.github.vhromada.catalog.validator.impl
import com.github.vhromada.catalog.common.exception.InputException
import com.github.vhromada.catalog.common.result.Event
import com.github.vhromada.catalog.common.result.Result
import com.github.vhromada.catalog.common.result.Severity
import com.github.vhromada.catalog.entity.ChangePictureRequest
import com.github.vhromada.catalog.validator.PictureValidator
import org.springframework.stereotype.Component
/**
* A class represents implementation of validator for pictures.
*
* @author Vladimir Hromada
*/
@Component("pictureValidator")
class PictureValidatorImpl : PictureValidator {
override fun validateRequest(request: ChangePictureRequest) {
val result = Result<Unit>()
when {
request.content == null -> {
result.addEvent(event = Event(severity = Severity.ERROR, key = "PICTURE_CONTENT_NULL", message = "Content mustn't be null."))
}
request.content.isEmpty() -> {
result.addEvent(event = Event(severity = Severity.ERROR, key = "PICTURE_CONTENT_EMPTY", message = "Content mustn't be empty."))
}
}
if (result.isError()) {
throw InputException(result = result)
}
}
}
| mit | 8c6402f967bfff1e850c03027b4860f0 | 36.382353 | 143 | 0.698662 | 4.428571 | false | false | false | false |
apollographql/apollo-android | apollo-ast/src/main/kotlin/com/apollographql/apollo3/ast/check_key_fields.kt | 1 | 3606 | package com.apollographql.apollo3.ast
private class CheckKeyFieldsScope(
val schema: Schema,
val allFragmentDefinitions: Map<String, GQLFragmentDefinition>,
)
fun checkKeyFields(operation: GQLOperationDefinition, schema: Schema, allFragmentDefinitions: Map<String, GQLFragmentDefinition>) {
val parentType = operation.rootTypeDefinition(schema)!!.name
CheckKeyFieldsScope(schema, allFragmentDefinitions).checkField("Operation(${operation.name})", operation.selectionSet.selections, parentType)
}
fun checkKeyFields(fragmentDefinition: GQLFragmentDefinition, schema: Schema, allFragmentDefinitions: Map<String, GQLFragmentDefinition>) {
CheckKeyFieldsScope(schema, allFragmentDefinitions).checkField("Fragment(${fragmentDefinition.name})", fragmentDefinition.selectionSet.selections, fragmentDefinition.typeCondition.name)
}
private fun CheckKeyFieldsScope.checkField(
path: String,
selections: List<GQLSelection>,
parentType: String,
) {
schema.typeDefinitions.values.filterIsInstance<GQLObjectTypeDefinition>().forEach {
checkFieldSet(path, selections, parentType, it.name)
}
}
private fun CheckKeyFieldsScope.checkFieldSet(path: String, selections: List<GQLSelection>, parentType: String, possibleType: String) {
val implementedTypes = schema.implementedTypes(possibleType)
val mergedFields = collectFields(selections, parentType, implementedTypes).groupBy {
it.field.name
}.values
if (implementedTypes.contains(parentType)) {
// only check types that are actually possible
val fieldNames = mergedFields.map { it.first().field }
.filter { it.alias == null }
.map { it.name }.toSet()
val keyFieldNames = schema.keyFields(possibleType)
val missingFieldNames = keyFieldNames.subtract(fieldNames)
check(missingFieldNames.isEmpty()) {
"Key Field(s) '$missingFieldNames' are not queried on $possibleType at $path"
}
}
mergedFields.forEach {
val first = it.first()
val rawTypeName = first.field.definitionFromScope(schema, first.parentType)!!.type.leafType().name
checkField(path + "." + first.field.name, it.flatMap { it.field.selectionSet?.selections ?: emptyList() }, rawTypeName)
}
}
private class FieldWithParent(val field: GQLField, val parentType: String)
private fun CheckKeyFieldsScope.collectFields(
selections: List<GQLSelection>,
parentType: String,
implementedTypes: Set<String>,
): List<FieldWithParent> {
if (!implementedTypes.contains(parentType)) {
return emptyList()
}
return selections.flatMap {
when (it) {
is GQLField -> {
if (it.directives.hasCondition()) {
return@flatMap emptyList()
}
listOf(FieldWithParent(it, parentType))
}
is GQLInlineFragment -> {
if (it.directives.hasCondition()) {
return@flatMap emptyList()
}
collectFields(it.selectionSet.selections, it.typeCondition.name, implementedTypes)
}
is GQLFragmentSpread -> {
if (it.directives.hasCondition()) {
return@flatMap emptyList()
}
val fragmentDefinition = allFragmentDefinitions[it.name]!!
collectFields(fragmentDefinition.selectionSet.selections, fragmentDefinition.typeCondition.name, implementedTypes)
}
}
}
}
private fun List<GQLDirective>?.hasCondition(): Boolean {
return this?.any {
it.name == "skip" && (it.arguments!!.arguments.first().value as? GQLStringValue)?.value != "false"
|| it.name == "include" && (it.arguments!!.arguments.first().value as? GQLStringValue)?.value != "true"
} ?: false
} | mit | ce567648b358a564fa27b09b69199235 | 36.185567 | 187 | 0.721298 | 4.27758 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/util/src/org/jetbrains/kotlin/util/CollectionUtils.kt | 1 | 1941 | // 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.util
import org.jetbrains.annotations.ApiStatus
import java.util.*
inline fun <T, R> Collection<T>.mapAll(transform: (T) -> R?): List<R>? {
val result = ArrayList<R>(this.size)
for (item in this) {
result += transform(item) ?: return null
}
return result
}
fun <K, V> merge(vararg maps: Map<K, V>?): Map<K, V> {
val result = mutableMapOf<K, V>()
for (map in maps) {
if (map != null) {
result.putAll(map)
}
}
return result
}
@ApiStatus.Internal
@Suppress("UNCHECKED_CAST")
inline fun <reified T> Sequence<*>.takeWhileIsInstance(): Sequence<T> = takeWhile { it is T } as Sequence<T>
@ApiStatus.Internal
fun <T> Sequence<T>.takeWhileInclusive(predicate: (T) -> Boolean): Sequence<T> =
sequence {
for (elem in this@takeWhileInclusive) {
yield(elem)
if (!predicate(elem)) break
}
}
/**
* Returns a [List] containing the first elements satisfying [predicate], as well as the subsequent first element for which [predicate] is
* not satisfied (if such an element exists).
*/
fun <T> List<T>.takeWhileInclusive(predicate: (T) -> Boolean): List<T> {
val inclusiveIndex = indexOfFirst { !predicate(it) }
if (inclusiveIndex == -1) {
// Needs to return a defensive copy because `takeWhile` is expected to return a new list.
return toList()
}
return slice(0..inclusiveIndex)
}
/**
* Sorted by [selector] or preserves the order for elements where [selector] returns the same result
*/
@ApiStatus.Internal
fun <T, R : Comparable<R>> Sequence<T>.sortedConservativelyBy(selector: (T) -> R?): Sequence<T> =
withIndex()
.sortedWith(compareBy({ (_, value) -> selector(value) }, IndexedValue<T>::index))
.map(IndexedValue<T>::value)
| apache-2.0 | 24d68545bf0a1ff8fb86fe07f52bbaab | 32.465517 | 138 | 0.64915 | 3.725528 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/yesod/hamlet/parser/HamletParser.kt | 1 | 7056 | package org.jetbrains.yesod.hamlet.parser
/**
* @author Leyla H
*/
import com.intellij.lang.PsiParser
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IElementType
import com.intellij.lang.PsiBuilder
import com.intellij.lang.PsiBuilder.Marker
import com.intellij.lang.ASTNode
import com.intellij.psi.tree.TokenSet
class HamletParser : PsiParser {
override fun parse(root: IElementType, psiBuilder: PsiBuilder): ASTNode {
val rootmMarker = psiBuilder.mark()
parseText(psiBuilder)
rootmMarker.done(root)
return psiBuilder.treeBuilt
}
fun parseText(psiBuilder: PsiBuilder) {
while (!psiBuilder.eof()) {
val token = psiBuilder.tokenType
if (token == HamletTokenTypes.OANGLE) {
parseTag(psiBuilder)
} else if (token == HamletTokenTypes.STRING) {
parseString(psiBuilder)
} else if (token == HamletTokenTypes.DOCTYPE) {
parseDoctype(psiBuilder)
} else if (token == HamletTokenTypes.OPERATOR) {
parseOperator(psiBuilder)
} else if (token == HamletTokenTypes.COMMENT) {
parseCommentInLine(psiBuilder)
} else if (token == HamletTokenTypes.COMMENT_START) {
parseCommentWithEnd(psiBuilder)
} else if (token == HamletTokenTypes.INTERPOLATION) {
parseInterpolation(psiBuilder)
} else if (token == HamletTokenTypes.ESCAPE) {
parseEscape(psiBuilder)
} else {
parseAny(psiBuilder)
}
}
}
fun parseAttributeValue(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.ATTRIBUTE_VALUE)
}
fun parseTag(psiBuilder: PsiBuilder) {
psiBuilder.advanceLexer()
var tokenType = psiBuilder.tokenType
if (tokenType == HamletTokenTypes.SLASH) {
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.TAG)
}
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.TAG)
tokenType = psiBuilder.tokenType
while (tokenType != HamletTokenTypes.CANGLE) {
if (tokenType == HamletTokenTypes.DOT_IDENTIFIER) {
parseDotIdentifier(psiBuilder)
} else if (tokenType == HamletTokenTypes.IDENTIFIER) {
parseAttribute(psiBuilder)
} else if (tokenType == HamletTokenTypes.EQUAL) {
parseEqual(psiBuilder)
} else if (tokenType == HamletTokenTypes.COLON_IDENTIFIER) {
parseColonIdentifier(psiBuilder)
} else if (tokenType == HamletTokenTypes.SHARP_IDENTIFIER) {
parseSharpIdentifier(psiBuilder)
} else if (tokenType == HamletTokenTypes.INTERPOLATION) {
parseInterpolation(psiBuilder)
} else if (tokenType == HamletTokenTypes.STRING) {
parseString(psiBuilder)
} else if (tokenType == HamletTokenTypes.ESCAPE) {
parseEscape(psiBuilder)
} else {
parseAny(psiBuilder)
}
tokenType = psiBuilder.tokenType
}
}
fun parseEqual(psiBuilder: PsiBuilder) {
psiBuilder.advanceLexer()
val next = psiBuilder.tokenType
if (next == HamletTokenTypes.STRING) {
parseString(psiBuilder)
} else if (next == HamletTokenTypes.INTERPOLATION) {
parseInterpolation(psiBuilder)
} else if (next == HamletTokenTypes.CANGLE) {
return
} else {
parseAttributeValue(psiBuilder)
}
}
fun parseAttribute(psiBuilder: PsiBuilder) {
val marker = psiBuilder.mark()
psiBuilder.advanceLexer()
marker.done(HamletTokenTypes.ATTRIBUTE)
}
fun parseDoctype(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
parseUntil(psiBuilder)
tagMarker.done(HamletTokenTypes.DOCTYPE)
}
fun parseInterpolation(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.INTERPOLATION)
while (!psiBuilder.eof()) {
val token = psiBuilder.tokenType
if (token == HamletTokenTypes.END_INTERPOLATION) {
parseEndInterpolation(psiBuilder)
break
} else
parseAny(psiBuilder)
}
}
fun parseDotIdentifier(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.DOT_IDENTIFIER)
}
fun parseEndInterpolation(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.END_INTERPOLATION)
}
fun parseSharpIdentifier(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.SHARP_IDENTIFIER)
}
fun parseColonIdentifier(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.COLON_IDENTIFIER)
}
fun parseOperator(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.OPERATOR)
}
fun parseString(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.STRING)
}
fun parseCommentInLine(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
parseUntil(psiBuilder)
tagMarker.done(HamletTokenTypes.COMMENT)
}
fun parseCommentWithEnd(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
while (!psiBuilder.eof()) {
val token = psiBuilder.tokenType
if (token == HamletTokenTypes.COMMENT_END) {
psiBuilder.advanceLexer()
break
}
parseAny(psiBuilder)
}
tagMarker.done(HamletTokenTypes.COMMENT)
}
fun parseEscape(psiBuilder: PsiBuilder) {
val tagMarker = psiBuilder.mark()
psiBuilder.advanceLexer()
tagMarker.done(HamletTokenTypes.ESCAPE)
}
fun parseUntil(psiBuilder: PsiBuilder) {
while (!psiBuilder.eof()) {
val token = psiBuilder.tokenType
if (token == HamletTokenTypes.NEWLINE) {
psiBuilder.advanceLexer()
break
}
parseAny(psiBuilder)
}
}
fun parseAny(psiBuilder: PsiBuilder) {
val marker = psiBuilder.mark()
psiBuilder.advanceLexer()
marker.done(HamletTokenTypes.ANY)
}
}
| apache-2.0 | d0b7f8aa08be376550ecb47270b7d0fb | 31.666667 | 77 | 0.615221 | 4.564036 | false | false | false | false |
exercism/xkotlin | exercises/practice/wordy/.meta/src/reference/kotlin/Wordy.kt | 1 | 1855 | import java.util.regex.Pattern
import kotlin.math.pow
object Wordy {
private val startPattern = Pattern.compile("^What is (-?\\d+)(.*)\\?$")
private val operandPattern = Pattern.compile("^ ([^-0-9]+) (-?\\d+)(.*)$")
private val powerPattern = Pattern.compile("^ raised to the (-?\\d+)(st|nd|rd|th) power(.*)$")
fun answer(input: String): Int {
val startMatcher = startPattern.matcher(input)
require(startMatcher.find())
val firstNumber = startMatcher.group(1).toInt()
val rest = startMatcher.group(2)
return answerRecursive(rest, firstNumber)
}
private fun answerRecursive(input: String, result: Int): Int {
val operandMatcher = operandPattern.matcher(input)
val powerMatcher = powerPattern.matcher(input)
return when {
powerMatcher.find() -> {
val operand = powerMatcher.group(1).toInt()
val rest = powerMatcher.group(3)
answerRecursive(rest, result.toDouble().pow(operand.toDouble()).toInt())
}
operandMatcher.find() -> {
val operator = operandMatcher.group(1)
val operand = operandMatcher.group(2).toInt()
val rest = operandMatcher.group(3)
when (operator) {
"plus" -> answerRecursive(rest, result + operand)
"minus" -> answerRecursive(rest, result - operand)
"multiplied by" -> answerRecursive(rest, result * operand)
"divided by" -> answerRecursive(rest, result / operand)
else -> throw IllegalArgumentException("Unknown operator '$operator'!")
}
}
input.isEmpty() -> result
else -> throw IllegalArgumentException("Cannot parse '$input'!")
}
}
}
| mit | 1c124df4d8669c35d084a0e1b3b3e9f7 | 42.139535 | 98 | 0.57035 | 4.591584 | false | false | false | false |
allotria/intellij-community | platform/credential-store/src/PasswordSafeImpl.kt | 2 | 9953 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("PackageDirectoryMismatch")
package com.intellij.ide.passwordSafe.impl
import com.intellij.configurationStore.SettingsSavingComponent
import com.intellij.credentialStore.*
import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException
import com.intellij.credentialStore.keePass.*
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.ide.passwordSafe.PasswordStorage
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.serviceContainer.NonInjectable
import com.intellij.util.concurrency.SynchronizedClearableLazy
import com.intellij.util.pooledThreadSingleAlarm
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.runAsync
import java.io.Closeable
import java.nio.file.Path
import java.nio.file.Paths
open class BasePasswordSafe @NonInjectable constructor(val settings: PasswordSafeSettings, provider: CredentialStore? = null /* TestOnly */) : PasswordSafe() {
@Suppress("unused")
constructor() : this(service<PasswordSafeSettings>(), null)
override var isRememberPasswordByDefault: Boolean
get() = settings.state.isRememberPasswordByDefault
set(value) {
settings.state.isRememberPasswordByDefault = value
}
private val _currentProvider = SynchronizedClearableLazy { computeProvider(settings) }
protected val currentProviderIfComputed: CredentialStore?
get() = if (_currentProvider.isInitialized()) _currentProvider.value else null
internal var currentProvider: CredentialStore
get() = _currentProvider.value
set(value) {
_currentProvider.value = value
}
internal fun closeCurrentStore(isSave: Boolean, isEvenMemoryOnly: Boolean) {
val store = currentProviderIfComputed ?: return
if (!isEvenMemoryOnly && store is InMemoryCredentialStore) {
return
}
_currentProvider.drop()
if (isSave && store is KeePassCredentialStore) {
try {
store.save(createMasterKeyEncryptionSpec())
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.warn(e)
}
}
else if (store is Closeable) {
store.close()
}
}
internal fun createMasterKeyEncryptionSpec(): EncryptionSpec {
val pgpKey = settings.state.pgpKeyId
return when (pgpKey) {
null -> EncryptionSpec(type = getDefaultEncryptionType(), pgpKeyId = null)
else -> EncryptionSpec(type = EncryptionType.PGP_KEY, pgpKeyId = pgpKey)
}
}
// it is helper storage to support set password as memory-only (see setPassword memoryOnly flag)
protected val memoryHelperProvider: Lazy<CredentialStore> = lazy { InMemoryCredentialStore() }
override val isMemoryOnly: Boolean
get() = settings.providerType == ProviderType.MEMORY_ONLY
init {
provider?.let {
currentProvider = it
}
}
override fun get(attributes: CredentialAttributes): Credentials? {
val value = currentProvider.get(attributes)
if ((value == null || value.password.isNullOrEmpty()) && memoryHelperProvider.isInitialized()) {
// if password was set as `memoryOnly`
memoryHelperProvider.value.get(attributes)?.let {
return it
}
}
return value
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
currentProvider.set(attributes, credentials)
if (attributes.isPasswordMemoryOnly && !credentials?.password.isNullOrEmpty()) {
// we must store because otherwise on get will be no password
memoryHelperProvider.value.set(attributes.toPasswordStoreable(), credentials)
}
else if (memoryHelperProvider.isInitialized()) {
memoryHelperProvider.value.set(attributes, null)
}
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?, memoryOnly: Boolean) {
if (memoryOnly) {
memoryHelperProvider.value.set(attributes.toPasswordStoreable(), credentials)
// remove to ensure that on getPassword we will not return some value from default provider
currentProvider.set(attributes, null)
}
else {
set(attributes, credentials)
}
}
// maybe in the future we will use native async, so, this method added here instead "if need, just use runAsync in your code"
override fun getAsync(attributes: CredentialAttributes): Promise<Credentials?> = runAsync { get(attributes) }
open suspend fun save() {
val keePassCredentialStore = currentProviderIfComputed as? KeePassCredentialStore ?: return
keePassCredentialStore.save(createMasterKeyEncryptionSpec())
}
override fun isPasswordStoredOnlyInMemory(attributes: CredentialAttributes, credentials: Credentials): Boolean {
if (isMemoryOnly || credentials.password.isNullOrEmpty()) {
return true
}
if (!memoryHelperProvider.isInitialized()) {
return false
}
return memoryHelperProvider.value.get(attributes)?.let {
!it.password.isNullOrEmpty()
} ?: false
}
}
class PasswordSafeImpl : BasePasswordSafe(), SettingsSavingComponent {
// SecureRandom (used to generate master password on first save) can be blocking on Linux
private val saveAlarm = pooledThreadSingleAlarm(delay = 0) {
val currentThread = Thread.currentThread()
ShutDownTracker.getInstance().registerStopperThread(currentThread)
try {
(currentProviderIfComputed as? KeePassCredentialStore)?.save(createMasterKeyEncryptionSpec())
}
finally {
ShutDownTracker.getInstance().unregisterStopperThread(currentThread)
}
}
override suspend fun save() {
val keePassCredentialStore = currentProviderIfComputed as? KeePassCredentialStore ?: return
if (keePassCredentialStore.isNeedToSave()) {
saveAlarm.request()
}
}
@Suppress("unused", "DeprecatedCallableAddReplaceWith")
@get:Deprecated("Do not use it")
@get:ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
// public - backward compatibility
val memoryProvider: PasswordStorage
get() = memoryHelperProvider.value as PasswordStorage
}
internal fun getDefaultKeePassDbFile() = getDefaultKeePassBaseDirectory().resolve(DB_FILE_NAME)
private fun computeProvider(settings: PasswordSafeSettings): CredentialStore {
if (settings.providerType == ProviderType.MEMORY_ONLY || (ApplicationManager.getApplication()?.isUnitTestMode == true)) {
return InMemoryCredentialStore()
}
fun showError(@NlsContexts.NotificationTitle title: String) {
NOTIFICATION_MANAGER.notify(title = title,
content = CredentialStoreBundle.message("notification.content.in.memory.storage"),
action = object: NotificationAction(
CredentialStoreBundle.message("notification.content.password.settings.action")
) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
// to hide before Settings open, otherwise dialog and notification are shown at the same time
notification.expire()
ShowSettingsUtil.getInstance().showSettingsDialog(e.project, PasswordSafeConfigurable::class.java)
}
})
}
if (settings.providerType == ProviderType.KEEPASS) {
try {
val dbFile = settings.keepassDb?.let { Paths.get(it) } ?: getDefaultKeePassDbFile()
return KeePassCredentialStore(dbFile, getDefaultMasterPasswordFile())
}
catch (e: IncorrectMasterPasswordException) {
LOG.warn(e)
showError(if (e.isFileMissed) CredentialStoreBundle.message("notification.title.password.missing")
else CredentialStoreBundle.message("notification.title.password.incorrect"))
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
showError(CredentialStoreBundle.message("notification.title.database.error"))
}
}
else {
try {
val store = createPersistentCredentialStore()
if (store == null) {
showError(CredentialStoreBundle.message("notification.title.keychain.not.available"))
}
else {
return store
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
showError(CredentialStoreBundle.message("notification.title.cannot.use.keychain"))
}
}
settings.providerType = ProviderType.MEMORY_ONLY
return InMemoryCredentialStore()
}
internal fun createPersistentCredentialStore(): CredentialStore? {
for (factory in CredentialStoreFactory.CREDENTIAL_STORE_FACTORY.extensionList) {
return factory.create() ?: continue
}
return null
}
@TestOnly
fun createKeePassStore(dbFile: Path, masterPasswordFile: Path): PasswordSafe {
val store = KeePassCredentialStore(dbFile, masterPasswordFile)
val settings = PasswordSafeSettings()
settings.loadState(PasswordSafeSettings.PasswordSafeOptions().apply {
provider = ProviderType.KEEPASS
keepassDb = store.dbFile.toString()
})
return BasePasswordSafe(settings, store)
}
private fun CredentialAttributes.toPasswordStoreable() = if (isPasswordMemoryOnly) CredentialAttributes(serviceName, userName, requestor) else this | apache-2.0 | 2c5f8850c00c99b5c42d9b6b60193be8 | 37.284615 | 159 | 0.724003 | 4.902956 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/observable/operations/CompoundParallelOperationTrace.kt | 3 | 2740 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.observable.operations
import com.intellij.openapi.diagnostic.Logger
import java.util.concurrent.CopyOnWriteArrayList
class CompoundParallelOperationTrace<Id>(private val debugName: String? = null) {
private val traces = LinkedHashMap<Id, Int>()
private val beforeOperationListeners = CopyOnWriteArrayList<() -> Unit>()
private val afterOperationListeners = CopyOnWriteArrayList<() -> Unit>()
fun isOperationCompleted(): Boolean {
synchronized(this) {
return traces.isEmpty()
}
}
fun startTask(taskId: Id) {
val isOperationCompletedBeforeStart: Boolean
synchronized(this) {
isOperationCompletedBeforeStart = traces.isEmpty()
addTask(taskId)
}
if (isOperationCompletedBeforeStart) {
debug("Operation is started")
beforeOperationListeners.forEach { it() }
}
}
fun finishTask(taskId: Id) {
val isOperationCompletedAfterFinish: Boolean
synchronized(this) {
if (!removeTask(taskId)) return
isOperationCompletedAfterFinish = traces.isEmpty()
}
if (isOperationCompletedAfterFinish) {
debug("Operation is finished")
afterOperationListeners.forEach { it() }
}
}
private fun addTask(taskId: Id) {
val taskCounter = traces.getOrPut(taskId) { 0 }
traces[taskId] = taskCounter + 1
debug("Task is started with id `$taskId`")
}
private fun removeTask(taskId: Id): Boolean {
debug("Task is finished with id `$taskId`")
val taskCounter = traces[taskId] ?: return false
when (taskCounter) {
1 -> traces.remove(taskId)
else -> traces[taskId] = taskCounter - 1
}
return taskCounter == 1
}
fun beforeOperation(listener: Listener) {
beforeOperation(listener::listen)
}
fun beforeOperation(listener: () -> Unit) {
beforeOperationListeners.add(listener)
}
fun afterOperation(listener: Listener) {
afterOperation(listener::listen)
}
fun afterOperation(listener: () -> Unit) {
afterOperationListeners.add(listener)
}
private fun debug(message: String) {
if (LOG.isDebugEnabled) {
val debugPrefix = if (debugName == null) "" else "$debugName: "
LOG.debug("$debugPrefix$message")
}
}
interface Listener {
fun listen()
}
companion object {
private val LOG = Logger.getInstance(CompoundParallelOperationTrace::class.java)
fun <Id, R> CompoundParallelOperationTrace<Id>.task(taskId: Id, action: () -> R): R {
startTask(taskId)
try {
return action()
}
finally {
finishTask(taskId)
}
}
}
} | apache-2.0 | b5dacdeb2129c3fd61ad44101fabc240 | 26.41 | 140 | 0.678832 | 4.391026 | false | false | false | false |
xranby/modern-jogl-examples | src/main/kotlin/main/tut06/rotations.kt | 1 | 9312 | package main.tut06
import buffer.destroy
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL2ES3.GL_COLOR
import com.jogamp.opengl.GL2ES3.GL_DEPTH
import com.jogamp.opengl.GL3
import extensions.intBufferBig
import extensions.toFloatBuffer
import extensions.toShortBuffer
import glsl.programOf
import main.*
import main.framework.Framework
import main.framework.Semantic
import mat.Mat3
import mat.Mat4
import vec._3.Vec3
import vec._4.Vec4
/**
* Created by elect on 23/02/17.
*/
fun main(args: Array<String>) {
Rotations_()
}
class Rotations_ : Framework("Tutorial 06 - Rotations") {
object Buffer {
val VERTEX = 0
val INDEX = 1
val MAX = 2
}
var theProgram = 0
var modelToCameraMatrixUnif = 0
var cameraToClipMatrixUnif = 0
val cameraToClipMatrix = Mat4(0.0f)
val frustumScale = calcFrustumScale(45.0f)
fun calcFrustumScale(fovDeg: Float) = 1.0f / glm.tan(fovDeg.rad / 2.0f)
val bufferObject = intBufferBig(Buffer.MAX)
val vao = intBufferBig(1)
val numberOfVertices = 8
val GREEN_COLOR = floatArrayOf(0.0f, 1.0f, 0.0f, 1.0f)
val BLUE_COLOR = floatArrayOf(0.0f, 0.0f, 1.0f, 1.0f)
val RED_COLOR = floatArrayOf(1.0f, 0.0f, 0.0f, 1.0f)
val BROWN_COLOR = floatArrayOf(0.5f, 0.5f, 0.0f, 1.0f)
val vertexData = floatArrayOf(
+1.0f, +1.0f, +1.0f,
-1.0f, -1.0f, +1.0f,
-1.0f, +1.0f, -1.0f,
+1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
+1.0f, +1.0f, -1.0f,
+1.0f, -1.0f, +1.0f,
-1.0f, +1.0f, +1.0f,
GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3],
BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3],
RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3],
BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3],
GREEN_COLOR[0], GREEN_COLOR[1], GREEN_COLOR[2], GREEN_COLOR[3],
BLUE_COLOR[0], BLUE_COLOR[1], BLUE_COLOR[2], BLUE_COLOR[3],
RED_COLOR[0], RED_COLOR[1], RED_COLOR[2], RED_COLOR[3],
BROWN_COLOR[0], BROWN_COLOR[1], BROWN_COLOR[2], BROWN_COLOR[3])
val indexData = shortArrayOf(
0, 1, 2,
1, 0, 3,
2, 3, 0,
3, 2, 1,
5, 4, 6,
4, 5, 7,
7, 6, 4,
6, 7, 5)
private val instanceList = arrayOf(
Instance(this::nullRotation, Vec3(0.0f, 0.0f, -25.0f)),
Instance(this::rotateX, Vec3(-5.0f, -5.0f, -25.0f)),
Instance(this::rotateY, Vec3(-5.0f, +5.0f, -25.0f)),
Instance(this::rotateZ, Vec3(+5.0f, +5.0f, -25.0f)),
Instance(this::rotateAxis, Vec3(5.0f, -5.0f, -25.0f)))
var start = 0L
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffers(gl)
glGenVertexArrays(1, vao)
glBindVertexArray(vao[0])
val colorDataOffset = Vec3.SIZE * numberOfVertices
glBindBuffer(GL_ARRAY_BUFFER, bufferObject[Buffer.VERTEX])
glEnableVertexAttribArray(Semantic.Attr.POSITION)
glEnableVertexAttribArray(Semantic.Attr.COLOR)
glVertexAttribPointer(Semantic.Attr.POSITION, 3, GL_FLOAT, false, Vec3.SIZE, 0)
glVertexAttribPointer(Semantic.Attr.COLOR, 4, GL_FLOAT, false, Vec4.SIZE, colorDataOffset.L)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferObject[Buffer.INDEX])
glBindVertexArray(0)
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
glFrontFace(GL_CW)
glEnable(GL_DEPTH_TEST)
glDepthMask(true)
glDepthFunc(GL_LEQUAL)
glDepthRange(0.0, 1.0)
start = System.currentTimeMillis()
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, this::class.java, "tut06", "pos-color-local-transform.vert", "color-passthrough.frag")
modelToCameraMatrixUnif = glGetUniformLocation(theProgram, "modelToCameraMatrix")
cameraToClipMatrixUnif = glGetUniformLocation(theProgram, "cameraToClipMatrix")
val zNear = 1.0f
val zFar = 61.0f
cameraToClipMatrix[0].x = frustumScale
cameraToClipMatrix[1].y = frustumScale
cameraToClipMatrix[2].z = (zFar + zNear) / (zNear - zFar)
cameraToClipMatrix[2].w = -1.0f
cameraToClipMatrix[3].z = 2f * zFar * zNear / (zNear - zFar)
cameraToClipMatrix to matBuffer
glUseProgram(theProgram)
glUniformMatrix4fv(cameraToClipMatrixUnif, 1, false, matBuffer)
glUseProgram(0)
}
fun initializeVertexBuffers(gl: GL3) = with(gl) {
val vertexBuffer = vertexData.toFloatBuffer()
val indexBuffer = indexData.toShortBuffer()
glGenBuffers(Buffer.MAX, bufferObject)
glBindBuffer(GL_ARRAY_BUFFER, bufferObject[Buffer.VERTEX])
glBufferData(GL_ARRAY_BUFFER, vertexBuffer.SIZE.L, vertexBuffer, GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindBuffer(GL_ARRAY_BUFFER, bufferObject[Buffer.INDEX])
glBufferData(GL_ARRAY_BUFFER, indexBuffer.SIZE.L, indexBuffer, GL_STATIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, 0)
vertexBuffer.destroy()
indexBuffer.destroy()
}
override fun display(gl: GL3) = with(gl) {
glClearBufferfv(GL_COLOR, 0, clearColor.put(0, 0.0f).put(1, 0.0f).put(2, 0.0f).put(3, 0.0f))
glClearBufferfv(GL_DEPTH, 0, clearDepth.put(0, 1.0f))
glUseProgram(theProgram)
glBindVertexArray(vao[0])
val elapsedTime = (System.currentTimeMillis() - start) / 1_000f
instanceList.forEach {
val transformMatrix = it.constructMatrix(elapsedTime)
glUniformMatrix4fv(modelToCameraMatrixUnif, 1, false, transformMatrix to matBuffer)
glDrawElements(GL_TRIANGLES, indexData.size, GL_UNSIGNED_SHORT, 0)
}
glBindVertexArray(0)
glUseProgram(0)
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
cameraToClipMatrix.a0 = frustumScale * (h / w.f)
cameraToClipMatrix.b1 = frustumScale
glUseProgram(theProgram)
glUniformMatrix4fv(cameraToClipMatrixUnif, 1, false, cameraToClipMatrix to matBuffer)
glUseProgram(0)
glViewport(0, 0, w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffers(Buffer.MAX, bufferObject)
glDeleteVertexArrays(1, vao)
vao.destroy()
bufferObject.destroy()
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> {
animator.remove(window)
window.destroy()
}
}
}
private class Instance(val calcRotation: (Float) -> Mat3, val offset: Vec3) {
fun constructMatrix(elapsedTime: Float): Mat4 {
val rotMatrix = calcRotation(elapsedTime)
val theMat = Mat4(rotMatrix)
theMat[3] = Vec4(offset, 1f)
return theMat
}
}
fun nullRotation(elapsedTime: Float) = Mat3(1f)
fun rotateX(elapsedTime: Float): Mat3 {
val angRad = computeAngleRad(elapsedTime, 3f)
val cos = glm.cos(angRad)
val sin = glm.sin(angRad)
val theMat = Mat3(1f)
theMat[1].y = cos; theMat[2].y = -sin
theMat[1].z = sin; theMat[2].z = cos
return theMat
}
fun rotateY(elapsedTime: Float): Mat3 {
val angRad = computeAngleRad(elapsedTime, 2f)
val cos = glm.cos(angRad)
val sin = glm.sin(angRad)
val theMat = Mat3(1f)
theMat[0].x = cos; theMat[2].x = sin
theMat[0].z = -sin; theMat[2].z = cos
return theMat
}
fun rotateZ(elapsedTime: Float): Mat3 {
val angRad = computeAngleRad(elapsedTime, 2f)
val cos = glm.cos(angRad)
val sin = glm.sin(angRad)
val theMat = Mat3(1f)
theMat[0].x = cos; theMat[1].x = -sin
theMat[0].y = sin; theMat[1].y = cos
return theMat
}
fun rotateAxis(elapsedTime: Float): Mat3 {
val angRad = computeAngleRad(elapsedTime, 2f)
val cos = glm.cos(angRad)
val invCos = 1f - cos
val sin = glm.sin(angRad)
val axis = Vec3(1f).normalize_()
val theMat = Mat3(1f)
theMat[0].x = (axis.x * axis.x) + ((1 - axis.x * axis.x) * cos)
theMat[1].x = axis.x * axis.y * (invCos) - (axis.z * sin)
theMat[2].x = axis.x * axis.z * (invCos) + (axis.y * sin)
theMat[0].y = axis.x * axis.y * (invCos) + (axis.z * sin)
theMat[1].y = (axis.y * axis.y) + ((1 - axis.y * axis.y) * cos)
theMat[2].y = axis.y * axis.z * (invCos) - (axis.x * sin)
theMat[0].z = axis.x * axis.z * (invCos) - (axis.y * sin)
theMat[1].z = axis.y * axis.z * (invCos) + (axis.x * sin)
theMat[2].z = (axis.z * axis.z) + ((1 - axis.z * axis.z) * cos)
return theMat
}
fun computeAngleRad(elapsedTime: Float, loopDuration: Float): Float {
val scale = (Math.PI * 2.0f / loopDuration).f
val currentTimeThroughLoop = elapsedTime % loopDuration
return currentTimeThroughLoop * scale
}
}
| mit | 314b61deb849fe5d9fd73cd01be84ec2 | 29.233766 | 121 | 0.598905 | 3.462997 | false | false | false | false |
leafclick/intellij-community | platform/service-container/src/com/intellij/serviceContainer/PlatformComponentManagerImpl.kt | 1 | 32230 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.serviceContainer
import com.intellij.diagnostic.LoadingState
import com.intellij.diagnostic.PluginException
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.ide.plugins.*
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.idea.Main
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.components.ServiceDescriptor.PreloadMode
import com.intellij.openapi.components.impl.ComponentManagerImpl
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.*
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Disposer
import com.intellij.util.SmartList
import com.intellij.util.SystemProperties
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.storage.HeavyProcessLatch
import com.intellij.util.messages.*
import com.intellij.util.messages.impl.MessageBusImpl
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.TestOnly
import java.lang.reflect.Constructor
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Modifier
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.Executor
internal val LOG = logger<PlatformComponentManagerImpl>()
abstract class PlatformComponentManagerImpl @JvmOverloads constructor(internal val parent: PlatformComponentManagerImpl?,
setExtensionsRootArea: Boolean = parent == null) : ComponentManagerImpl(parent), Disposable.Parent, MessageBusOwner {
companion object {
private val constructorParameterResolver = ConstructorParameterResolver()
@JvmStatic
protected val fakeCorePluginDescriptor = DefaultPluginDescriptor(PluginManagerCore.CORE_ID, null)
// not as file level function to avoid scope cluttering
@Internal
fun <T> isLightService(serviceClass: Class<T>): Boolean {
return Modifier.isFinal(serviceClass.modifiers) && serviceClass.isAnnotationPresent(Service::class.java)
}
}
@Suppress("LeakingThis")
private val extensionArea = ExtensionsAreaImpl(this)
private var messageBus: MessageBusImpl? = null
private var handlingInitComponentError = false
@Volatile
private var isServicePreloadingCancelled = false
private var instantiatedComponentCount = 0
private var componentConfigCount = -1
@Suppress("LeakingThis")
internal val serviceParentDisposable = Disposer.newDisposable("services of ${javaClass.name}@${System.identityHashCode(this)}")
var componentCreated = false
private set
private val lightServices: ConcurrentMap<Class<*>, Any>? = when {
parent == null || parent.picoContainer.parent == null -> ContainerUtil.newConcurrentMap()
else -> null
}
@Suppress("DEPRECATION")
private val baseComponents: MutableList<BaseComponent> = SmartList()
protected open val componentStore: IComponentStore
get() = getService(IComponentStore::class.java)!!
init {
if (setExtensionsRootArea) {
Extensions.setRootArea(extensionArea)
}
}
final override fun getMessageBus(): MessageBus {
if (containerState.get().ordinal >= ContainerState.DISPOSE_IN_PROGRESS.ordinal) {
throw IllegalStateException("Already disposed: $this")
}
return messageBus ?: getOrCreateMessageBusUnderLock()
}
protected open fun setProgressDuringInit(indicator: ProgressIndicator) {
indicator.fraction = getPercentageOfComponentsLoaded()
}
protected fun getPercentageOfComponentsLoaded(): Double {
return instantiatedComponentCount.toDouble() / componentConfigCount
}
final override fun getExtensionArea(): ExtensionsAreaImpl = extensionArea
@Internal
fun registerComponents(plugins: List<IdeaPluginDescriptorImpl>, notifyListeners: Boolean) {
val listenerCallbacks = if (notifyListeners) mutableListOf<Runnable>() else null
registerComponents(plugins.map { DescriptorToLoad(it) }, listenerCallbacks)
listenerCallbacks?.forEach(Runnable::run)
}
data class DescriptorToLoad(
// plugin descriptor can have some definitions that are not applied until some specified plugin is not enabled,
// if both descriptor and rootDescriptor are specified, descriptor it is such partial part
val descriptor: IdeaPluginDescriptorImpl,
val baseDescriptor: IdeaPluginDescriptorImpl = descriptor
)
@Internal
open fun registerComponents(plugins: List<DescriptorToLoad>, listenerCallbacks: List<Runnable>?) {
val activityNamePrefix = activityNamePrefix()
val app = getApplication()
val headless = app == null || app.isHeadlessEnvironment
var newComponentConfigCount = 0
var map: ConcurrentMap<String, MutableList<ListenerDescriptor>>? = null
val isHeadlessMode = app?.isHeadlessEnvironment == true
val isUnitTestMode = app?.isUnitTestMode == true
val clonePoint = parent != null
var activity = activityNamePrefix?.let { StartUpMeasurer.startMainActivity("${it}service and ep registration") }
// register services before registering extensions because plugins can access services in their
// extensions which can be invoked right away if the plugin is loaded dynamically
for (plugin in plugins) {
val containerDescriptor = getContainerDescriptor(plugin.descriptor)
registerServices(containerDescriptor.services, plugin.baseDescriptor)
for (descriptor in containerDescriptor.components) {
if (!descriptor.prepareClasses(headless) || !isComponentSuitable(descriptor)) {
continue
}
try {
registerComponent(descriptor, plugin.descriptor)
newComponentConfigCount++
}
catch (e: Throwable) {
handleInitComponentError(e, null, plugin.descriptor.pluginId)
}
}
val listeners = containerDescriptor.listeners
if (listeners.isNotEmpty()) {
if (map == null) {
map = ContainerUtil.newConcurrentMap()
}
for (listener in listeners) {
if ((isUnitTestMode && !listener.activeInTestMode) || (isHeadlessMode && !listener.activeInHeadlessMode)) {
continue
}
map.getOrPut(listener.topicClassName) { SmartList() }.add(listener)
}
}
containerDescriptor.extensionPoints?.let {
extensionArea.registerExtensionPoints(it, clonePoint)
}
}
if (activity != null) {
activity = activity.endAndStart("${activityNamePrefix}extension registration")
}
for ((pluginDescriptor, rootDescriptor) in plugins) {
pluginDescriptor.registerExtensions(extensionArea, this, rootDescriptor, listenerCallbacks)
}
activity?.end()
if (componentConfigCount == -1) {
componentConfigCount = newComponentConfigCount
}
// app - phase must be set before getMessageBus()
if (picoContainer.parent == null && !LoadingState.COMPONENTS_REGISTERED.isOccurred /* loading plugin on the fly */) {
StartUpMeasurer.setCurrentState(LoadingState.COMPONENTS_REGISTERED)
}
// ensure that messageBus is created, regardless of lazy listeners map state
val messageBus = getOrCreateMessageBusUnderLock()
if (map != null) {
messageBus.setLazyListeners(map)
}
}
protected fun createComponents(indicator: ProgressIndicator?) {
LOG.assertTrue(!componentCreated)
if (indicator != null) {
indicator.isIndeterminate = false
}
val activity = when (val activityNamePrefix = activityNamePrefix()) {
null -> null
else -> StartUpMeasurer.startMainActivity("$activityNamePrefix${StartUpMeasurer.Activities.CREATE_COMPONENTS_SUFFIX}")
}
for (componentAdapter in myPicoContainer.componentAdapters) {
if (componentAdapter is MyComponentAdapter) {
componentAdapter.getInstance<Any>(this, keyClass = null, indicator = indicator)
}
}
activity?.end()
componentCreated = true
}
@TestOnly
fun registerComponentImplementation(componentKey: Class<*>, componentImplementation: Class<*>, shouldBeRegistered: Boolean) {
val picoContainer = picoContainer
val adapter = picoContainer.unregisterComponent(componentKey) as MyComponentAdapter?
if (shouldBeRegistered) {
LOG.assertTrue(adapter != null)
}
picoContainer.registerComponent(
MyComponentAdapter(componentKey, componentImplementation.name, DefaultPluginDescriptor("test registerComponentImplementation"), this,
componentImplementation))
}
@TestOnly
fun <T : Any> replaceComponentInstance(componentKey: Class<T>, componentImplementation: T, parentDisposable: Disposable?): T? {
val adapter = myPicoContainer.getComponentAdapter(componentKey) as MyComponentAdapter
return adapter.replaceInstance(componentImplementation, parentDisposable)
}
private fun registerComponent(config: ComponentConfig, pluginDescriptor: PluginDescriptor) {
val interfaceClass = Class.forName(config.interfaceClass, true, pluginDescriptor.pluginClassLoader)
if (config.options != null && java.lang.Boolean.parseBoolean(config.options!!.get("overrides"))) {
myPicoContainer.unregisterComponent(interfaceClass) ?: throw PluginException("$config does not override anything",
pluginDescriptor.pluginId)
}
val implementationClass = when (config.interfaceClass) {
config.implementationClass -> interfaceClass.name
else -> config.implementationClass
}
// implementationClass == null means we want to unregister this component
if (!implementationClass.isNullOrEmpty()) {
val ws = config.options != null && java.lang.Boolean.parseBoolean(config.options!!.get("workspace"))
myPicoContainer.registerComponent(MyComponentAdapter(interfaceClass, implementationClass, pluginDescriptor, this, null, ws))
}
}
internal open fun getApplication(): Application? = if (this is Application) this else ApplicationManager.getApplication()
private fun registerServices(services: List<ServiceDescriptor>, pluginDescriptor: IdeaPluginDescriptor) {
val picoContainer = myPicoContainer
for (descriptor in services) {
// Allow to re-define service implementations in plugins.
// Empty serviceImplementation means we want to unregister service.
if (descriptor.overrides && picoContainer.unregisterComponent(descriptor.getInterface()) == null) {
throw PluginException("Service: ${descriptor.getInterface()} doesn't override anything", pluginDescriptor.pluginId)
}
// empty serviceImplementation means we want to unregister service
if (descriptor.implementation != null) {
picoContainer.registerComponent(ServiceComponentAdapter(descriptor, pluginDescriptor, this))
}
}
}
@Internal
fun handleInitComponentError(t: Throwable, componentClassName: String?, pluginId: PluginId) {
if (handlingInitComponentError) {
return
}
handlingInitComponentError = true
try {
handleComponentError(t, componentClassName, pluginId)
}
finally {
handlingInitComponentError = false
}
}
@Internal
fun initializeComponent(component: Any, serviceDescriptor: ServiceDescriptor?) {
if (serviceDescriptor == null || !(component is PathMacroManager || component is IComponentStore || component is MessageBusFactory)) {
LoadingState.CONFIGURATION_STORE_INITIALIZED.checkOccurred()
componentStore.initComponent(component, serviceDescriptor)
}
}
protected abstract fun getContainerDescriptor(pluginDescriptor: IdeaPluginDescriptorImpl): ContainerDescriptor
final override fun <T : Any> getComponent(interfaceClass: Class<T>): T? {
val picoContainer = picoContainer
val adapter = picoContainer.getComponentAdapter(interfaceClass) ?: return null
if (adapter is ServiceComponentAdapter) {
LOG.error("$interfaceClass it is service, use getService instead of getComponent")
}
@Suppress("UNCHECKED_CAST")
return when (adapter) {
is BaseComponentAdapter -> {
if (parent != null && adapter.componentManager !== this) {
LOG.error("getComponent must be called on appropriate container (current: $this, expected: ${adapter.componentManager})")
}
adapter.getInstance(adapter.componentManager, interfaceClass)
}
else -> adapter.getComponentInstance(picoContainer) as T
}
}
final override fun <T : Any> getService(serviceClass: Class<T>) = doGetService(serviceClass, true)
final override fun <T : Any> getServiceIfCreated(serviceClass: Class<T>) = doGetService(serviceClass, false)
private fun <T : Any> doGetService(serviceClass: Class<T>, createIfNeeded: Boolean): T? {
val lightServices = lightServices
if (lightServices != null && isLightService(serviceClass)) {
return getLightService(serviceClass, createIfNeeded)
}
val key = serviceClass.name
val adapter = picoContainer.getServiceAdapter(key) as? ServiceComponentAdapter
if (adapter != null) {
return adapter.getInstance(this, serviceClass, createIfNeeded)
}
checkCanceledIfNotInClassInit()
if (parent != null) {
val result = parent.doGetService(serviceClass, createIfNeeded)
if (result != null) {
LOG.error("$key is registered as application service, but requested as project one")
return result
}
}
val result = getComponent(serviceClass) ?: return null
val message = "$key requested as a service, but it is a component - convert it to a service or " +
"change call to ${if (parent == null) "ApplicationManager.getApplication().getComponent()" else "project.getComponent()"}"
if (SystemProperties.`is`("idea.test.getService.assert.as.warn")) {
LOG.warn(message)
}
else {
PluginException.logPluginError(LOG, message, null, serviceClass)
}
return result
}
internal fun <T : Any> getLightService(serviceClass: Class<T>, createIfNeeded: Boolean): T? {
val lightServices = lightServices!!
@Suppress("UNCHECKED_CAST")
val result = lightServices.get(serviceClass) as T?
if (result != null || !createIfNeeded) {
return result
}
else {
synchronized(serviceClass) {
return getOrCreateLightService(serviceClass, lightServices)
}
}
}
@Internal
fun getServiceImplementationClassNames(prefix: String): List<String> {
val result = ArrayList<String>()
ServiceManagerImpl.processAllDescriptors(this) { serviceDescriptor ->
val implementation = serviceDescriptor.implementation ?: return@processAllDescriptors
if (implementation.startsWith(prefix)) {
result.add(implementation)
}
}
return result
}
private fun <T : Any> getOrCreateLightService(serviceClass: Class<T>, cache: ConcurrentMap<Class<*>, Any>): T {
LoadingState.COMPONENTS_REGISTERED.checkOccurred()
@Suppress("UNCHECKED_CAST")
var result = cache.get(serviceClass) as T?
if (result != null) {
return result
}
HeavyProcessLatch.INSTANCE.processStarted("Creating service '${serviceClass.name}'").use {
if (ProgressIndicatorProvider.getGlobalProgressIndicator() == null) {
result = createLightService(serviceClass)
}
else {
ProgressManager.getInstance().executeNonCancelableSection {
result = createLightService(serviceClass)
}
}
}
val prevValue = cache.put(serviceClass, result)
LOG.assertTrue(prevValue == null)
return result!!
}
@Synchronized
protected open fun getOrCreateMessageBusUnderLock(): MessageBusImpl {
var messageBus = this.messageBus
if (messageBus != null) {
return messageBus
}
messageBus = MessageBusFactory.newMessageBus(this, parent?.messageBus) as MessageBusImpl
if (StartUpMeasurer.isMeasuringPluginStartupCosts()) {
messageBus.setMessageDeliveryListener { topic, messageName, handler, duration ->
if (!StartUpMeasurer.isMeasuringPluginStartupCosts()) {
messageBus.setMessageDeliveryListener(null)
return@setMessageDeliveryListener
}
logMessageBusDelivery(topic, messageName, handler, duration)
}
}
registerServiceInstance(MessageBus::class.java, messageBus, fakeCorePluginDescriptor)
this.messageBus = messageBus
return messageBus
}
protected open fun logMessageBusDelivery(topic: Topic<*>, messageName: String?, handler: Any, duration: Long) {
val loader = handler.javaClass.classLoader
val pluginId = if (loader is PluginClassLoader) loader.pluginIdString else PluginManagerCore.CORE_ID.idString
StartUpMeasurer.addPluginCost(pluginId, "MessageBus", duration)
}
/**
* Use only if approved by core team.
*/
@Internal
fun registerComponent(key: Class<*>, implementation: Class<*>, pluginDescriptor: PluginDescriptor, override: Boolean) {
val picoContainer = picoContainer
if (override && picoContainer.unregisterComponent(key) == null) {
throw PluginException("Component $key doesn't override anything", pluginDescriptor.pluginId)
}
picoContainer.registerComponent(MyComponentAdapter(key, implementation.name, pluginDescriptor, this, implementation))
}
/**
* Use only if approved by core team.
*/
@Internal
fun registerService(serviceInterface: Class<*>, implementation: Class<*>, pluginDescriptor: PluginDescriptor, override: Boolean) {
val serviceKey = serviceInterface.name
if (override && myPicoContainer.unregisterComponent(serviceKey) == null) {
throw PluginException("Service $serviceKey doesn't override anything", pluginDescriptor.pluginId)
}
val descriptor = ServiceDescriptor()
descriptor.serviceInterface = serviceInterface.name
descriptor.serviceImplementation = implementation.name
myPicoContainer.registerComponent(ServiceComponentAdapter(descriptor, pluginDescriptor, this, implementation))
}
/**
* Use only if approved by core team.
*/
@Internal
fun <T : Any> registerServiceInstance(serviceInterface: Class<T>, instance: T, pluginDescriptor: PluginDescriptor) {
val serviceKey = serviceInterface.name
myPicoContainer.unregisterComponent(serviceKey)
val descriptor = ServiceDescriptor()
descriptor.serviceInterface = serviceKey
descriptor.serviceImplementation = instance.javaClass.name
picoContainer.registerComponent(ServiceComponentAdapter(descriptor, pluginDescriptor, this, instance.javaClass, instance))
}
@TestOnly
@Internal
fun <T : Any> replaceServiceInstance(serviceInterface: Class<T>, instance: T, parentDisposable: Disposable) {
val adapter = myPicoContainer.getServiceAdapter(serviceInterface.name) as ServiceComponentAdapter
adapter.replaceInstance(instance, parentDisposable)
}
private fun <T : Any> createLightService(serviceClass: Class<T>): T {
val startTime = StartUpMeasurer.getCurrentTime()
val result = instantiateClass(serviceClass, null)
if (result is Disposable) {
Disposer.register(serviceParentDisposable, result)
}
initializeComponent(result, null)
val pluginClassLoader = serviceClass.classLoader as? PluginClassLoader
StartUpMeasurer.addCompletedActivity(startTime, serviceClass, getServiceActivityCategory(this), pluginClassLoader?.pluginIdString)
return result
}
final override fun <T : Any> instantiateClass(aClass: Class<T>, pluginId: PluginId?): T {
checkCanceledIfNotInClassInit()
try {
if (parent == null) {
val constructor = aClass.getDeclaredConstructor()
constructor.isAccessible = true
return constructor.newInstance()
}
else {
val constructors = aClass.declaredConstructors
var constructor: Constructor<*>? = if (constructors.size > 1) {
// see ConfigurableEP - prefer constructor that accepts our instance
constructors.firstOrNull { it.parameterCount == 1 && it.parameterTypes[0].isAssignableFrom(javaClass) }
}
else {
null
}
if (constructor == null) {
constructors.sortBy { it.parameterCount }
constructor = constructors.first()!!
}
constructor.isAccessible = true
@Suppress("UNCHECKED_CAST")
return when (constructor.parameterCount) {
1 -> constructor.newInstance(this)
else -> constructor.newInstance()
} as T
}
}
catch (e: Throwable) {
if (e is InvocationTargetException) {
val targetException = e.targetException
if (targetException is ControlFlowException) {
throw targetException
}
}
else if (e is ControlFlowException) {
throw e
}
val message = "Cannot create class ${aClass.name}"
if (pluginId == null) {
throw PluginException.createByClass(message, e, aClass)
}
else {
throw PluginException(message, e, pluginId)
}
}
}
final override fun <T : Any> instantiateClassWithConstructorInjection(aClass: Class<T>, key: Any, pluginId: PluginId): T {
return instantiateUsingPicoContainer(aClass, key, pluginId, this, constructorParameterResolver)
}
internal open val isGetComponentAdapterOfTypeCheckEnabled: Boolean
get() = true
final override fun <T : Any> instantiateExtensionWithPicoContainerOnlyIfNeeded(className: String?,
pluginDescriptor: PluginDescriptor?): T {
val pluginId = pluginDescriptor?.pluginId ?: PluginId.getId("unknown")
if (className == null) {
throw PluginException("implementation class is not specified", pluginId)
}
val aClass = try {
@Suppress("UNCHECKED_CAST")
Class.forName(className, true, pluginDescriptor?.pluginClassLoader ?: javaClass.classLoader) as Class<T>
}
catch (e: Throwable) {
throw PluginException(e, pluginId)
}
try {
return instantiateClass(aClass, pluginId)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: ExtensionNotApplicableException) {
throw e
}
catch (e: Throwable) {
when {
e.cause is NoSuchMethodException || e.cause is IllegalArgumentException -> {
val exception = PluginException("Bean extension class constructor must not have parameters: $className", pluginId)
if ((pluginDescriptor?.isBundled == true) || getApplication()?.isUnitTestMode == true) {
LOG.error(exception)
}
else {
LOG.warn(exception)
}
}
e is PluginException -> throw e
else -> throw if (pluginDescriptor == null) PluginException.createByClass(e, aClass)
else PluginException(e, pluginDescriptor.pluginId)
}
}
return instantiateClassWithConstructorInjection(aClass, aClass, pluginId)
}
final override fun createListener(descriptor: ListenerDescriptor): Any {
val pluginDescriptor = descriptor.pluginDescriptor
val aClass = try {
Class.forName(descriptor.listenerClassName, true, pluginDescriptor.pluginClassLoader)
}
catch (e: Throwable) {
throw PluginException("Cannot create listener ${descriptor.listenerClassName}", e, pluginDescriptor.pluginId)
}
return instantiateClass(aClass, pluginDescriptor.pluginId)
}
final override fun logError(error: Throwable, pluginId: PluginId) {
if (error is ProcessCanceledException || error is ExtensionNotApplicableException) {
throw error
}
LOG.error(createPluginExceptionIfNeeded(error, pluginId))
}
final override fun createError(error: Throwable, pluginId: PluginId): RuntimeException {
return when (error) {
is ProcessCanceledException, is ExtensionNotApplicableException -> error as RuntimeException
else -> createPluginExceptionIfNeeded(error, pluginId)
}
}
final override fun createError(message: String, pluginId: PluginId) = PluginException(message, pluginId)
@Internal
fun unloadServices(containerDescriptor: ContainerDescriptor): List<Any> {
val unloadedInstances = ArrayList<Any>()
for (service in containerDescriptor.services) {
val adapter = myPicoContainer.unregisterComponent(service.getInterface()) as? ServiceComponentAdapter ?: continue
val instance = adapter.getInstance<Any>(this, null, createIfNeeded = false) ?: continue
if (instance is Disposable) {
Disposer.dispose(instance)
}
unloadedInstances.add(instance)
}
return unloadedInstances
}
@Internal
open fun activityNamePrefix(): String? = null
data class ServicePreloadingResult(val asyncPreloadedServices: CompletableFuture<Void?>,
val syncPreloadedServices: CompletableFuture<Void?>)
@ApiStatus.Internal
fun preloadServices(plugins: List<IdeaPluginDescriptorImpl>, executor: Executor, onlyIfAwait: Boolean = false): ServicePreloadingResult {
val asyncPreloadedServices = mutableListOf<CompletableFuture<Void>>()
val syncPreloadedServices = mutableListOf<CompletableFuture<Void>>()
for (plugin in plugins) {
serviceLoop@
for (service in getContainerDescriptor(plugin).services) {
val list = when (service.preload) {
PreloadMode.TRUE -> {
if (onlyIfAwait) {
continue@serviceLoop
}
else {
asyncPreloadedServices
}
}
PreloadMode.NOT_HEADLESS -> {
if (onlyIfAwait || getApplication()!!.isHeadlessEnvironment) {
continue@serviceLoop
}
else {
asyncPreloadedServices
}
}
PreloadMode.NOT_LIGHT_EDIT -> {
if (onlyIfAwait || Main.isLightEdit()) {
continue@serviceLoop
}
else {
asyncPreloadedServices
}
}
PreloadMode.AWAIT -> {
syncPreloadedServices
}
PreloadMode.FALSE -> continue@serviceLoop
else -> throw IllegalStateException("Unknown preload mode ${service.preload}")
}
val future = CompletableFuture.runAsync(Runnable {
if (!isServicePreloadingCancelled && !isDisposed) {
val adapter = myPicoContainer.getServiceAdapter(service.getInterface()) as ServiceComponentAdapter? ?: return@Runnable
try {
adapter.getInstance<Any>(this, null)
}
catch (e: StartupAbortedException) {
isServicePreloadingCancelled = true
throw e
}
}
}, executor)
list.add(future)
}
}
return ServicePreloadingResult(asyncPreloadedServices = CompletableFuture.allOf(*asyncPreloadedServices.toTypedArray()),
syncPreloadedServices = CompletableFuture.allOf(*syncPreloadedServices.toTypedArray()))
}
override fun isDisposed(): Boolean {
return containerState.get().ordinal >= ContainerState.DISPOSE_IN_PROGRESS.ordinal
}
final override fun beforeTreeDispose() {
stopServicePreloading()
ApplicationManager.getApplication().assertIsWriteThread()
if (!containerState.compareAndSet(ContainerState.ACTIVE, ContainerState.DISPOSE_IN_PROGRESS)) {
// disposed in a recommended way using ProjectManager
return
}
// disposed directly using Disposer.dispose()
// we don't care that state DISPOSE_IN_PROGRESS is already set,
// and exceptions because of that possible - use ProjectManager to close and dispose project.
startDispose()
}
@Internal
fun startDispose() {
stopServicePreloading()
Disposer.disposeChildren(this)
val messageBus = messageBus
// There is a chance that someone will try to connect to message bus and will get NPE because of disposed connection disposable,
// because container state is not yet set to DISPOSE_IN_PROGRESS.
// So, 1) dispose connection children 2) set state DISPOSE_IN_PROGRESS 3) dispose connection
messageBus?.disposeConnectionChildren()
containerState.set(ContainerState.DISPOSE_IN_PROGRESS)
messageBus?.disposeConnection()
}
override fun dispose() {
if (!containerState.compareAndSet(ContainerState.DISPOSE_IN_PROGRESS, ContainerState.DISPOSED)) {
throw IllegalStateException("Expected current state is DISPOSE_IN_PROGRESS, but actual state is ${containerState.get()} ($this)")
}
// dispose components and services
Disposer.dispose(serviceParentDisposable)
// release references to services instances
myPicoContainer.release()
val messageBus = messageBus
if (messageBus != null ) {
// Must be after disposing of serviceParentDisposable, because message bus disposes child buses, so, we must dispose all services first.
// For example, service ModuleManagerImpl disposes modules, each module, in turn, disposes module's message bus (child bus of application).
Disposer.dispose(messageBus)
this.messageBus = null
}
if (!containerState.compareAndSet(ContainerState.DISPOSED, ContainerState.DISPOSE_COMPLETED)) {
throw IllegalStateException("Expected current state is DISPOSED, but actual state is ${containerState.get()} ($this)")
}
componentConfigCount = -1
}
@Internal
fun stopServicePreloading() {
isServicePreloadingCancelled = true
}
@Suppress("DEPRECATION")
override fun getComponent(name: String): BaseComponent? {
for (componentAdapter in picoContainer.componentAdapters) {
if (componentAdapter is MyComponentAdapter) {
val instance = componentAdapter.getInitializedInstance()
if (instance is BaseComponent && name == instance.componentName) {
return instance
}
}
}
return null
}
@Internal
internal fun componentCreated(indicator: ProgressIndicator?) {
instantiatedComponentCount++
if (indicator != null) {
indicator.checkCanceled()
setProgressDuringInit(indicator)
}
}
}
private fun createPluginExceptionIfNeeded(error: Throwable, pluginId: PluginId): RuntimeException {
return when (error) {
is PluginException, is ExtensionInstantiationException -> error as RuntimeException
else -> PluginException(error, pluginId)
}
}
fun handleComponentError(t: Throwable, componentClassName: String?, pluginId: PluginId?) {
if (t is StartupAbortedException) {
throw t
}
val app = ApplicationManager.getApplication()
if (app != null && app.isUnitTestMode) {
throw t
}
var effectivePluginId = pluginId
if (effectivePluginId == null || PluginManagerCore.CORE_ID == effectivePluginId) {
if (componentClassName != null) {
effectivePluginId = PluginManagerCore.getPluginByClassName(componentClassName)
}
}
if (effectivePluginId == null || PluginManagerCore.CORE_ID == effectivePluginId) {
if (t is ExtensionInstantiationException) {
effectivePluginId = t.extensionOwnerId
}
}
if (effectivePluginId != null && PluginManagerCore.CORE_ID != effectivePluginId) {
throw StartupAbortedException("Fatal error initializing plugin ${effectivePluginId.idString}", PluginException(t, effectivePluginId))
}
else {
throw StartupAbortedException("Fatal error initializing '$componentClassName'", t)
}
}
| apache-2.0 | b48d6c34a2f1e27dc803f88f22fb1933 | 36.828638 | 187 | 0.712287 | 5.194198 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/boxInline/nonLocalReturns/tryFinally/declSite/voidInlineFun.kt | 5 | 1287 | // FILE: 1.kt
package test
public inline fun <R> doCall(block: ()-> R, finallyBlock: ()-> Unit) {
try {
block()
} finally {
finallyBlock()
}
}
// FILE: 2.kt
import test.*
class Holder {
var value: String = ""
}
fun test1(h: Holder): String {
doCall ({
return "OK_NONLOCAL"
}, {
h.value = "OK_FINALLY"
})
return "FAIL";
}
fun test2(h: Holder): String {
doCall ({
h.value += "OK_LOCAL"
"OK_LOCAL"
}, {
h.value += ", OK_FINALLY"
return "OK_FINALLY"
})
return "FAIL";
}
fun test3(h: Holder): String {
doCall ({
h.value += "OK_NONLOCAL"
return "OK_NONLOCAL"
}, {
h.value += ", OK_FINALLY"
return "OK_FINALLY"
})
return "FAIL";
}
fun box(): String {
var h = Holder()
val test1 = test1(h)
if (test1 != "OK_NONLOCAL" || h.value != "OK_FINALLY") return "test1: ${test1}, holder: ${h.value}"
h = Holder()
val test2 = test2(h)
if (test2 != "OK_FINALLY" || h.value != "OK_LOCAL, OK_FINALLY") return "test2: ${test2}, holder: ${h.value}"
h = Holder()
val test3 = test3(h)
if (test3 != "OK_FINALLY" || h.value != "OK_NONLOCAL, OK_FINALLY") return "test3: ${test3}, holder: ${h.value}"
return "OK"
}
| apache-2.0 | 1397f7524cdce1440899179f3e6f713d | 16.875 | 115 | 0.517483 | 3.028235 | false | true | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/sensors/modules/MagnetometerUncalibratedModule.kt | 2 | 1872 | // Copyright 2015-present 650 Industries. All rights reserved.
package abi43_0_0.expo.modules.sensors.modules
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorManager
import android.os.Bundle
import abi43_0_0.expo.modules.interfaces.sensors.SensorServiceInterface
import abi43_0_0.expo.modules.interfaces.sensors.services.MagnetometerUncalibratedServiceInterface
import abi43_0_0.expo.modules.core.Promise
import abi43_0_0.expo.modules.core.interfaces.ExpoMethod
class MagnetometerUncalibratedModule(reactContext: Context?) : BaseSensorModule(reactContext) {
override val eventName: String = "magnetometerUncalibratedDidUpdate"
override fun getName(): String = "ExponentMagnetometerUncalibrated"
override fun getSensorService(): SensorServiceInterface {
return moduleRegistry.getModule(MagnetometerUncalibratedServiceInterface::class.java)
}
override fun eventToMap(sensorEvent: SensorEvent): Bundle {
return Bundle().apply {
putDouble("x", sensorEvent.values[0].toDouble())
putDouble("y", sensorEvent.values[1].toDouble())
putDouble("z", sensorEvent.values[2].toDouble())
}
}
@ExpoMethod
fun startObserving(promise: Promise) {
super.startObserving()
promise.resolve(null)
}
@ExpoMethod
fun stopObserving(promise: Promise) {
super.stopObserving()
promise.resolve(null)
}
@ExpoMethod
fun setUpdateInterval(updateInterval: Int, promise: Promise) {
super.setUpdateInterval(updateInterval)
promise.resolve(null)
}
@ExpoMethod
fun isAvailableAsync(promise: Promise) {
val mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
val isAvailable = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED) != null
promise.resolve(isAvailable)
}
}
| bsd-3-clause | 801cbc3718bb5cfc4729dfb535906135 | 33.036364 | 102 | 0.778846 | 4.404706 | false | false | false | false |
Virtlink/aesi | aesi-utils/src/main/kotlin/com/virtlink/editorservices/symbols/Symbol.kt | 1 | 435 | package com.virtlink.editorservices.symbols
import com.virtlink.editorservices.Span
import java.net.URI
data class Symbol(
override val label: String,
override val resource: URI? = null,
override val nameRange: Span? = null,
override val kind: String? = null,
override val attributes: List<String> = emptyList())
: ISymbol {
override fun toString(): String
= this.label
} | apache-2.0 | ece180267721871e84c02d05281155a3 | 24.647059 | 60 | 0.65977 | 4.438776 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/ProjectSearchResultHolderViewModel.kt | 1 | 4676 | package com.kickstarter.viewmodels
import android.util.Pair
import androidx.annotation.NonNull
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.NumberUtils
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.PairUtils
import com.kickstarter.libs.utils.extensions.deadlineCountdownValue
import com.kickstarter.models.Project
import com.kickstarter.ui.viewholders.ProjectSearchResultViewHolder
import rx.Observable
import rx.subjects.PublishSubject
interface ProjectSearchResultHolderViewModel {
interface Inputs {
/** Call to configure the view model with a project and isFeatured data. */
fun configureWith(projectAndIsFeatured: Pair<Project, Boolean>)
/** Call to say user clicked a project */
fun projectClicked()
}
interface Outputs {
/** Emits the formatted days to go text to be displayed. */
fun deadlineCountdownValueTextViewText(): Observable<String>
/** Emits the project clicked by the user. */
fun notifyDelegateOfResultClick(): Observable<Project>
/** Emits the percent funded text to be displayed. */
fun percentFundedTextViewText(): Observable<String>
/** Emits the project be used to display the deadline countdown detail. */
fun projectForDeadlineCountdownUnitTextView(): Observable<Project>
/** Emits the project title to be displayed. */
fun projectNameTextViewText(): Observable<String>
/** Emits the project photo url to be displayed. */
fun projectPhotoUrl(): Observable<String>
}
class ViewModel(@NonNull environment: Environment) :
ActivityViewModel<ProjectSearchResultViewHolder>(environment), Inputs, Outputs {
private val projectAndIsFeatured = PublishSubject.create<Pair<Project, Boolean>>()
private val projectClicked = PublishSubject.create<Void>()
private val deadlineCountdownValueTextViewText: Observable<String>
private val notifyDelegateOfResultClick: Observable<Project>
private val percentFundedTextViewText: Observable<String>
private val projectForDeadlineCountdownDetail: Observable<Project>
private val projectNameTextViewText: Observable<String>
private val projectPhotoUrl: Observable<String>
val inputs: Inputs = this
val outputs: Outputs = this
init {
deadlineCountdownValueTextViewText = projectAndIsFeatured
.map {
NumberUtils.format(
it.first.deadlineCountdownValue()
)
}
percentFundedTextViewText = projectAndIsFeatured
.map {
NumberUtils.flooredPercentage(
it.first.percentageFunded()
)
}
projectForDeadlineCountdownDetail = projectAndIsFeatured
.map { it.first }
projectPhotoUrl = projectAndIsFeatured
.map {
Pair.create(
it.first.photo(), it.second
)
}
.filter { ObjectUtils.isNotNull(it.first) }
.map {
if (it.second)
it.first?.full()
else
it.first?.med()
}
projectNameTextViewText = projectAndIsFeatured
.map { it.first.name() }
notifyDelegateOfResultClick = projectAndIsFeatured
.map { PairUtils.first(it) }
.compose(Transformers.takeWhen(projectClicked))
}
override fun configureWith(projectAndIsFeatured: Pair<Project, Boolean>) {
this.projectAndIsFeatured.onNext(projectAndIsFeatured)
}
override fun projectClicked() {
projectClicked.onNext(null)
}
override fun deadlineCountdownValueTextViewText(): Observable<String> = deadlineCountdownValueTextViewText
override fun notifyDelegateOfResultClick(): Observable<Project> = notifyDelegateOfResultClick
override fun percentFundedTextViewText(): Observable<String> = percentFundedTextViewText
override fun projectForDeadlineCountdownUnitTextView(): Observable<Project> = projectForDeadlineCountdownDetail
override fun projectPhotoUrl(): Observable<String> = projectPhotoUrl
override fun projectNameTextViewText(): Observable<String> = projectNameTextViewText
}
}
| apache-2.0 | 937de74e16ee1ea8d0a295d77296eeac | 37.644628 | 119 | 0.657827 | 5.560048 | false | false | false | false |
ericfabreu/ktmdb | ktmdb/src/main/kotlin/com/ericfabreu/ktmdb/utils/MediaHelper.kt | 1 | 2105 | package com.ericfabreu.ktmdb.utils
import com.beust.klaxon.JsonObject
/**
* Utility functions and constants for images.
*/
@Suppress("UNUSED")
object MediaHelper {
/* All possible sizes according to the configuration file
* https://developers.themoviedb.org/3/configuration */
enum class ImageSize(val size: String) {
BACKDROP_W300("w300"),
BACKDROP_W780("w780"),
BACKDROP_W1280("w1280"),
LOGO_W45("w45"),
LOGO_W92("w92"),
LOGO_W154("w154"),
LOGO_W185("w300"),
LOGO_W500("w500"),
POSTER_W92("w92"),
POSTER_W154("w154"),
POSTER_W185("w185"),
POSTER_W342("w342"),
POSTER_W500("w500"),
POSTER_W780("w780"),
PROFILE_W45("w45"),
PROFILE_W185("w185"),
PROFILE_H632("h632"),
STILL_W92("w92"),
STILL_W185("w185"),
STILL_W300("w300"),
ORIGINAL("original")
}
enum class MediaType(val str: String) {
MOVIE("movie"),
TV("tv")
}
data class ImageFile(private val lst: JsonObject) {
val aspectRatio = lst["aspect_ratio"] as Double
val path = lst["file_path"] as String
val height = lst["height"] as Int
val width = lst["width"] as Int
// This ensures that Kotlin will not crash if it sees a 0 and thinks it is an integer
val voteAverage = lst["vote_average"].toString().toDouble()
val voteCount = lst["vote_count"] as Int
val language = lst["iso_639_1"] as String?
}
data class VideoFile(private val lst: JsonObject) {
val id = lst["id"] as String
val language = lst["iso_639_1"] as String
val region = lst["iso_3166_1"] as String
val key = lst["key"] as String
val name = lst["name"] as String
val site = lst["site"] as String
val size = lst["size"] as Int
val type = lst["type"] as String
}
private const val IMG_BASE_URL = "https://image.tmdb.org/t/p/"
fun getImageLink(path: String?, size: ImageSize): String = IMG_BASE_URL + size.size + path
}
| mit | fab9cadee324f960b293908fb8740409 | 30.41791 | 94 | 0.580048 | 3.573854 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowPaneState.kt | 4 | 1139 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.util.Pair
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.WindowInfo
import it.unimi.dsi.fastutil.objects.Object2FloatOpenHashMap
internal class ToolWindowPaneState {
private val idToSplitProportion = Object2FloatOpenHashMap<String>()
var maximizedProportion: Pair<ToolWindow, Int>? = null
var isStripesOverlaid = false
fun getPreferredSplitProportion(id: String?, defaultValue: Float): Float {
val f = idToSplitProportion.getFloat(id)
return if (f == 0f) defaultValue else f
}
fun addSplitProportion(info: WindowInfo, component: InternalDecoratorImpl?, splitter: Splitter) {
if (info.isSplit && component != null) {
idToSplitProportion.put(component.toolWindow.id, splitter.proportion)
}
}
fun isMaximized(window: ToolWindow): Boolean {
return maximizedProportion != null && maximizedProportion!!.first === window
}
} | apache-2.0 | 3b8e1b745ed64cf1b89f4b0f8243b02d | 37 | 140 | 0.76734 | 4.298113 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/links/downvoters/DownvotersActivity.kt | 1 | 3558 | package io.github.feelfreelinux.wykopmobilny.ui.modules.links.downvoters
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.base.BaseActivity
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Downvoter
import io.github.feelfreelinux.wykopmobilny.models.fragments.DataFragment
import io.github.feelfreelinux.wykopmobilny.models.fragments.getDataFragmentInstance
import io.github.feelfreelinux.wykopmobilny.models.fragments.removeDataFragment
import io.github.feelfreelinux.wykopmobilny.ui.adapters.DownvoterListAdapter
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.prepare
import kotlinx.android.synthetic.main.activity_conversations_list.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
class DownvotersActivity : BaseActivity(), androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener, DownvotersView {
companion object {
const val DATA_FRAGMENT_TAG = "DOWNVOTERS_LIST"
const val EXTRA_LINKID = "LINK_ID_EXTRA"
fun createIntent(linkId: Int, activity: Activity) =
Intent(activity, DownvotersActivity::class.java).apply {
putExtra(EXTRA_LINKID, linkId)
}
}
@Inject lateinit var presenter: DownvotersPresenter
@Inject lateinit var downvotersAdapter: DownvoterListAdapter
private lateinit var downvotersDataFragment: DataFragment<List<Downvoter>>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
downvotersDataFragment = supportFragmentManager.getDataFragmentInstance(DATA_FRAGMENT_TAG)
setContentView(R.layout.activity_voterslist)
setSupportActionBar(toolbar)
supportActionBar?.title = resources.getString(R.string.downvoters)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
swiperefresh.setOnRefreshListener(this)
recyclerView?.apply {
prepare()
adapter = downvotersAdapter
}
swiperefresh?.isRefreshing = false
presenter.linkId = intent.getIntExtra(EXTRA_LINKID, -1)
presenter.subscribe(this)
if (downvotersDataFragment.data == null) {
loadingView?.isVisible = true
onRefresh()
} else {
downvotersAdapter.items.addAll(downvotersDataFragment.data!!)
loadingView?.isVisible = false
}
}
override fun showDownvoters(downvoters: List<Downvoter>) {
loadingView?.isVisible = false
swiperefresh?.isRefreshing = false
downvotersAdapter.apply {
items.clear()
items.addAll(downvoters)
notifyDataSetChanged()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> finish()
}
return super.onOptionsItemSelected(item)
}
override fun onRefresh() = presenter.getDownvoters()
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
downvotersDataFragment.data = downvotersAdapter.items
}
override fun onDestroy() {
presenter.unsubscribe()
super.onDestroy()
}
override fun onPause() {
if (isFinishing) supportFragmentManager.removeDataFragment(downvotersDataFragment)
super.onPause()
}
} | mit | 211d2973505c3a427cc1b083f6a9c0bb | 36.861702 | 132 | 0.722316 | 5.032532 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/InlayTextMetrics.kt | 1 | 3492 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hints.presentation
import com.intellij.ide.ui.AntialiasingType
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.impl.FontInfo
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.Font
import java.awt.FontMetrics
import java.awt.font.FontRenderContext
import kotlin.math.ceil
import kotlin.math.max
@ApiStatus.Internal
class InlayTextMetricsStorage(val editor: EditorImpl) {
private var smallTextMetrics : InlayTextMetrics? = null
private var normalTextMetrics : InlayTextMetrics? = null
val smallTextSize: Int
@RequiresEdt
get() = max(1, editor.colorsScheme.editorFontSize - 1)
val normalTextSize: Int
@RequiresEdt
get() = editor.colorsScheme.editorFontSize
@RequiresEdt
fun getFontMetrics(small: Boolean): InlayTextMetrics {
var metrics: InlayTextMetrics?
if (small) {
metrics = smallTextMetrics
val fontSize = smallTextSize
if (metrics == null || !metrics.isActual(smallTextSize)) {
metrics = InlayTextMetrics.create(editor, fontSize)
smallTextMetrics = metrics
}
} else {
metrics = normalTextMetrics
val fontSize = normalTextSize
if (metrics == null || !metrics.isActual(normalTextSize)) {
metrics = InlayTextMetrics.create(editor, fontSize)
normalTextMetrics = metrics
}
}
return metrics
}
}
class InlayTextMetrics(
private val editor: EditorImpl,
val fontHeight: Int,
val fontBaseline: Int,
private val fontMetrics: FontMetrics
) {
companion object {
fun create(editor: EditorImpl, size: Int) : InlayTextMetrics {
val familyName = UIUtil.getLabelFont().family
val font = UIUtil.getFontWithFallback(familyName, Font.PLAIN, size)
val context = getCurrentContext(editor)
val metrics = FontInfo.getFontMetrics(font, context)
// We assume this will be a better approximation to a real line height for a given font
val fontHeight = ceil(font.createGlyphVector(context, "Albpq@").visualBounds.height).toInt()
val fontBaseline = ceil(font.createGlyphVector(context, "Alb").visualBounds.height).toInt()
return InlayTextMetrics(editor, fontHeight, fontBaseline, metrics)
}
private fun getCurrentContext(editor: Editor): FontRenderContext {
val editorContext = FontInfo.getFontRenderContext(editor.contentComponent)
return FontRenderContext(editorContext.transform,
AntialiasingType.getKeyForCurrentScope(false),
UISettings.editorFractionalMetricsHint)
}
}
val font: Font
get() = fontMetrics.font
// Editor metrics:
val ascent: Int
get() = editor.ascent
val descent: Int
get() = editor.descent
fun isActual(size: Int) : Boolean {
if (size != font.size) return false
return getCurrentContext(editor).equals(fontMetrics.fontRenderContext)
}
/**
* Offset from the top edge of drawing rectangle to rectangle with text.
*/
fun offsetFromTop(): Int = (editor.lineHeight - fontHeight) / 2
fun getStringWidth(text: String): Int {
return fontMetrics.stringWidth(text)
}
} | apache-2.0 | b7c527388ee495cb92d6b4875953f8a9 | 33.245098 | 140 | 0.724227 | 4.558747 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/ranges/ProgressionIterators.kt | 2 | 2439 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin.ranges
/**
* An iterator over a progression of values of type `Char`.
* @property step the number by which the value is incremented on each step.
*/
internal class CharProgressionIterator(first: Char, last: Char, val step: Int) : CharIterator() {
private val finalElement = last.toInt()
private var hasNext: Boolean = if (step > 0) first <= last else first >= last
private var next = if (hasNext) first.toInt() else finalElement
override fun hasNext(): Boolean = hasNext
override fun nextChar(): Char {
val value = next
if (value == finalElement) {
if (!hasNext) throw kotlin.NoSuchElementException()
hasNext = false
}
else {
next += step
}
return value.toChar()
}
}
/**
* An iterator over a progression of values of type `Int`.
* @property step the number by which the value is incremented on each step.
*/
internal class IntProgressionIterator(first: Int, last: Int, val step: Int) : IntIterator() {
private val finalElement = last
private var hasNext: Boolean = if (step > 0) first <= last else first >= last
private var next = if (hasNext) first else finalElement
override fun hasNext(): Boolean = hasNext
override fun nextInt(): Int {
val value = next
if (value == finalElement) {
if (!hasNext) throw kotlin.NoSuchElementException()
hasNext = false
}
else {
next += step
}
return value
}
}
/**
* An iterator over a progression of values of type `Long`.
* @property step the number by which the value is incremented on each step.
*/
internal class LongProgressionIterator(first: Long, last: Long, val step: Long) : LongIterator() {
private val finalElement = last
private var hasNext: Boolean = if (step > 0) first <= last else first >= last
private var next = if (hasNext) first else finalElement
override fun hasNext(): Boolean = hasNext
override fun nextLong(): Long {
val value = next
if (value == finalElement) {
if (!hasNext) throw kotlin.NoSuchElementException()
hasNext = false
}
else {
next += step
}
return value
}
} | apache-2.0 | dabee3d607986e07de531f3b498b5741 | 30.282051 | 101 | 0.626896 | 4.508318 | false | false | false | false |
jwren/intellij-community | plugins/evaluation-plugin/src/com/intellij/cce/actions/EvaluateCompletionForSelectedFilesAction.kt | 3 | 2308 | package com.intellij.cce.actions
import com.intellij.cce.EvaluationPluginBundle
import com.intellij.cce.dialog.FullSettingsDialog
import com.intellij.cce.evaluation.BackgroundStepFactory
import com.intellij.cce.evaluation.EvaluationProcess
import com.intellij.cce.evaluation.EvaluationRootInfo
import com.intellij.cce.util.FilesHelper
import com.intellij.cce.workspace.EvaluationWorkspace
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VirtualFile
class EvaluateCompletionForSelectedFilesAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)?.toList() ?: emptyList<VirtualFile>()
val language2files = FilesHelper.getFiles(project, files)
if (language2files.isEmpty()) {
Messages.showInfoMessage(project,
EvaluationPluginBundle.message("EvaluateCompletionForSelectedFilesAction.error.text"),
EvaluationPluginBundle.message("EvaluateCompletionForSelectedFilesAction.error.title"))
return
}
val dialog = FullSettingsDialog(project, files, language2files)
val result = dialog.showAndGet()
if (!result) return
val config = dialog.buildConfig()
val workspace = EvaluationWorkspace.create(config)
val process = EvaluationProcess.build({
shouldGenerateActions = true
shouldInterpretActions = true
shouldGenerateReports = true
}, BackgroundStepFactory(config, project, false, null, EvaluationRootInfo(true)))
process.startAsync(workspace)
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)?.isNotEmpty() ?: false
e.presentation.isVisible = e.place == ActionPlaces.ACTION_SEARCH || !ApplicationInfo.getInstance().build.isSnapshot
}
} | apache-2.0 | af1d010643c35059af55e6d7e0d419fe | 46.122449 | 123 | 0.722704 | 5.061404 | false | true | false | false |
jwren/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/RefreshIncomingChangesAction.kt | 5 | 1244 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.committed
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.committed.CacheSettingsDialog.showSettingsDialog
class RefreshIncomingChangesAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val project = e.project
e.presentation.isEnabled =
project != null &&
IncomingChangesViewProvider.VisibilityPredicate().test(project) &&
CommittedChangesCache.getInstanceIfCreated(project)?.isRefreshingIncomingChanges != true
}
override fun actionPerformed(e: AnActionEvent) = doRefresh(e.project!!)
companion object {
@JvmStatic
fun doRefresh(project: Project) {
val cache = CommittedChangesCache.getInstance(project)
cache.hasCachesForAnyRoot { hasCaches ->
if (!hasCaches && !showSettingsDialog(project)) return@hasCachesForAnyRoot
cache.refreshAllCachesAsync(true, false)
cache.refreshIncomingChangesAsync()
}
}
}
} | apache-2.0 | 5edfe5f0a20e2577c08f7e986d03dd47 | 36.727273 | 140 | 0.76045 | 4.641791 | false | false | false | false |
ninjahoahong/unstoppable | app/src/main/java/com/ninjahoahong/unstoppable/utils/FragmentStateChanger.kt | 1 | 2280 | package com.ninjahoahong.unstoppable.utils
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import com.ninjahoahong.unstoppable.R
import com.zhuinden.simplestack.StateChange
class FragmentStateChanger(
private val fragmentManager: FragmentManager,
private val containerId: Int
) {
fun handleStateChange(stateChange: StateChange) {
val fragmentTransaction = fragmentManager.beginTransaction().apply {
when (stateChange.direction) {
StateChange.FORWARD -> {
setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left, R.anim.slide_in_from_right, R.anim.slide_out_to_left)
}
StateChange.BACKWARD -> {
setCustomAnimations(R.anim.slide_in_from_left, R.anim.slide_out_to_right, R.anim.slide_in_from_left, R.anim.slide_out_to_right)
}
}
val previousState = stateChange.getPreviousState<BaseKey>()
val newState = stateChange.getNewState<BaseKey>()
for (oldKey in previousState) {
val fragment = fragmentManager.findFragmentByTag(oldKey.fragmentTag)
if (fragment != null) {
if (!newState.contains(oldKey)) {
remove(fragment)
} else if (!fragment.isDetached) {
detach(fragment)
}
}
}
for (newKey in newState) {
var fragment: Fragment? = fragmentManager.findFragmentByTag(newKey.fragmentTag)
if (newKey == stateChange.topNewState<Any>()) {
if (fragment != null) {
if (fragment.isDetached) {
attach(fragment)
}
} else {
fragment = newKey.newFragment()
add(containerId, fragment, newKey.fragmentTag)
}
} else {
if (fragment != null && !fragment.isDetached) {
detach(fragment)
}
}
}
}
fragmentTransaction.commitAllowingStateLoss()
}
} | mit | 2552b5924ca5e69f9cc6d98de1501957 | 41.240741 | 147 | 0.536404 | 5.066667 | false | false | false | false |
androidx/androidx | wear/watchface/watchface/src/main/java/androidx/wear/watchface/CancellableUniqueTask.kt | 3 | 1371 | /*
* 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.wear.watchface
import android.os.Handler
/**
* Task posting helper which allows only one pending task at a time.
*/
internal class CancellableUniqueTask(private val handler: Handler) {
private var pendingTask: Runnable? = null
fun cancel() {
pendingTask?.let { handler.removeCallbacks(it) }
pendingTask = null
}
fun isPending() = (pendingTask != null)
fun postUnique(task: () -> Unit) {
postDelayedUnique(0, task)
}
fun postDelayedUnique(delayMillis: Long, task: () -> Unit) {
cancel()
val runnable = Runnable {
task()
pendingTask = null
}
handler.postDelayed(runnable, delayMillis)
pendingTask = runnable
}
} | apache-2.0 | 4b9706cfcb648f5c583ef23d66197e78 | 28.191489 | 75 | 0.67469 | 4.366242 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/preview/jcef/impl/IncrementalDOMBuilder.kt | 7 | 5338 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.ui.preview.jcef.impl
import com.intellij.openapi.diagnostic.thisLogger
import org.intellij.plugins.markdown.ui.preview.html.links.IntelliJImageGeneratingProvider
import org.jetbrains.annotations.ApiStatus
import org.jsoup.Jsoup
import org.jsoup.nodes.Comment
import org.jsoup.nodes.DataNode
import org.jsoup.nodes.Node
import org.jsoup.nodes.TextNode
import java.net.URI
import java.net.URISyntaxException
import java.net.URLEncoder
import java.nio.file.Path
import java.nio.file.Paths
@ApiStatus.Internal
class IncrementalDOMBuilder(
html: String,
private val basePath: Path?,
private val fileSchemeResourceProcessor: FileSchemeResourceProcessingStrategy? = null
) {
fun interface FileSchemeResourceProcessingStrategy {
fun processFileSchemeResource(basePath: Path, originalUri: URI): String?
}
private val document = Jsoup.parse(html)
private val builder = StringBuilder()
fun generateRenderClosure(): String {
// language=JavaScript
return """
() => {
const o = (tag, ...attrs) => IncrementalDOM.elementOpen(tag, null, null, ...attrs.map(decodeURIComponent));
const t = content => IncrementalDOM.text(decodeURIComponent(content));
const c = IncrementalDOM.elementClose;
${generateDomBuildCalls()}
}
"""
}
fun generateDomBuildCalls(): String {
traverse(document.body())
return builder.toString()
}
private fun ensureCorrectTag(name: String): String {
return when (name) {
"body" -> "div"
else -> name
}
}
private fun encodeArgument(argument: String): String {
return URLEncoder.encode(argument, Charsets.UTF_8).replace("+", "%20")
}
private fun openTag(node: Node) {
with(builder) {
append("o('")
append(ensureCorrectTag(node.nodeName()))
append("'")
for (attribute in node.attributes()) {
append(",'")
append(attribute.key)
append('\'')
val value = attribute.value
@Suppress("SENSELESS_COMPARISON")
if (value != null) {
append(",'")
append(encodeArgument(value))
append("'")
}
}
append(");")
}
}
private fun closeTag(node: Node) {
with(builder) {
append("c('")
append(ensureCorrectTag(node.nodeName()))
append("');")
}
}
private fun textElement(getter: () -> String) {
with(builder) {
// It seems like CefBrowser::executeJavaScript() is not supporting a lot of unicode
// symbols (like emojis) in the code string (probably a limitation of CefString).
// To preserve these symbols, we are encoding our strings before sending them to JCEF,
// and decoding them before executing the code.
// For our use case it's enough to encode just the actual text content that
// will be displayed (only IncrementalDOM.text() calls).
append("t(`")
append(encodeArgument(getter.invoke()))
append("`);")
}
}
private fun preprocessNode(node: Node): Node {
if (fileSchemeResourceProcessor != null && basePath != null && shouldPreprocessImageNode(node)) {
try {
actuallyProcessImageNode(node, basePath, fileSchemeResourceProcessor)
} catch (exception: Throwable) {
val originalUrlValue = node.attr("src")
thisLogger().error("Failed to process image node\nbasePath: $basePath\noriginalUrl: $originalUrlValue", exception)
}
}
return node
}
private fun actuallyProcessImageNode(node: Node, basePath: Path, fileSchemeResourceProcessor: FileSchemeResourceProcessingStrategy) {
val originalUrlValue = node.attr("src")
val uri = when {
originalUrlValue.startsWith("file:/") -> createUri(originalUrlValue)
else -> createFileUri(originalUrlValue, basePath) ?: createUri(originalUrlValue)
}
if (uri != null && (uri.scheme == null || uri.scheme == "file")) {
val processed = fileSchemeResourceProcessor.processFileSchemeResource(basePath, uri) ?: return
node.attr("data-original-src", originalUrlValue)
node.attr("src", processed)
}
}
private fun shouldPreprocessImageNode(node: Node): Boolean {
return node.nodeName() == "img" && !node.hasAttr(IntelliJImageGeneratingProvider.ignorePathProcessingAttributeName)
}
private fun traverse(node: Node) {
when (node) {
is TextNode -> textElement { node.wholeText }
is DataNode -> textElement { node.wholeData }
is Comment -> Unit
else -> {
val preprocessed = preprocessNode(node)
openTag(preprocessed)
for (child in preprocessed.childNodes()) {
traverse(child)
}
closeTag(preprocessed)
}
}
}
companion object {
private fun createUri(string: String): URI? {
try {
return URI(string)
} catch (exception: URISyntaxException) {
return null
}
}
private fun createFileUri(string: String, basePath: Path?): URI? {
try {
val resolved = basePath?.resolve(string) ?: Paths.get(string)
return resolved.toUri()
} catch(ignored: Throwable) {
return null
}
}
}
}
| apache-2.0 | 01beb836436e4bd48b175fb65a8384f5 | 31.351515 | 158 | 0.663919 | 4.332792 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/quickfixUtil.kt | 1 | 2821 | // 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.util
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.getDataFlowValueFactory
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.ifEmpty
inline fun <reified T : PsiElement> Diagnostic.createIntentionForFirstParentOfType(
factory: (T) -> KotlinQuickFixAction<T>?
) = psiElement.getNonStrictParentOfType<T>()?.let(factory)
fun createIntentionFactory(
factory: (Diagnostic) -> IntentionAction?
) = object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) = factory(diagnostic)
}
fun KtPrimaryConstructor.addConstructorKeyword(): PsiElement? {
val modifierList = this.modifierList ?: return null
val psiFactory = KtPsiFactory(this)
val constructor = if (valueParameterList == null) {
psiFactory.createPrimaryConstructor("constructor()")
} else {
psiFactory.createConstructorKeyword()
}
return addAfter(constructor, modifierList)
}
fun getDataFlowAwareTypes(
expression: KtExpression,
bindingContext: BindingContext = expression.analyze(),
originalType: KotlinType? = bindingContext.getType(expression)
): Collection<KotlinType> {
if (originalType == null) return emptyList()
val dataFlowInfo = bindingContext.getDataFlowInfoAfter(expression)
val dataFlowValueFactory = expression.getResolutionFacade().getDataFlowValueFactory()
val expressionType = bindingContext.getType(expression) ?: return listOf(originalType)
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(
expression, expressionType, bindingContext, expression.getResolutionFacade().moduleDescriptor
)
return dataFlowInfo.getCollectedTypes(dataFlowValue, expression.languageVersionSettings).ifEmpty { listOf(originalType) }
}
| apache-2.0 | c8c17d1b4ea630a2565268a88760823d | 46.016667 | 158 | 0.810705 | 5.055556 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/gradle-tooling/impl/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinGradlePluginVersionExtensions.kt | 2 | 497 | // 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.gradleTooling
fun KotlinGradlePluginVersion?.supportsKotlinAndroidMultiplatformSourceSetLayoutVersion2(): Boolean {
if (this == null) return false
return this >= "1.8.0-dev-1593"
}
fun KotlinGradlePluginVersion?.supportsKotlinAndroidSourceSetInfo(): Boolean {
if (this == null) return false
return this >= "1.8.0-dev-1593"
} | apache-2.0 | d057bca9c245d0a57e7f39bc1126e476 | 40.5 | 120 | 0.760563 | 4.04065 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspections/redundantSuspendModifier/test.kt | 9 | 1132 | // WITH_STDLIB
fun coroutine(block: suspend () -> Unit) {}
// Not redundant
suspend fun rootSuspend() {
coroutine {
empty()
}
}
// Redundant
suspend fun empty() {}
suspend fun suspendUser() = rootSuspend() // not redundant
open class My {
// Not redundant
open suspend fun baseSuspend() {
rootSuspend()
}
}
class Your : My() {
override fun baseSuspend() {
}
}
class SIterable {
operator fun iterator() = this
// Redundant
suspend operator fun hasNext(): Boolean = false
// Redundant
suspend operator fun next(): Int = 0
}
class SIterator {
// Redundant
suspend operator fun iterator() = this
operator fun hasNext(): Boolean = false
operator fun next(): Int = 0
}
// Not redundant
suspend fun foo() {
val iterable = SIterable()
coroutine {
for (x in iterable) {
println(x)
}
}
}
// Not redundant
suspend fun bar() {
val iterator = SIterator()
coroutine {
for (x in iterator) {
println(x)
}
}
}
interface Suspended {
// Not redundant
suspend fun bar()
} | apache-2.0 | 614beaf89ec4a491857ee58739616285 | 15.42029 | 58 | 0.583039 | 4.042857 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/NamingConventionInspections.kt | 4 | 17990 | // 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.analysis.AnalysisScope
import com.intellij.codeInspection.*
import com.intellij.codeInspection.reference.RefEntity
import com.intellij.codeInspection.reference.RefFile
import com.intellij.codeInspection.reference.RefPackage
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.ui.EditorTextField
import com.siyeh.ig.BaseGlobalInspection
import com.siyeh.ig.psiutils.TestUtils
import org.intellij.lang.annotations.Language
import org.intellij.lang.regexp.RegExpFileType
import org.jdom.Element
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit
import org.jetbrains.kotlin.idea.quickfix.RenameIdentifierFix
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.refactoring.isInjectedFragment
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType
import java.awt.BorderLayout
import java.util.regex.PatternSyntaxException
import javax.swing.JPanel
data class NamingRule(val message: String, val matcher: (String) -> Boolean)
private fun findRuleMessage(checkString: String, rules: Array<out NamingRule>): String? {
for (rule in rules) {
if (rule.matcher(checkString)) {
return rule.message
}
}
return null
}
private val START_UPPER = NamingRule(KotlinBundle.message("should.start.with.an.uppercase.letter")) {
it.getOrNull(0)?.isUpperCase() == false
}
private val START_LOWER = NamingRule(KotlinBundle.message("should.start.with.a.lowercase.letter")) {
it.getOrNull(0)?.isLowerCase() == false
}
private val NO_UNDERSCORES = NamingRule(KotlinBundle.message("should.not.contain.underscores")) {
'_' in it
}
private val NO_START_UPPER = NamingRule(KotlinBundle.message("should.not.start.with.an.uppercase.letter")) {
it.getOrNull(0)?.isUpperCase() == true
}
private val NO_START_UNDERSCORE = NamingRule(KotlinBundle.message("should.not.start.with.an.underscore")) {
it.startsWith('_')
}
private val NO_MIDDLE_UNDERSCORES = NamingRule(KotlinBundle.message("should.not.contain.underscores.in.the.middle.or.the.end")) {
'_' in it.substring(1)
}
private val NO_BAD_CHARACTERS = NamingRule(KotlinBundle.message("may.contain.only.letters.and.digits")) {
it.any { c -> c !in 'a'..'z' && c !in 'A'..'Z' && c !in '0'..'9' }
}
private val NO_BAD_CHARACTERS_OR_UNDERSCORE = NamingRule(KotlinBundle.message("may.contain.only.letters.digits.or.underscores")) {
it.any { c -> c !in 'a'..'z' && c !in 'A'..'Z' && c !in '0'..'9' && c != '_' }
}
class NamingConventionInspectionSettings(
private val entityName: String,
@Language("RegExp") val defaultNamePattern: String,
private val setNamePatternCallback: ((value: String) -> Unit),
private vararg val rules: NamingRule
) {
var nameRegex: Regex? = defaultNamePattern.toRegex()
var namePattern: String = defaultNamePattern
set(value) {
field = value
setNamePatternCallback.invoke(value)
nameRegex = try {
value.toRegex()
} catch (e: PatternSyntaxException) {
null
}
}
fun verifyName(element: PsiNameIdentifierOwner, holder: ProblemsHolder, additionalCheck: () -> Boolean) {
val name = element.name
val nameIdentifier = element.nameIdentifier
if (name != null && nameIdentifier != null && nameRegex?.matches(name) == false && additionalCheck()) {
val message = getNameMismatchMessage(name)
@NlsSafe
val descriptionTemplate = "$entityName ${KotlinBundle.message("text.name")} <code>#ref</code> $message #loc"
holder.registerProblem(
element.nameIdentifier!!,
descriptionTemplate,
RenameIdentifierFix()
)
}
}
fun getNameMismatchMessage(name: String): String {
if (namePattern != defaultNamePattern) {
return getDefaultErrorMessage()
}
return findRuleMessage(name, rules) ?: getDefaultErrorMessage()
}
fun getDefaultErrorMessage() = KotlinBundle.message("doesn.t.match.regex.0", namePattern)
fun createOptionsPanel(): JPanel = NamingConventionOptionsPanel(this)
private class NamingConventionOptionsPanel(settings: NamingConventionInspectionSettings) : JPanel() {
init {
layout = BorderLayout()
val regexField = EditorTextField(settings.namePattern, null, RegExpFileType.INSTANCE).apply {
setOneLineMode(true)
}
regexField.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(e: DocumentEvent) {
settings.namePattern = regexField.text
}
})
val labeledComponent = LabeledComponent.create(regexField, KotlinBundle.message("text.pattern"), BorderLayout.WEST)
add(labeledComponent, BorderLayout.NORTH)
}
}
}
sealed class NamingConventionInspection(
entityName: String,
@Language("RegExp") defaultNamePattern: String,
vararg rules: NamingRule
) : AbstractKotlinInspection() {
// Serialized inspection state
@Suppress("MemberVisibilityCanBePrivate")
var namePattern: String = defaultNamePattern
private val namingSettings = NamingConventionInspectionSettings(
entityName, defaultNamePattern,
setNamePatternCallback = { value ->
namePattern = value
},
rules = *rules
)
protected fun verifyName(element: PsiNameIdentifierOwner, holder: ProblemsHolder, additionalCheck: () -> Boolean = { true }) {
namingSettings.verifyName(element, holder, additionalCheck)
}
protected fun getNameMismatchMessage(name: String): String {
return namingSettings.getNameMismatchMessage(name)
}
override fun createOptionsPanel(): JPanel = namingSettings.createOptionsPanel()
override fun readSettings(node: Element) {
super.readSettings(node)
namingSettings.namePattern = namePattern
}
}
class ClassNameInspection : NamingConventionInspection(
KotlinBundle.message("class"),
"[A-Z][A-Za-z\\d]*",
START_UPPER, NO_UNDERSCORES, NO_BAD_CHARACTERS
) {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
verifyName(classOrObject, holder)
}
override fun visitEnumEntry(enumEntry: KtEnumEntry) {
// do nothing
}
}
}
}
class EnumEntryNameInspection : NamingConventionInspection(
KotlinBundle.message("enum.entry"),
"[A-Z]([A-Za-z\\d]*|[A-Z_\\d]*)",
START_UPPER, NO_BAD_CHARACTERS_OR_UNDERSCORE
) {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return enumEntryVisitor { enumEntry -> verifyName(enumEntry, holder) }
}
}
class FunctionNameInspection : NamingConventionInspection(
KotlinBundle.message("function"),
"[a-z][A-Za-z\\d]*",
START_LOWER, NO_UNDERSCORES, NO_BAD_CHARACTERS
) {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return namedFunctionVisitor { function ->
if (function.hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
return@namedFunctionVisitor
}
if (!TestUtils.isInTestSourceContent(function)) {
verifyName(function, holder) {
val functionName = function.name
val typeReference = function.typeReference
if (typeReference != null) {
typeReference.text != functionName
} else {
function.resolveToDescriptorIfAny()
?.returnType
?.fqName
?.takeUnless(FqName::isRoot)
?.shortName()
?.asString() != functionName
}
}
}
}
}
}
class TestFunctionNameInspection : NamingConventionInspection(
KotlinBundle.message("test.function"),
"[a-z][A-Za-z_\\d]*",
START_LOWER
) {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return namedFunctionVisitor { function ->
if (!TestUtils.isInTestSourceContent(function)) {
return@namedFunctionVisitor
}
if (function.nameIdentifier?.text?.startsWith("`") == true) {
return@namedFunctionVisitor
}
verifyName(function, holder)
}
}
}
abstract class PropertyNameInspectionBase protected constructor(
private val kind: PropertyKind,
entityName: String,
defaultNamePattern: String,
vararg rules: NamingRule
) : NamingConventionInspection(entityName, defaultNamePattern, *rules) {
protected enum class PropertyKind { NORMAL, PRIVATE, OBJECT_OR_TOP_LEVEL, CONST, LOCAL }
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return propertyVisitor { property ->
if (property.hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
return@propertyVisitor
}
if (property.getKind() == kind) {
verifyName(property, holder)
}
}
}
private fun KtProperty.getKind(): PropertyKind = when {
isLocal -> PropertyKind.LOCAL
containingClassOrObject is KtObjectDeclaration -> PropertyKind.OBJECT_OR_TOP_LEVEL
isTopLevel -> PropertyKind.OBJECT_OR_TOP_LEVEL
hasModifier(KtTokens.CONST_KEYWORD) -> PropertyKind.CONST
visibilityModifierType() == KtTokens.PRIVATE_KEYWORD -> PropertyKind.PRIVATE
else -> PropertyKind.NORMAL
}
}
class PropertyNameInspection :
PropertyNameInspectionBase(
PropertyKind.NORMAL, KotlinBundle.message("property"), "[a-z][A-Za-z\\d]*",
START_LOWER, NO_UNDERSCORES, NO_BAD_CHARACTERS
)
class ObjectPropertyNameInspection :
PropertyNameInspectionBase(
PropertyKind.OBJECT_OR_TOP_LEVEL,
KotlinBundle.message("object.or.top.level.property"),
"[A-Za-z][_A-Za-z\\d]*",
NO_START_UNDERSCORE, NO_BAD_CHARACTERS_OR_UNDERSCORE
)
class PrivatePropertyNameInspection :
PropertyNameInspectionBase(
PropertyKind.PRIVATE, KotlinBundle.message("private.property"), "_?[a-z][A-Za-z\\d]*",
NO_MIDDLE_UNDERSCORES, NO_BAD_CHARACTERS_OR_UNDERSCORE
)
class ConstPropertyNameInspection :
PropertyNameInspectionBase(PropertyKind.CONST, KotlinBundle.message("const.property"), "[A-Z][_A-Z\\d]*")
class LocalVariableNameInspection :
PropertyNameInspectionBase(
PropertyKind.LOCAL, KotlinBundle.message("local.variable"), "[a-z][A-Za-z\\d]*",
START_LOWER, NO_UNDERSCORES, NO_BAD_CHARACTERS
)
private class PackageNameInspectionLocal(
val parentInspection: InspectionProfileEntry,
val namingSettings: NamingConventionInspectionSettings
) : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return packageDirectiveVisitor { directive ->
val packageNameExpression = directive.packageNameExpression ?: return@packageDirectiveVisitor
val checkResult = checkPackageDirective(directive, namingSettings) ?: return@packageDirectiveVisitor
val descriptionTemplate = checkResult.toProblemTemplateString()
holder.registerProblem(
packageNameExpression,
descriptionTemplate,
RenamePackageFix()
)
}
}
companion object {
data class CheckResult(val errorMessage: String, val isForPart: Boolean)
@NlsSafe
fun CheckResult.toProblemTemplateString(): String {
return KotlinBundle.message("package.name") + if (isForPart) {
" <code>#ref</code> ${KotlinBundle.message("text.part")} $errorMessage #loc"
} else {
" <code>#ref</code> $errorMessage #loc"
}
}
fun checkPackageDirective(directive: KtPackageDirective, namingSettings: NamingConventionInspectionSettings): CheckResult? {
return checkQualifiedName(directive.qualifiedName, namingSettings)
}
fun checkQualifiedName(qualifiedName: String, namingSettings: NamingConventionInspectionSettings): CheckResult? {
if (qualifiedName.isEmpty() || namingSettings.nameRegex?.matches(qualifiedName) != false) {
return null
}
val partErrorMessage = if (namingSettings.namePattern == namingSettings.defaultNamePattern) {
qualifiedName.split('.').asSequence()
.mapNotNull { part -> findRuleMessage(part, PackageNameInspection.PART_RULES) }
.firstOrNull()
} else {
null
}
return if (partErrorMessage != null) {
CheckResult(partErrorMessage, true)
} else {
CheckResult(namingSettings.getDefaultErrorMessage(), false)
}
}
}
private class RenamePackageFix : RenameIdentifierFix() {
override fun getElementToRename(element: PsiElement): PsiElement? {
val packageDirective = element as? KtPackageDirective ?: return null
return JavaPsiFacade.getInstance(element.project).findPackage(packageDirective.qualifiedName)
}
}
override fun getShortName(): String = parentInspection.shortName
override fun getDisplayName(): String = parentInspection.displayName
}
class PackageNameInspection : BaseGlobalInspection() {
companion object {
const val DEFAULT_PACKAGE_NAME_PATTERN = "[a-z_][a-zA-Z\\d_]*(\\.[a-z_][a-zA-Z\\d_]*)*"
val PART_RULES = arrayOf(NO_BAD_CHARACTERS_OR_UNDERSCORE, NO_START_UPPER)
@NlsSafe
private fun PackageNameInspectionLocal.Companion.CheckResult.toErrorMessage(qualifiedName: String): String {
return KotlinBundle.message("package.name") + if (isForPart) {
" <code>$qualifiedName</code> ${KotlinBundle.message("text.part")} $errorMessage"
} else {
" <code>$qualifiedName</code> $errorMessage"
}
}
}
// Serialized setting
@Suppress("MemberVisibilityCanBePrivate")
var namePattern: String = DEFAULT_PACKAGE_NAME_PATTERN
private val namingSettings = NamingConventionInspectionSettings(
KotlinBundle.message("text.Package"),
DEFAULT_PACKAGE_NAME_PATTERN,
setNamePatternCallback = { value ->
namePattern = value
}
)
override fun checkElement(
refEntity: RefEntity,
analysisScope: AnalysisScope,
inspectionManager: InspectionManager,
globalInspectionContext: GlobalInspectionContext
): Array<CommonProblemDescriptor>? {
when (refEntity) {
is RefFile -> {
val psiFile = refEntity.psiElement
if (psiFile is KtFile && !psiFile.isInjectedFragment && !psiFile.packageMatchesDirectoryOrImplicit()) {
val packageDirective = psiFile.packageDirective
if (packageDirective != null) {
val qualifiedName = packageDirective.qualifiedName
val checkResult = PackageNameInspectionLocal.checkPackageDirective(packageDirective, namingSettings)
if (checkResult != null) {
return arrayOf(inspectionManager.createProblemDescriptor(checkResult.toErrorMessage(qualifiedName)))
}
}
}
}
is RefPackage -> {
@NonNls val name = StringUtil.getShortName(refEntity.getQualifiedName())
if (name.isEmpty() || InspectionsBundle.message("inspection.reference.default.package") == name) {
return null
}
val checkResult = PackageNameInspectionLocal.checkQualifiedName(name, namingSettings)
if (checkResult != null) {
return arrayOf(inspectionManager.createProblemDescriptor(checkResult.toErrorMessage(name)))
}
}
else -> {
return null
}
}
return null
}
override fun readSettings(element: Element) {
super.readSettings(element)
namingSettings.namePattern = namePattern
}
override fun createOptionsPanel() = namingSettings.createOptionsPanel()
override fun getSharedLocalInspectionTool(): LocalInspectionTool {
return PackageNameInspectionLocal(this, namingSettings)
}
} | apache-2.0 | 11ec9dcf4169d8aebe4715fb3ead03e0 | 37.197452 | 158 | 0.6607 | 4.970986 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/views/ExpandableMathStatisticsView.kt | 1 | 5851 | package sk.styk.martin.apkanalyzer.views
import android.content.Context
import android.text.format.Formatter
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import sk.styk.martin.apkanalyzer.R
import sk.styk.martin.apkanalyzer.databinding.ViewMathStatisticsCardBinding
import sk.styk.martin.apkanalyzer.model.statistics.MathStatistics
import sk.styk.martin.apkanalyzer.ui.appdetail.page.activity.ARROW_ANIMATION_DURATION
import sk.styk.martin.apkanalyzer.ui.appdetail.page.activity.ROTATION_FLIPPED
import sk.styk.martin.apkanalyzer.ui.appdetail.page.activity.ROTATION_STANDARD
import sk.styk.martin.apkanalyzer.util.BigDecimalFormatter
class ExpandableMathStatisticsView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs) {
private val binding = ViewMathStatisticsCardBinding.inflate(LayoutInflater.from(context), this, true)
private var type: Type = Type.INTEGRAL
var title: String = ""
set(value) {
field = value
binding.itemTitle.text = value
}
var statistics: MathStatistics? = null
set(value) {
field = value
value?.let {
type.setStatistics(it, binding.itemArithmeticMean,
binding.itemMedian, binding.itemMin, binding.itemMax,
binding.itemDeviation, binding.itemVariance
)
}
}
var expandListener: OnClickListener? = null
set(value) {
field = value
binding.titleContainer.setOnClickListener(expandListener)
}
init {
val attributes = context.obtainStyledAttributes(attrs, R.styleable.ExpandableMathStatisticsView, 0, 0)
title = attributes.getString(R.styleable.ExpandableMathStatisticsView_title) ?: ""
type = Type.resolve(attributes.getString(R.styleable.ExpandableMathStatisticsView_type))
attributes.recycle()
orientation = VERTICAL
}
fun setExpanded(isExpanded: Boolean) {
binding.toggleArrow.animate().apply {
cancel()
setDuration(ARROW_ANIMATION_DURATION).rotation(if (isExpanded) ROTATION_FLIPPED else ROTATION_STANDARD)
}
binding.expandableContainer.setExpanded(isExpanded, true)
}
internal enum class Type {
INTEGRAL {
override fun setStatistics(statistics: MathStatistics, mean: NewDetailListItemView, median: NewDetailListItemView, min: NewDetailListItemView,
max: NewDetailListItemView, deviation: NewDetailListItemView, variance: NewDetailListItemView) {
mean.valueText = BigDecimalFormatter.getCommonFormat().format(statistics.arithmeticMean)
median.valueText = BigDecimalFormatter.getFormat(0, 0).format(statistics.median)
min.valueText = BigDecimalFormatter.getFormat(0, 0).format(statistics.min)
max.valueText = BigDecimalFormatter.getFormat(0, 0).format(statistics.max)
deviation.valueText = BigDecimalFormatter.getCommonFormat().format(statistics.deviation)
variance.valueText = BigDecimalFormatter.getCommonFormat().format(statistics.variance)
}
},
DECIMAL {
override fun setStatistics(statistics: MathStatistics, mean: NewDetailListItemView, median: NewDetailListItemView, min: NewDetailListItemView,
max: NewDetailListItemView, deviation: NewDetailListItemView, variance: NewDetailListItemView) {
mean.valueText = BigDecimalFormatter.getCommonFormat().format(statistics.arithmeticMean)
median.valueText = BigDecimalFormatter.getCommonFormat().format(statistics.median)
min.valueText = BigDecimalFormatter.getCommonFormat().format(statistics.min)
max.valueText = BigDecimalFormatter.getCommonFormat().format(statistics.max)
deviation.valueText = BigDecimalFormatter.getCommonFormat().format(statistics.deviation)
variance.valueText = BigDecimalFormatter.getCommonFormat().format(statistics.variance)
}
},
SIZE {
override fun setStatistics(statistics: MathStatistics, mean: NewDetailListItemView, median: NewDetailListItemView, min: NewDetailListItemView,
max: NewDetailListItemView, deviation: NewDetailListItemView, variance: NewDetailListItemView) {
mean.valueText = Formatter.formatShortFileSize(mean.context, statistics.arithmeticMean.toLong())
median.valueText = Formatter.formatShortFileSize(mean.context, statistics.median.toLong())
min.valueText = Formatter.formatShortFileSize(mean.context, statistics.min.toLong())
max.valueText = Formatter.formatShortFileSize(mean.context, statistics.max.toLong())
deviation.valueText = Formatter.formatShortFileSize(mean.context, statistics.deviation.toLong())
variance.valueText = Formatter.formatShortFileSize(mean.context, statistics.variance.toLong())
}
};
internal abstract fun setStatistics(statistics: MathStatistics, mean: NewDetailListItemView, median: NewDetailListItemView, min: NewDetailListItemView,
max: NewDetailListItemView, deviation: NewDetailListItemView, variance: NewDetailListItemView)
companion object {
fun resolve(stringAttribute: String?): Type {
return when (stringAttribute) {
"size" -> SIZE
"decimal" -> DECIMAL
"integral" -> INTEGRAL
else -> INTEGRAL
}
}
}
}
}
| gpl-3.0 | c81d366b12f59683422ebdee05f64e00 | 50.324561 | 159 | 0.678175 | 5.074588 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/util/ExternalApplicationsUtil.kt | 2 | 9248 | /*
* Copyright 2018 New Vector Ltd
*
* 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 im.vector.util
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Browser
import android.provider.MediaStore
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import im.vector.BuildConfig
import im.vector.R
import org.jetbrains.anko.toast
import org.matrix.androidsdk.core.Log
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
private const val LOG_TAG = "ExternalApplicationsUtil"
/**
* Open a url in the internet browser of the system
*/
fun openUrlInExternalBrowser(context: Context, url: String?) {
url?.let {
openUrlInExternalBrowser(context, Uri.parse(it))
}
}
/**
* Open a uri in the internet browser of the system
*/
fun openUrlInExternalBrowser(context: Context, uri: Uri?) {
uri?.let {
val browserIntent = Intent(Intent.ACTION_VIEW, it).apply {
putExtra(Browser.EXTRA_APPLICATION_ID, context.packageName)
putExtra(Browser.EXTRA_CREATE_NEW_TAB, true)
}
try {
context.startActivity(browserIntent)
} catch (activityNotFoundException: ActivityNotFoundException) {
context.toast(R.string.error_no_external_application_found)
}
}
}
/**
* Open sound recorder external application
*/
fun openSoundRecorder(activity: Activity, requestCode: Int) {
val recordSoundIntent = Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION)
// Create chooser
val chooserIntent = Intent.createChooser(recordSoundIntent, activity.getString(R.string.go_on_with))
try {
activity.startActivityForResult(chooserIntent, requestCode)
} catch (activityNotFoundException: ActivityNotFoundException) {
activity.toast(R.string.error_no_external_application_found)
}
}
/**
* Open file selection activity
*/
fun openFileSelection(activity: Activity,
fragment: Fragment?,
allowMultipleSelection: Boolean,
requestCode: Int) {
val fileIntent = Intent(Intent.ACTION_GET_CONTENT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
fileIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, allowMultipleSelection)
}
fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
fileIntent.type = "*/*"
try {
fragment
?.startActivityForResult(fileIntent, requestCode)
?: run {
activity.startActivityForResult(fileIntent, requestCode)
}
} catch (activityNotFoundException: ActivityNotFoundException) {
activity.toast(R.string.error_no_external_application_found)
}
}
/**
* Open external video recorder
*/
fun openVideoRecorder(activity: Activity, requestCode: Int) {
val captureIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
// lowest quality
captureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0)
try {
activity.startActivityForResult(captureIntent, requestCode)
} catch (activityNotFoundException: ActivityNotFoundException) {
activity.toast(R.string.error_no_external_application_found)
}
}
/**
* Open external camera
* @return the latest taken picture camera uri
*/
fun openCamera(activity: Activity, titlePrefix: String, requestCode: Int): String? {
val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
// the following is a fix for buggy 2.x devices
val date = Date()
val formatter = SimpleDateFormat("yyyyMMddHHmmss", Locale.US)
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, titlePrefix + formatter.format(date))
// The Galaxy S not only requires the name of the file to output the image to, but will also not
// set the mime type of the picture it just took (!!!). We assume that the Galaxy S takes image/jpegs
// so the attachment uploader doesn't freak out about there being no mimetype in the content database.
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
var dummyUri: Uri? = null
try {
dummyUri = activity.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
if (null == dummyUri) {
Log.e(LOG_TAG, "Cannot use the external storage media to save image")
}
} catch (uoe: UnsupportedOperationException) {
Log.e(LOG_TAG, "Unable to insert camera URI into MediaStore.Images.Media.EXTERNAL_CONTENT_URI"
+ " - no SD card? Attempting to insert into device storage.", uoe)
} catch (e: Exception) {
Log.e(LOG_TAG, "Unable to insert camera URI into MediaStore.Images.Media.EXTERNAL_CONTENT_URI. $e", e)
}
if (null == dummyUri) {
try {
dummyUri = activity.contentResolver.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values)
if (null == dummyUri) {
Log.e(LOG_TAG, "Cannot use the internal storage to save media to save image")
}
} catch (e: Exception) {
Log.e(LOG_TAG, "Unable to insert camera URI into internal storage. Giving up. $e", e)
}
}
if (dummyUri != null) {
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, dummyUri)
Log.d(LOG_TAG, "trying to take a photo on " + dummyUri.toString())
} else {
Log.d(LOG_TAG, "trying to take a photo with no predefined uri")
}
// Store the dummy URI which will be set to a placeholder location. When all is lost on Samsung devices,
// this will point to the data we're looking for.
// Because Activities tend to use a single MediaProvider for all their intents, this field will only be the
// *latest* TAKE_PICTURE Uri. This is deemed acceptable as the normal flow is to create the intent then immediately
// fire it, meaning onActivityResult/getUri will be the next thing called, not another createIntentFor.
val result = if (dummyUri == null) null else dummyUri.toString()
try {
activity.startActivityForResult(captureIntent, requestCode)
return result
} catch (activityNotFoundException: ActivityNotFoundException) {
activity.toast(R.string.error_no_external_application_found)
}
return null
}
/**
* Send an email to address with optional subject and message
*/
fun sendMailTo(address: String, subject: String? = null, message: String? = null, activity: Activity) {
val intent = Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", address, null))
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, message)
try {
activity.startActivity(intent)
} catch (activityNotFoundException: ActivityNotFoundException) {
activity.toast(R.string.error_no_external_application_found)
}
}
/**
* Open an arbitrary uri
*/
fun openUri(activity: Activity, uri: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri))
try {
activity.startActivity(intent)
} catch (activityNotFoundException: ActivityNotFoundException) {
activity.toast(R.string.error_no_external_application_found)
}
}
/**
* Send media to a third party application.
*
* @param activity the activity
* @param savedMediaPath the media path
* @param mimeType the media mime type.
*/
fun openMedia(activity: Activity, savedMediaPath: String, mimeType: String) {
val file = File(savedMediaPath)
val uri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".fileProvider", file)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, mimeType)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
try {
activity.startActivity(intent)
} catch (activityNotFoundException: ActivityNotFoundException) {
activity.toast(R.string.error_no_external_application_found)
}
}
/**
* Open the play store to the provided application Id
*/
fun openPlayStore(activity: Activity, appId: String) {
try {
activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appId")))
} catch (activityNotFoundException: android.content.ActivityNotFoundException) {
try {
activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$appId")))
} catch (activityNotFoundException: ActivityNotFoundException) {
activity.toast(R.string.error_no_external_application_found)
}
}
} | apache-2.0 | 81216d2c73d9d374b20e75ba9fbc784d | 34.988327 | 129 | 0.696367 | 4.269621 | false | false | false | false |
googlecodelabs/while-in-use-location | complete/src/main/java/com/example/android/whileinuselocation/MainActivity.kt | 1 | 12656 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.whileinuselocation
import android.Manifest
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.ServiceConnection
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.location.Location
import android.net.Uri
import android.os.Bundle
import android.os.IBinder
import android.provider.Settings
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.android.material.snackbar.Snackbar
private const val TAG = "MainActivity"
private const val REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE = 34
/**
* This app allows a user to receive location updates without the background permission even when
* the app isn't in focus. This is the preferred approach for Android.
*
* It does this by creating a foreground service (tied to a Notification) when the
* user navigates away from the app. Because of this, it only needs foreground or "while in use"
* location permissions. That is, there is no need to ask for location in the background (which
* requires additional permissions in the manifest).
*
* Note: Users have the following options in Android 11+ regarding location:
*
* * Allow all the time
* * Allow while app is in use, i.e., while app is in foreground (new in Android 10)
* * Allow one time use (new in Android 11)
* * Not allow location at all
*
* It is generally recommended you only request "while in use" location permissions (location only
* needed in the foreground), e.g., fine and coarse. If your app has an approved use case for
* using location in the background, request that permission in context and separately from
* fine/coarse location requests. In addition, if the user denies the request or only allows
* "while-in-use", handle it gracefully. To see an example of background location, please review
* {@link https://github.com/android/location-samples/tree/master/LocationUpdatesBackgroundKotlin}.
*
* Android 10 and higher also now requires developers to specify foreground service type in the
* manifest (in this case, "location").
*
* For the feature that requires location in the foreground, this sample uses a long-running bound
* and started service for location updates. The service is aware of foreground status of this
* activity, which is the only bound client in this sample.
*
* While getting location in the foreground, if the activity ceases to be in the foreground (user
* navigates away from the app), the service promotes itself to a foreground service and continues
* receiving location updates.
*
* When the activity comes back to the foreground, the foreground service stops, and the
* notification associated with that foreground service is removed.
*
* While the foreground service notification is displayed, the user has the option to launch the
* activity from the notification. The user can also remove location updates directly from the
* notification. This dismisses the notification and stops the service.
*/
class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
private var foregroundOnlyLocationServiceBound = false
// Provides location updates for while-in-use feature.
private var foregroundOnlyLocationService: ForegroundOnlyLocationService? = null
// Listens for location broadcasts from ForegroundOnlyLocationService.
private lateinit var foregroundOnlyBroadcastReceiver: ForegroundOnlyBroadcastReceiver
private lateinit var sharedPreferences: SharedPreferences
private lateinit var foregroundOnlyLocationButton: Button
private lateinit var outputTextView: TextView
// Monitors connection to the while-in-use service.
private val foregroundOnlyServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val binder = service as ForegroundOnlyLocationService.LocalBinder
foregroundOnlyLocationService = binder.service
foregroundOnlyLocationServiceBound = true
}
override fun onServiceDisconnected(name: ComponentName) {
foregroundOnlyLocationService = null
foregroundOnlyLocationServiceBound = false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
foregroundOnlyBroadcastReceiver = ForegroundOnlyBroadcastReceiver()
sharedPreferences =
getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE)
foregroundOnlyLocationButton = findViewById(R.id.foreground_only_location_button)
outputTextView = findViewById(R.id.output_text_view)
foregroundOnlyLocationButton.setOnClickListener {
val enabled = sharedPreferences.getBoolean(
SharedPreferenceUtil.KEY_FOREGROUND_ENABLED, false)
if (enabled) {
foregroundOnlyLocationService?.unsubscribeToLocationUpdates()
} else {
// TODO: Step 1.0, Review Permissions: Checks and requests if needed.
if (foregroundPermissionApproved()) {
foregroundOnlyLocationService?.subscribeToLocationUpdates()
?: Log.d(TAG, "Service Not Bound")
} else {
requestForegroundPermissions()
}
}
}
}
override fun onStart() {
super.onStart()
updateButtonState(
sharedPreferences.getBoolean(SharedPreferenceUtil.KEY_FOREGROUND_ENABLED, false)
)
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
val serviceIntent = Intent(this, ForegroundOnlyLocationService::class.java)
bindService(serviceIntent, foregroundOnlyServiceConnection, Context.BIND_AUTO_CREATE)
}
override fun onResume() {
super.onResume()
LocalBroadcastManager.getInstance(this).registerReceiver(
foregroundOnlyBroadcastReceiver,
IntentFilter(
ForegroundOnlyLocationService.ACTION_FOREGROUND_ONLY_LOCATION_BROADCAST)
)
}
override fun onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(
foregroundOnlyBroadcastReceiver
)
super.onPause()
}
override fun onStop() {
if (foregroundOnlyLocationServiceBound) {
unbindService(foregroundOnlyServiceConnection)
foregroundOnlyLocationServiceBound = false
}
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
super.onStop()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
// Updates button states if new while in use location is added to SharedPreferences.
if (key == SharedPreferenceUtil.KEY_FOREGROUND_ENABLED) {
updateButtonState(sharedPreferences.getBoolean(
SharedPreferenceUtil.KEY_FOREGROUND_ENABLED, false)
)
}
}
// TODO: Step 1.0, Review Permissions: Method checks if permissions approved.
private fun foregroundPermissionApproved(): Boolean {
return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
)
}
// TODO: Step 1.0, Review Permissions: Method requests permissions.
private fun requestForegroundPermissions() {
val provideRationale = foregroundPermissionApproved()
// If the user denied a previous request, but didn't check "Don't ask again", provide
// additional rationale.
if (provideRationale) {
Snackbar.make(
findViewById(R.id.activity_main),
R.string.permission_rationale,
Snackbar.LENGTH_LONG
)
.setAction(R.string.ok) {
// Request permission
ActivityCompat.requestPermissions(
this@MainActivity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE
)
}
.show()
} else {
Log.d(TAG, "Request foreground only permission")
ActivityCompat.requestPermissions(
this@MainActivity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE
)
}
}
// TODO: Step 1.0, Review Permissions: Handles permission result.
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
Log.d(TAG, "onRequestPermissionResult")
when (requestCode) {
REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE -> when {
grantResults.isEmpty() ->
// If user interaction was interrupted, the permission request
// is cancelled and you receive empty arrays.
Log.d(TAG, "User interaction was cancelled.")
grantResults[0] == PackageManager.PERMISSION_GRANTED ->
// Permission was granted.
foregroundOnlyLocationService?.subscribeToLocationUpdates()
else -> {
// Permission denied.
updateButtonState(false)
Snackbar.make(
findViewById(R.id.activity_main),
R.string.permission_denied_explanation,
Snackbar.LENGTH_LONG
)
.setAction(R.string.settings) {
// Build intent that displays the App settings screen.
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts(
"package",
BuildConfig.APPLICATION_ID,
null
)
intent.data = uri
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
.show()
}
}
}
}
private fun updateButtonState(trackingLocation: Boolean) {
if (trackingLocation) {
foregroundOnlyLocationButton.text = getString(R.string.stop_location_updates_button_text)
} else {
foregroundOnlyLocationButton.text = getString(R.string.start_location_updates_button_text)
}
}
private fun logResultsToScreen(output: String) {
val outputWithPreviousLogs = "$output\n${outputTextView.text}"
outputTextView.text = outputWithPreviousLogs
}
/**
* Receiver for location broadcasts from [ForegroundOnlyLocationService].
*/
private inner class ForegroundOnlyBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val location = intent.getParcelableExtra<Location>(
ForegroundOnlyLocationService.EXTRA_LOCATION
)
if (location != null) {
logResultsToScreen("Foreground location: ${location.toText()}")
}
}
}
}
| apache-2.0 | 0f124e087c9e08762a6982aff31c5ef3 | 40.495082 | 102 | 0.66585 | 5.464594 | false | false | false | false |
android/uamp | common/src/main/java/com/example/android/uamp/common/MusicServiceConnection.kt | 3 | 7813 | /*
* Copyright 2018 Google Inc. All rights reserved.
*
* 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.uamp.common
import android.content.ComponentName
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.ResultReceiver
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.lifecycle.MutableLiveData
import androidx.media.MediaBrowserServiceCompat
import com.example.android.uamp.common.MusicServiceConnection.MediaBrowserConnectionCallback
import com.example.android.uamp.media.NETWORK_FAILURE
import com.example.android.uamp.media.extensions.id
/**
* Class that manages a connection to a [MediaBrowserServiceCompat] instance, typically a
* [MusicService] or one of its subclasses.
*
* Typically it's best to construct/inject dependencies either using DI or, as UAMP does,
* using [InjectorUtils] in the app module. There are a few difficulties for that here:
* - [MediaBrowserCompat] is a final class, so mocking it directly is difficult.
* - A [MediaBrowserConnectionCallback] is a parameter into the construction of
* a [MediaBrowserCompat], and provides callbacks to this class.
* - [MediaBrowserCompat.ConnectionCallback.onConnected] is the best place to construct
* a [MediaControllerCompat] that will be used to control the [MediaSessionCompat].
*
* Because of these reasons, rather than constructing additional classes, this is treated as
* a black box (which is why there's very little logic here).
*
* This is also why the parameters to construct a [MusicServiceConnection] are simple
* parameters, rather than private properties. They're only required to build the
* [MediaBrowserConnectionCallback] and [MediaBrowserCompat] objects.
*/
class MusicServiceConnection(context: Context, serviceComponent: ComponentName) {
val isConnected = MutableLiveData<Boolean>()
.apply { postValue(false) }
val networkFailure = MutableLiveData<Boolean>()
.apply { postValue(false) }
val rootMediaId: String get() = mediaBrowser.root
val playbackState = MutableLiveData<PlaybackStateCompat>()
.apply { postValue(EMPTY_PLAYBACK_STATE) }
val nowPlaying = MutableLiveData<MediaMetadataCompat>()
.apply { postValue(NOTHING_PLAYING) }
val transportControls: MediaControllerCompat.TransportControls
get() = mediaController.transportControls
private val mediaBrowserConnectionCallback = MediaBrowserConnectionCallback(context)
private val mediaBrowser = MediaBrowserCompat(
context,
serviceComponent,
mediaBrowserConnectionCallback, null
).apply { connect() }
private lateinit var mediaController: MediaControllerCompat
fun subscribe(parentId: String, callback: MediaBrowserCompat.SubscriptionCallback) {
mediaBrowser.subscribe(parentId, callback)
}
fun unsubscribe(parentId: String, callback: MediaBrowserCompat.SubscriptionCallback) {
mediaBrowser.unsubscribe(parentId, callback)
}
fun sendCommand(command: String, parameters: Bundle?) =
sendCommand(command, parameters) { _, _ -> }
fun sendCommand(
command: String,
parameters: Bundle?,
resultCallback: ((Int, Bundle?) -> Unit)
) = if (mediaBrowser.isConnected) {
mediaController.sendCommand(command, parameters, object : ResultReceiver(Handler()) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
resultCallback(resultCode, resultData)
}
})
true
} else {
false
}
private inner class MediaBrowserConnectionCallback(private val context: Context) :
MediaBrowserCompat.ConnectionCallback() {
/**
* Invoked after [MediaBrowserCompat.connect] when the request has successfully
* completed.
*/
override fun onConnected() {
// Get a MediaController for the MediaSession.
mediaController = MediaControllerCompat(context, mediaBrowser.sessionToken).apply {
registerCallback(MediaControllerCallback())
}
isConnected.postValue(true)
}
/**
* Invoked when the client is disconnected from the media browser.
*/
override fun onConnectionSuspended() {
isConnected.postValue(false)
}
/**
* Invoked when the connection to the media browser failed.
*/
override fun onConnectionFailed() {
isConnected.postValue(false)
}
}
private inner class MediaControllerCallback : MediaControllerCompat.Callback() {
override fun onPlaybackStateChanged(state: PlaybackStateCompat?) {
playbackState.postValue(state ?: EMPTY_PLAYBACK_STATE)
}
override fun onMetadataChanged(metadata: MediaMetadataCompat?) {
// When ExoPlayer stops we will receive a callback with "empty" metadata. This is a
// metadata object which has been instantiated with default values. The default value
// for media ID is null so we assume that if this value is null we are not playing
// anything.
nowPlaying.postValue(
if (metadata?.id == null) {
NOTHING_PLAYING
} else {
metadata
}
)
}
override fun onQueueChanged(queue: MutableList<MediaSessionCompat.QueueItem>?) {
}
override fun onSessionEvent(event: String?, extras: Bundle?) {
super.onSessionEvent(event, extras)
when (event) {
NETWORK_FAILURE -> networkFailure.postValue(true)
}
}
/**
* Normally if a [MediaBrowserServiceCompat] drops its connection the callback comes via
* [MediaControllerCompat.Callback] (here). But since other connection status events
* are sent to [MediaBrowserCompat.ConnectionCallback], we catch the disconnect here and
* send it on to the other callback.
*/
override fun onSessionDestroyed() {
mediaBrowserConnectionCallback.onConnectionSuspended()
}
}
companion object {
// For Singleton instantiation.
@Volatile
private var instance: MusicServiceConnection? = null
fun getInstance(context: Context, serviceComponent: ComponentName) =
instance ?: synchronized(this) {
instance ?: MusicServiceConnection(context, serviceComponent)
.also { instance = it }
}
}
}
@Suppress("PropertyName")
val EMPTY_PLAYBACK_STATE: PlaybackStateCompat = PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_NONE, 0, 0f)
.build()
@Suppress("PropertyName")
val NOTHING_PLAYING: MediaMetadataCompat = MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, "")
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, 0)
.build()
| apache-2.0 | fdcf062138c793130731d861db9a8fc9 | 38.659898 | 97 | 0.692308 | 5.29336 | false | false | false | false |
android/uamp | automotive/src/main/java/com/example/android/uamp/automotive/PhoneSignInFragment.kt | 2 | 2809 | /*
* 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 com.example.android.uamp.automotive
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.text.HtmlCompat
import androidx.fragment.app.Fragment
import com.example.android.uamp.automotive.databinding.PhoneSignInBinding
/**
* Fragment that is used to facilitate phone sign-in. The fragment allows users to choose between
* either the PIN or QR code sign-in flow.
*/
class PhoneSignInFragment : Fragment(R.layout.phone_sign_in) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val context = requireContext()
val binding = PhoneSignInBinding.bind(view)
binding.toolbar.setNavigationOnClickListener {
requireActivity().supportFragmentManager.popBackStack()
}
// Set up PIN sign in button.
binding.appIcon.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.aural_logo))
binding.primaryMessage.text = getString(R.string.phone_sign_in_primary_text)
binding.pinSignInButton.text = getString(R.string.pin_sign_in_button_label)
binding.pinSignInButton.setOnClickListener {
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.sign_in_container, PinCodeSignInFragment())
.addToBackStack("landingPage")
.commit()
}
// Set up QR code sign in button.
binding.qrSignInButton.text = getString(R.string.qr_sign_in_button_label)
binding.qrSignInButton.setOnClickListener {
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.sign_in_container, QrCodeSignInFragment())
.addToBackStack("landingPage")
.commit()
}
// Links in footer text should be clickable.
binding.footer.text = HtmlCompat.fromHtml(
context.getString(R.string.sign_in_footer),
HtmlCompat.FROM_HTML_MODE_LEGACY
)
binding.footer.movementMethod = LinkMovementMethod.getInstance()
}
} | apache-2.0 | 73a17f04d5aae5f00847da90d8b6968d | 39.142857 | 99 | 0.706301 | 4.552674 | false | false | false | false |
fgsguedes/adventofcode | 2017/src/main/kotlin/day2/CorruptionChecksum.kt | 1 | 1207 | package day2
import fromMultipleLineInput
import kotlin.Int.Companion.MAX_VALUE
import kotlin.Int.Companion.MIN_VALUE
import kotlin.math.max
import kotlin.math.min
fun calcCheckSum(input: List<List<Int>>): Int {
return input.map { row ->
row.fold(MAX_VALUE to MIN_VALUE) { (currentMin, currentMax), rowElement ->
min(rowElement, currentMin) to max(rowElement, currentMax)
}
}.sumBy { (min, max) -> max - min }
}
fun calcCheckSumPart2(input: List<List<Int>>): Int {
return input.map { row ->
row.filter { element ->
row.any { innerElement ->
element != innerElement &&
(element % innerElement == 0 || innerElement % element == 0)
}
}.sorted()
}.sumBy { (first, second) -> second / first }
}
fun main(args: Array<String>) {
val input = fromMultipleLineInput(2017, 2, "CorruptionChecksumInput.txt") { rawInput ->
rawInput.map { row ->
row.split('\t').map { it.toInt() }
}
}
println(calcCheckSum(input))
val inputPart2 = fromMultipleLineInput(2017, 2, "CorruptionChecksumInputPart2.txt") { rawInput ->
rawInput.map { row ->
row.split('\t').map { it.toInt() }
}
}
println(calcCheckSumPart2(inputPart2))
}
| gpl-2.0 | ce8a82e67d329eef457e4f6911e1a8a2 | 27.738095 | 99 | 0.650373 | 3.4 | false | false | false | false |
ibinti/intellij-community | platform/platform-api/src/com/intellij/openapi/project/ProjectUtil.kt | 2 | 7837 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("ProjectUtil")
package com.intellij.openapi.project
import com.intellij.ide.DataManager
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.appSystemDir
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModifiableModuleModel
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFilePathWrapper
import com.intellij.util.PathUtilRt
import com.intellij.util.io.exists
import com.intellij.util.text.trimMiddle
import java.nio.file.InvalidPathException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.function.Consumer
import javax.swing.JComponent
val Module.rootManager: ModuleRootManager
get() = ModuleRootManager.getInstance(this)
@JvmOverloads
fun calcRelativeToProjectPath(file: VirtualFile, project: Project?, includeFilePath: Boolean = true, includeUniqueFilePath: Boolean = false, keepModuleAlwaysOnTheLeft: Boolean = false): String {
if (file is VirtualFilePathWrapper && file.enforcePresentableName()) {
return if (includeFilePath) file.presentablePath else file.name
}
val url = if (includeFilePath) {
file.presentableUrl
}
else if (includeUniqueFilePath) {
UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file)
}
else {
file.name
}
if (project == null) {
return url
}
return displayUrlRelativeToProject(file, url, project, includeFilePath, keepModuleAlwaysOnTheLeft)
}
fun guessProjectForFile(file: VirtualFile?): Project? = ProjectLocator.getInstance().guessProjectForFile(file)
/***
* guessProjectForFile works incorrectly - even if file is config (idea config file) first opened project will be returned
*/
@JvmOverloads
fun guessProjectForContentFile(file: VirtualFile, fileType: FileType = FileTypeManager.getInstance().getFileTypeByFileName(file.nameSequence)): Project? {
if (ProjectCoreUtil.isProjectOrWorkspaceFile(file, fileType)) {
return null
}
return ProjectManager.getInstance().openProjects.firstOrNull { !it.isDefault && it.isInitialized && !it.isDisposed && ProjectRootManager.getInstance(it).fileIndex.isInContent(file) }
}
fun isProjectOrWorkspaceFile(file: VirtualFile): Boolean = ProjectCoreUtil.isProjectOrWorkspaceFile(file)
fun guessCurrentProject(component: JComponent?): Project {
var project: Project? = null
if (component != null) {
project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component))
}
@Suppress("DEPRECATION")
return project
?: ProjectManager.getInstance().openProjects.firstOrNull()
?: CommonDataKeys.PROJECT.getData(DataManager.getInstance().dataContext)
?: ProjectManager.getInstance().defaultProject
}
inline fun <T> Project.modifyModules(crossinline task: ModifiableModuleModel.() -> T): T {
val model = ModuleManager.getInstance(this).modifiableModel
val result = model.task()
runWriteAction {
model.commit()
}
return result
}
fun isProjectDirectoryExistsUsingIo(parent: VirtualFile): Boolean {
try {
return Paths.get(FileUtil.toSystemDependentName(parent.path), Project.DIRECTORY_STORE_FOLDER).exists()
}
catch (e: InvalidPathException) {
return false
}
}
/**
* Tries to guess the "main project directory" of the project.
*
* There is no strict definition of what is a project directory, since a project can contain multiple modules located in different places,
* and the `.idea` directory can be located elsewhere (making the popular [Project.getBaseDir] method not applicable to get the "project
* directory"). This method should be preferred, although it can't provide perfect accuracy either.
*
* @throws IllegalStateException if called on the default project, since there is no sense in "project dir" in that case.
*/
fun Project.guessProjectDir() : VirtualFile {
if (isDefault) {
throw IllegalStateException("Not applicable for default project")
}
val modules = ModuleManager.getInstance(this).modules
val module = if (modules.size == 1) modules.first() else modules.find { it.name == this.name }
module?.rootManager?.contentRoots?.firstOrNull()?.let {
return it
}
return this.baseDir!!
}
private fun Project.getProjectCacheFileName(forceNameUse: Boolean, hashSeparator: String): String {
val presentableUrl = presentableUrl
var name = if (forceNameUse || presentableUrl == null) {
name
}
else {
// lower case here is used for cosmetic reasons (develar - discussed with jeka - leave it as it was, user projects will not have long names as in our tests)
PathUtilRt.getFileName(presentableUrl).toLowerCase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
name = FileUtil.sanitizeFileName(name, false)
// do not use project.locationHash to avoid prefix for IPR projects (not required in our case because name in any case is prepended).
val locationHash = Integer.toHexString((presentableUrl ?: name).hashCode())
// trim to avoid "File name too long"
name = name.trimMiddle(Math.min(name.length, 255 - hashSeparator.length - locationHash.length), useEllipsisSymbol = false)
return "$name$hashSeparator${locationHash}"
}
@JvmOverloads
fun Project.getProjectCachePath(cacheName: String, forceNameUse: Boolean = false): Path {
return getProjectCachePath(appSystemDir.resolve(cacheName), forceNameUse)
}
fun Project.getExternalConfigurationDir(): Path {
return getProjectCachePath("external_build_system")
}
/**
* Use parameters only for migration purposes, once all usages will be migrated, parameters will be removed
*/
@JvmOverloads
fun Project.getProjectCachePath(baseDir: Path, forceNameUse: Boolean = false, hashSeparator: String = "."): Path {
return baseDir.resolve(getProjectCacheFileName(forceNameUse, hashSeparator))
}
/**
* Add one-time projectOpened listener.
*/
fun Project.runWhenProjectOpened(handler: Runnable) = runWhenProjectOpened(this) { handler.run() }
/**
* Add one-time first projectOpened listener.
*/
@JvmOverloads
fun runWhenProjectOpened(project: Project? = null, handler: Consumer<Project>) = runWhenProjectOpened(project) { handler.accept(it) }
/**
* Add one-time projectOpened listener.
*/
inline fun runWhenProjectOpened(project: Project? = null, crossinline handler: (project: Project) -> Unit) {
val connection = (project ?: ApplicationManager.getApplication()).messageBus.connect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(eventProject: Project) {
if (project == null || project === eventProject) {
connection.disconnect()
handler(eventProject)
}
}
})
} | apache-2.0 | 1b90a7dfc72730c874642bf9b4e84a76 | 37.995025 | 194 | 0.76981 | 4.468073 | false | false | false | false |
AdamMc331/CashCaretaker | app/src/main/java/com/androidessence/cashcaretaker/ui/main/MainActivity.kt | 1 | 3362 | package com.androidessence.cashcaretaker.ui.main
import android.os.Bundle
import android.view.MenuItem
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.androidessence.cashcaretaker.R
import com.androidessence.cashcaretaker.ui.accountlist.AccountListFragment
import com.androidessence.cashcaretaker.ui.addaccount.AddAccountDialog
import com.androidessence.cashcaretaker.ui.transactionlist.TransactionListFragment
import timber.log.Timber
/**
* Main entry point into the application.
*/
class MainActivity :
AppCompatActivity(),
MainController,
FragmentManager.OnBackStackChangedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportFragmentManager.addOnBackStackChangedListener(this)
initializeBackButton()
if (savedInstanceState == null) {
showAccounts()
}
}
override fun navigateToAddAccount() {
val dialog = AddAccountDialog()
dialog.show(supportFragmentManager, AddAccountDialog.FRAGMENT_NAME)
}
override fun showTransactions(accountName: String) {
Timber.d("Showing Transactions")
showFragment(
TransactionListFragment.newInstance(accountName),
TransactionListFragment.FRAGMENT_NAME
)
}
override fun showAccounts() {
showFragment(AccountListFragment.newInstance(), AccountListFragment.FRAGMENT_NAME)
}
/**
* Displays a fragment inside this Activity.
*/
private fun showFragment(
fragment: Fragment,
tag: String,
@IdRes container: Int = R.id.container
) {
Timber.d("Adding fragment: $tag")
supportFragmentManager
.beginTransaction()
.replace(container, fragment, tag)
.addToBackStack(tag)
.commit()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
val backStackCount = supportFragmentManager.backStackEntryCount
if (backStackCount > 1) {
Timber.d("Popping BackStack")
supportFragmentManager.popBackStackImmediate()
} else {
finish()
}
}
override fun onBackStackChanged() {
initializeBackButton()
val lastPosition = supportFragmentManager.backStackEntryCount - 1
val lastEntry = supportFragmentManager.getBackStackEntryAt(lastPosition)
when (lastEntry.name) {
AccountListFragment.FRAGMENT_NAME -> supportActionBar?.setTitle(R.string.app_name)
}
}
/**
* Checks the size of the back stack and sets the visibility of the back button if necessary.
*/
private fun initializeBackButton() {
val shouldShowUp = supportFragmentManager.backStackEntryCount > 1
supportActionBar?.setDisplayHomeAsUpEnabled(shouldShowUp)
}
}
| mit | c6f0c98ee44d34a3c286ecb4a22ad61d | 30.12963 | 97 | 0.687686 | 5.353503 | false | false | false | false |
osfans/trime | app/src/main/java/com/osfans/trime/ui/main/LogActivity.kt | 1 | 4257 | package com.osfans.trime.ui.main
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import cat.ereza.customactivityoncrash.CustomActivityOnCrash
import com.osfans.trime.R
import com.osfans.trime.TrimeApplication
import com.osfans.trime.databinding.ActivityLogBinding
import com.osfans.trime.ui.components.log.LogView
import com.osfans.trime.util.DeviceInfo
import com.osfans.trime.util.Logcat
import com.osfans.trime.util.applyTranslucentSystemBars
import com.osfans.trime.util.iso8601UTCDateTime
import com.osfans.trime.util.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.launch
/**
* The activity to show [LogView].
*
* This file is adapted from fcitx5-android project.
* Source: [fcitx5-android/LogActivity](https://github.com/fcitx5-android/fcitx5-android/blob/24457e13b7c3f9f59a6f220db7caad3d02f27651/app/src/main/java/org/fcitx/fcitx5/android/ui/main/LogActivity.kt)
*/
class LogActivity : AppCompatActivity() {
private lateinit var launcher: ActivityResultLauncher<String>
private lateinit var logView: LogView
private fun registerLauncher() {
launcher = registerForActivityResult(ActivityResultContracts.CreateDocument("text/plain")) { uri ->
lifecycleScope.launch(NonCancellable + Dispatchers.IO) {
uri?.runCatching {
contentResolver.openOutputStream(this)?.use { os ->
os.bufferedWriter().use {
it.write(DeviceInfo.get(this@LogActivity))
it.write(logView.currentLog)
}
}
}?.toast()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
applyTranslucentSystemBars()
val binding = ActivityLogBinding.inflate(layoutInflater)
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, windowInsets ->
val statusBars = windowInsets.getInsets(WindowInsetsCompat.Type.statusBars())
val navBars = windowInsets.getInsets(WindowInsetsCompat.Type.navigationBars())
binding.root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
leftMargin = navBars.left
rightMargin = navBars.right
bottomMargin = navBars.bottom
}
binding.toolbar.toolbar.updateLayoutParams<ViewGroup.MarginLayoutParams> {
topMargin = statusBars.top
}
windowInsets
}
setContentView(binding.root)
with(binding) {
setSupportActionBar(toolbar.toolbar)
[email protected] = logView
logView.setLogcat(
if (CustomActivityOnCrash.getConfigFromIntent(intent) == null) {
supportActionBar!!.apply {
setDisplayHomeAsUpEnabled(true)
setTitle(R.string.real_time_logs)
}
Logcat()
} else {
supportActionBar!!.setTitle(R.string.crash_logs)
clearButton.visibility = View.GONE
AlertDialog.Builder(this@LogActivity)
.setTitle(R.string.app_crash)
.setMessage(R.string.app_crash_message)
.setPositiveButton(android.R.string.ok) { _, _ -> }
.show()
Logcat(TrimeApplication.getLastPid())
}
)
clearButton.setOnClickListener {
logView.clear()
}
exportButton.setOnClickListener {
launcher.launch("$packageName-${iso8601UTCDateTime()}.txt")
}
}
registerLauncher()
}
}
| gpl-3.0 | dea2e6f85cca892d678f84e15c8418b5 | 40.330097 | 201 | 0.645525 | 4.921387 | false | false | false | false |
gradle/gradle | build-logic/binary-compatibility/src/main/kotlin/gradlebuild/binarycompatibility/SortAcceptedApiChangesTask.kt | 2 | 2139 | /*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 gradlebuild.binarycompatibility
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.TaskAction
/**
* This [Task][org.gradle.api.Task] reorders the changes in an accepted API changes file
* so that they are alphabetically sorted (by type, then member).
*/
@CacheableTask
abstract class SortAcceptedApiChangesTask : AbstractAcceptedApiChangesMaintenanceTask() {
@TaskAction
fun execute() {
val sortedChanges = sortChanges(loadChanges())
val json = formatChanges(sortedChanges)
apiChangesFile.asFile.get().bufferedWriter().use { out -> out.write(json) }
}
private
fun formatChanges(changes: List<AbstractAcceptedApiChangesMaintenanceTask.AcceptedApiChange>): String {
val gson: Gson = GsonBuilder().setPrettyPrinting().create()
val initialString = gson.toJson(AcceptedApiChanges(changes))
return adjustIndentation(initialString) + "\n"
}
/**
* It appears there is no way to configure Gson to use 4 spaces instead of 2 for indentation.
*
* See: https://github.com/google/gson/blob/master/UserGuide.md#TOC-Compact-Vs.-Pretty-Printing-for-JSON-Output-Format
*/
private
fun adjustIndentation(initalJsonString: String): String {
val indentationRegex = """^\s+""".toRegex(RegexOption.MULTILINE)
return indentationRegex.replace(initalJsonString) { m ->
" ".repeat(m.value.length * 2)
}
}
}
| apache-2.0 | b6f0044b686d981e440998af402cb840 | 35.87931 | 122 | 0.71669 | 4.278 | false | false | false | false |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/api/policy/contextrules/PolicyContextRule.kt | 1 | 3008 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.api.policy.contextrules
import com.google.android.libraries.pcc.chronicle.util.TypedMap
/**
* This defines the basic structure of a context rule.
*
* `name` and `operands` are used internally for the ledger. `operands` refers to any rules that are
* used within the current rule.
*/
interface PolicyContextRule {
val name: String
val operands: List<PolicyContextRule>
/** Returns whether a rule is true/false, for the given context */
operator fun invoke(context: TypedMap): Boolean
}
/**
* This context rule always returns true, regardless of the context. It can be used as a default
* ContextRule if no rules need to be applied.
*/
object All : PolicyContextRule {
override val name = "All"
override val operands: List<PolicyContextRule> = emptyList()
override fun invoke(context: TypedMap): Boolean = true
}
/** Allows policy rule expressions such as `Rule1 and Rule2` */
infix fun PolicyContextRule.and(other: PolicyContextRule): PolicyContextRule = And(this, other)
/** Used to perform an `&&` operation on the boolean evaluations of two PolicyContextRules */
class And(private val lhs: PolicyContextRule, private val rhs: PolicyContextRule) :
PolicyContextRule {
override val name = "And"
override val operands: List<PolicyContextRule> = listOf(lhs, rhs)
override fun invoke(context: TypedMap): Boolean = lhs(context) && rhs(context)
}
/** Allows policy rule expressions such as `Rule1 or Rule2` */
infix fun PolicyContextRule.or(other: PolicyContextRule): PolicyContextRule = Or(this, other)
/** Used to perform an `||` operation on the boolean evaluations of two PolicyContextRules */
class Or(private val lhs: PolicyContextRule, private val rhs: PolicyContextRule) :
PolicyContextRule {
override val name = "Or"
override val operands: List<PolicyContextRule> = listOf(lhs, rhs)
override fun invoke(context: TypedMap): Boolean = lhs(context) || rhs(context)
}
/** Allows policy rule expressions such as `not(Rule1)` */
fun not(rule: PolicyContextRule): PolicyContextRule = Not(rule)
/** Used to perform an `!` operation on the boolean evaluation of a PolicyContextRule */
class Not(private val inner: PolicyContextRule) : PolicyContextRule {
override val name = "Not"
override val operands: List<PolicyContextRule> = listOf(inner)
override fun invoke(context: TypedMap): Boolean = !inner(context)
}
| apache-2.0 | 4c8971648913390aaf7aa8818f581d4a | 39.106667 | 100 | 0.748338 | 4.098093 | false | false | false | false |
google/private-compute-libraries | javatests/com/google/android/libraries/pcc/chronicle/codegen/backend/lens/BaseProtoLensBodyBuilderTest.kt | 1 | 2276 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.codegen.backend.lens
import com.google.android.libraries.pcc.chronicle.codegen.FieldCategory
import com.google.android.libraries.pcc.chronicle.codegen.FieldEntry
import com.google.android.libraries.pcc.chronicle.codegen.Type
import com.google.android.libraries.pcc.chronicle.codegen.TypeLocation
import com.google.common.truth.Truth.assertThat
import com.squareup.kotlinpoet.CodeBlock
import kotlin.test.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class BaseProtoLensBodyBuilderTest {
@Test
fun buildSetterBody() {
val impl =
object : BaseProtoLensBodyBuilder() {
override fun supportsField(type: Type, field: FieldEntry) = true
override fun buildGetterBody(
type: Type,
field: FieldEntry,
entityParamName: String
): CodeBlock = fail("Shouldn't be called.")
override fun buildSetterBuilderCode(
type: Type,
field: FieldEntry,
entityParamName: String,
newValueParamName: String
): CodeBlock = CodeBlock.of("println(\"Hello world\")\n")
}
val setterBody =
impl.buildSetterBody(
type = Type(TypeLocation("foo", pkg = ""), emptyList()),
field = FieldEntry("field", FieldCategory.IntValue),
entityParamName = "entity",
newValueParamName = "newValue"
)
assertThat(setterBody.toString())
.contains(
"""
entity.toBuilder()
.apply {
println("Hello world")
}
.build()
""".trimIndent()
)
}
}
| apache-2.0 | ed82f590ec90aa231c913fbfe4bfd3da | 31.514286 | 75 | 0.680141 | 4.302457 | false | true | false | false |
nsnikhil/Notes | app/src/main/java/com/nrs/nsnik/notes/util/DbUtil.kt | 1 | 15836 | /*
* Notes Copyright (C) 2018 Nikhil Soni
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.nrs.nsnik.notes.util
import androidx.lifecycle.LiveData
import com.nrs.nsnik.notes.dagger.scopes.ApplicationScope
import com.nrs.nsnik.notes.data.FolderEntity
import com.nrs.nsnik.notes.data.NoteEntity
import com.nrs.nsnik.notes.data.NotesDatabase
import io.reactivex.Completable
import io.reactivex.CompletableObserver
import io.reactivex.Single
import io.reactivex.SingleObserver
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import java.io.IOException
import javax.inject.Inject
@ApplicationScope
class DbUtil @Inject
internal constructor(private val mNotesDatabase: NotesDatabase, @param:ApplicationScope private val mFileUtil: FileUtil) {
val noteList: LiveData<List<NoteEntity>>
get() = mNotesDatabase.noteDao.notesList
val folderList: LiveData<List<FolderEntity>>
get() = mNotesDatabase.folderDao.foldersList
fun insertNote(vararg noteEntities: NoteEntity) {
val single = Single.fromCallable { mNotesDatabase.noteDao.insertNotes(*noteEntities) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<LongArray> {
override fun onSubscribe(d: Disposable) {
}
override fun onSuccess(longs: LongArray) {
noteEntities.forEach {
try {
mFileUtil.saveNote(it, it.fileName!!)
} catch (e: IOException) {
e.printStackTrace()
}
}
longs.forEach {
Timber.d(it.toString())
}
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun deleteNote(vararg noteEntities: NoteEntity) {
val completable = Completable.fromCallable {
mNotesDatabase.noteDao.deleteNotes(*noteEntities)
null
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
completable.subscribe(object : CompletableObserver {
override fun onSubscribe(d: Disposable) {
}
override fun onComplete() {
Timber.d("Delete successful")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun deleteNoteByFolderName(folderName: String) {
val completable = Completable.fromCallable {
mNotesDatabase.noteDao.deleteNoteByFolderName(folderName)
null
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
completable.subscribe(object : CompletableObserver {
override fun onSubscribe(d: Disposable) {
}
override fun onComplete() {
Timber.d("Delete successful")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun updateNote(vararg noteEntities: NoteEntity) {
val single = Single.fromCallable { mNotesDatabase.noteDao.updateNote(*noteEntities) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Int> {
override fun onSubscribe(d: Disposable) {
}
override fun onSuccess(t: Int) {
noteEntities.forEach {
try {
mFileUtil.saveNote(it, it.fileName!!)
} catch (e: IOException) {
e.printStackTrace()
}
}
Timber.d(t.toString())
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun getNoteById(id: Int): LiveData<NoteEntity> {
return mNotesDatabase.noteDao.getNote(id)
}
fun getNoteByFolderName(folderName: String): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNoteByFolderName(folderName)
}
fun getNoteByFolderNameNoPinNoLock(folderName: String): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNotesByFolderNameNotPinnedNotLocked(folderName)
}
fun getNoteByFolderNamePinNoLock(folderName: String): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNotesByFolderNamePinnedNotLocked(folderName)
}
fun getNoteByFolderNameNoPinLock(folderName: String): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNotesByFolderNameNotPinnedLocked(folderName)
}
fun getNoteByFolderNamePinLock(folderName: String): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNotesByFolderNamePinnedLocked(folderName)
}
fun getNoteByFolderNameOrdered(folderName: String): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNoteByFolderNameOrdered(folderName)
}
fun getNoteByFolderNameOrderedLock(folderName: String): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNoteByFolderNameOrderedLock(folderName)
}
fun searchNote(query: String): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNoteByQuery(query)
}
fun getNotesByPin(isPinned: Int): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNoteByPin(isPinned)
}
fun getNotesByLock(isLocked: Int): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNoteByLock(isLocked)
}
fun getNotesByColor(color: String): LiveData<List<NoteEntity>> {
return mNotesDatabase.noteDao.getNoteByColor(color)
}
fun changeNotePinStatus(id: Int, pin: Int) {
val single = Single.fromCallable {
mNotesDatabase.noteDao.changeNotePinStatus(id, pin)
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Unit> {
override fun onSubscribe(d: Disposable) {
}
override fun onSuccess(t: Unit) {
Timber.d("Updated")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun changeNoteLockStatus(id: Int, lock: Int) {
val single = Single.fromCallable {
mNotesDatabase.noteDao.changeNoteLockStatus(id, lock)
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Unit> {
override fun onSubscribe(d: Disposable) {
}
override fun onSuccess(t: Unit) {
Timber.d("Updated")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun changeNoteFolder(id: Int, folderName: String) {
val single = Single.fromCallable {
mNotesDatabase.noteDao.changeNoteFolder(id, folderName)
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Unit> {
override fun onSubscribe(d: Disposable) {
}
override fun onSuccess(t: Unit) {
Timber.d("Updated")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
/**
* FOLDER
*/
fun insertFolder(vararg folderEntities: FolderEntity) {
val single = Single.fromCallable {
mNotesDatabase.folderDao.insertFolders(*folderEntities)
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<LongArray> {
override fun onSubscribe(d: Disposable) {
}
override fun onSuccess(longs: LongArray) {
longs.forEach {
Timber.d(it.toString())
}
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun deleteFolder(vararg folderEntities: FolderEntity) {
val completable = Completable.fromCallable {
mNotesDatabase.folderDao.deleteFolders(*folderEntities)
null
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
completable.subscribe(object : CompletableObserver {
override fun onSubscribe(d: Disposable) {
}
override fun onComplete() {
Timber.d("Delete Successful")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun deleteFolderByName(folderName: String) {
val completable = Completable.fromCallable {
mNotesDatabase.folderDao.deleteFolderByName(folderName)
null
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
completable.subscribe(object : CompletableObserver {
override fun onSubscribe(d: Disposable) {
}
override fun onComplete() {
Timber.d("Delete Successful")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun deleteFolderByParent(parentFolderName: String) {
val completable = Completable.fromCallable {
mNotesDatabase.folderDao.deleteFolderByParent(parentFolderName)
null
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
completable.subscribe(object : CompletableObserver {
override fun onSubscribe(d: Disposable) {
}
override fun onComplete() {
Timber.d("Delete Successful")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun updateFolder(vararg folderEntities: FolderEntity) {
val single = Single.fromCallable { mNotesDatabase.folderDao.updateFolders(*folderEntities) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Int> {
override fun onSubscribe(d: Disposable) {
}
override fun onSuccess(t: Int) {
Timber.d(t.toString())
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun getFolders(): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolders()
}
fun getFolderById(id: Int): LiveData<FolderEntity> {
return mNotesDatabase.folderDao.getFolder(id)
}
fun getFolderByName(name: String): LiveData<FolderEntity> {
return mNotesDatabase.folderDao.getFolderByName(name)
}
fun searchFolder(query: String): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByQuery(query)
}
fun getFolderByParent(parentFolder: String): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByParent(parentFolder)
}
fun getFolderByParentNoPinNoLock(parentFolder: String): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByParentNoPinNoLock(parentFolder)
}
fun getFolderByParentPinNoLock(parentFolder: String): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByParentPinNoLock(parentFolder)
}
fun getFolderByParentNoPinLock(parentFolder: String): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByParentNoPinLock(parentFolder)
}
fun getFolderByParentPinLock(parentFolder: String): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByParentPinLock(parentFolder)
}
fun getFolderByParentOrdered(parentFolder: String): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByParentOrdered(parentFolder)
}
fun getFolderByParentOrderedLock(parentFolder: String): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByParentOrderedLock(parentFolder)
}
fun getFolderByPin(isPinned: Int): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByPin(isPinned)
}
fun getFolderByLock(isLocked: Int): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByLock(isLocked)
}
fun getFolderByColor(color: String): LiveData<List<FolderEntity>> {
return mNotesDatabase.folderDao.getFolderByColor(color)
}
fun changeFolderPinStatus(id: Int, pin: Int) {
val single = Single.fromCallable {
mNotesDatabase.folderDao.changeFolderPinStatus(id, pin)
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Unit> {
override fun onSubscribe(d: Disposable) {
}
override fun onSuccess(t: Unit) {
Timber.d("Updated")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun changeFolderLockStatus(id: Int, lock: Int) {
val single = Single.fromCallable {
mNotesDatabase.folderDao.changeFolderLockStatus(id, lock)
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Unit> {
override fun onSubscribe(d: Disposable) {
}
override fun onSuccess(t: Unit) {
Timber.d("Updated")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
fun changeFolderParent(id: Int, parentFolderName: String) {
val single = Single.fromCallable {
mNotesDatabase.folderDao.changeFolderParent(id, parentFolderName)
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
single.subscribe(object : SingleObserver<Unit> {
override fun onSubscribe(d: Disposable) {
}
override fun onSuccess(t: Unit) {
Timber.d("Updated")
}
override fun onError(e: Throwable) {
Timber.d(e.message)
}
})
}
}
| gpl-3.0 | 792539f603d2847f669b8c1cc4a1ca2d | 32.837607 | 171 | 0.632357 | 4.778515 | false | false | false | false |
commons-app/apps-android-commons | app/src/main/java/fr/free/nrw/commons/nearby/PlaceAdapterDelegate.kt | 5 | 4324 | package fr.free.nrw.commons.nearby
import android.view.View
import android.view.View.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.transition.TransitionManager
import com.hannesdorfmann.adapterdelegates4.dsl.AdapterDelegateViewBindingViewHolder
import com.hannesdorfmann.adapterdelegates4.dsl.adapterDelegateViewBinding
import fr.free.nrw.commons.R
import fr.free.nrw.commons.bookmarks.locations.BookmarkLocationsDao
import fr.free.nrw.commons.databinding.ItemPlaceBinding
fun placeAdapterDelegate(
bookmarkLocationDao: BookmarkLocationsDao,
onItemClick: ((Place) -> Unit)? = null,
onCameraClicked: (Place) -> Unit,
onGalleryClicked: (Place) -> Unit,
onBookmarkClicked: (Place, Boolean) -> Unit,
onOverflowIconClicked: (Place, View) -> Unit,
onDirectionsClicked: (Place) -> Unit
) = adapterDelegateViewBinding<Place, Place, ItemPlaceBinding>({ layoutInflater, parent ->
ItemPlaceBinding.inflate(layoutInflater, parent, false)
}) {
with(binding) {
root.setOnClickListener { _: View? ->
showOrHideAndScrollToIfLast()
onItemClick?.invoke(item)
}
root.setOnFocusChangeListener { view1: View?, hasFocus: Boolean ->
if (!hasFocus && nearbyButtonLayout.buttonLayout.isShown) {
nearbyButtonLayout.buttonLayout.visibility = GONE
} else if (hasFocus && !nearbyButtonLayout.buttonLayout.isShown) {
showOrHideAndScrollToIfLast()
onItemClick?.invoke(item)
}
}
nearbyButtonLayout.cameraButton.setOnClickListener { onCameraClicked(item) }
nearbyButtonLayout.galleryButton.setOnClickListener { onGalleryClicked(item) }
bookmarkButtonImage.setOnClickListener {
val isBookmarked = bookmarkLocationDao.updateBookmarkLocation(item)
bookmarkButtonImage.setImageResource(
if (isBookmarked) R.drawable.ic_round_star_filled_24px else R.drawable.ic_round_star_border_24px
)
onBookmarkClicked(item, isBookmarked)
}
nearbyButtonLayout.iconOverflow.setOnClickListener { onOverflowIconClicked(item, it) }
nearbyButtonLayout.directionsButton.setOnClickListener { onDirectionsClicked(item) }
bind {
tvName.text = item.name
val descriptionText: String = item.longDescription
if (descriptionText == "?") {
tvDesc.setText(R.string.no_description_found)
tvDesc.visibility = INVISIBLE
} else {
// Remove the label and display only texts inside pharentheses (description) since too long
tvDesc.text =
descriptionText.substringAfter(tvName.text.toString() + " (")
.substringBeforeLast(")");
}
distance.text = item.distance
icon.setImageResource(item.label.icon)
nearbyButtonLayout.iconOverflow.visibility =
if (item.hasCommonsLink() || item.hasWikidataLink()) VISIBLE
else GONE
bookmarkButtonImage.setImageResource(
if (bookmarkLocationDao.findBookmarkLocation(item))
R.drawable.ic_round_star_filled_24px
else
R.drawable.ic_round_star_border_24px
)
}
}
}
private fun AdapterDelegateViewBindingViewHolder<Place, ItemPlaceBinding>.showOrHideAndScrollToIfLast() {
with(binding) {
TransitionManager.beginDelayedTransition(nearbyButtonLayout.buttonLayout)
if (nearbyButtonLayout.buttonLayout.isShown) {
nearbyButtonLayout.buttonLayout.visibility = GONE
} else {
nearbyButtonLayout.buttonLayout.visibility = VISIBLE
val recyclerView = root.parent as RecyclerView
val lastPosition = recyclerView.adapter!!.itemCount - 1
if (recyclerView.getChildLayoutPosition(root) == lastPosition) {
(recyclerView.layoutManager as LinearLayoutManager?)
?.scrollToPositionWithOffset(
lastPosition,
nearbyButtonLayout.buttonLayout.height
)
}
}
}
}
| apache-2.0 | df0af09099282dd010e7c1ae762097cd | 44.041667 | 112 | 0.659112 | 5.093051 | false | false | false | false |
kittinunf/ReactiveAndroid | sample/src/main/kotlin/com.github.kittinunf.reactiveandroid.sample/view/LandingActivity.kt | 1 | 3737 | package com.github.kittinunf.reactiveandroid.sample.view
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.github.kittinunf.reactiveandroid.Property
import com.github.kittinunf.reactiveandroid.reactive.addTo
import com.github.kittinunf.reactiveandroid.sample.R
import com.github.kittinunf.reactiveandroid.scheduler.AndroidThreadScheduler
import com.github.kittinunf.reactiveandroid.widget.AdapterViewProxyAdapter
import com.github.kittinunf.reactiveandroid.widget.rx_itemsWith
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_landing.toolbar
import kotlinx.android.synthetic.main.activity_landing.toolbarSpinner
import kotlinx.android.synthetic.main.spinner_item.view.spinnerTextView
import kotlinx.android.synthetic.main.spinner_item_dropdown.view.spinnerTextViewDropdown
import java.util.concurrent.TimeUnit
import kotlin.reflect.KClass
class LandingActivity : AppCompatActivity() {
val subscriptions = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_landing)
setUpToolbar()
setUpButtons()
setUpTextView()
}
override fun onDestroy() {
super.onDestroy()
subscriptions.dispose()
}
private fun setUpToolbar() {
setSupportActionBar(toolbar)
val property = Property(listOf("Item 1", "Item 2", "Item 3"))
toolbarSpinner.rx_itemsWith(property.observable, ItemAdapter()).addTo(subscriptions)
title = ""
}
private fun setUpButtons() {
// toSignInPageButton.rx_click().map { SignInActivity::class }.subscribe(this::start).addTo(subscriptions)
// toSignUpPageButton.rx_click().map { SignUpActivity::class }.subscribe(this::start).addTo(subscriptions)
// toListPageButton.rx_click().map { RecyclerViewActivity::class }.subscribe(this::start).addTo(subscriptions)
// toSectionListPageButton.rx_click().map { SectionRecyclerViewActivity::class }.subscribe(this::start).addTo(subscriptions)
// toFragmentPagerButton.rx_click().map { FragmentPagerActivity::class }.subscribe { start(it) }.addTo(subscriptions)
// toNestedListButton.rx_click().map { NestedRecyclerViewActivity::class }.subscribe { start(it) }.addTo(subscriptions)
}
private fun setUpTextView() {
Observable.interval(5, TimeUnit.SECONDS, Schedulers.computation())
.map(Long::toString)
.observeOn(AndroidThreadScheduler.main)
// .bindTo(resultTextView.rx_text)
// .addTo(subscriptions)
}
fun start(clazz: KClass<*>) {
startActivity(Intent(this, clazz.java))
}
inner class ItemAdapter : AdapterViewProxyAdapter<String>() {
override fun getItemId(position: Int) = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
val view = convertView ?: LayoutInflater.from(this@LandingActivity).inflate(R.layout.spinner_item, parent, false)
view.spinnerTextView.text = this[position]
return view
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View? {
val view = convertView ?: LayoutInflater.from(this@LandingActivity).inflate(R.layout.spinner_item_dropdown, parent, false)
view.spinnerTextViewDropdown.text = this[position]
return view
}
}
}
| mit | 1ff195e0bbc308fcf04a658f5fe193e3 | 41.954023 | 134 | 0.728124 | 4.579657 | false | false | false | false |
luxons/seven-wonders | sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/converters/Boards.kt | 1 | 4419 | package org.luxons.sevenwonders.engine.converters
import org.luxons.sevenwonders.engine.Player
import org.luxons.sevenwonders.engine.boards.ScienceType
import org.luxons.sevenwonders.engine.effects.RawPointsIncrease
import org.luxons.sevenwonders.engine.moves.Move
import org.luxons.sevenwonders.engine.resources.Resources
import org.luxons.sevenwonders.model.Age
import org.luxons.sevenwonders.model.MoveType
import org.luxons.sevenwonders.model.cards.Color
import org.luxons.sevenwonders.model.cards.TableCard
import org.luxons.sevenwonders.model.resources.CountedResource
import org.luxons.sevenwonders.model.wonders.ApiWonder
import org.luxons.sevenwonders.model.wonders.ApiWonderStage
import org.luxons.sevenwonders.engine.boards.Board as InternalBoard
import org.luxons.sevenwonders.engine.boards.Military as InternalMilitary
import org.luxons.sevenwonders.engine.boards.Science as InternalScience
import org.luxons.sevenwonders.engine.cards.Requirements as InternalRequirements
import org.luxons.sevenwonders.engine.resources.Production as InternalProduction
import org.luxons.sevenwonders.engine.wonders.Wonder as InternalWonder
import org.luxons.sevenwonders.engine.wonders.WonderStage as InternalWonderStage
import org.luxons.sevenwonders.model.boards.Board as ApiBoard
import org.luxons.sevenwonders.model.boards.Military as ApiMilitary
import org.luxons.sevenwonders.model.boards.Production as ApiProduction
import org.luxons.sevenwonders.model.boards.Requirements as ApiRequirements
import org.luxons.sevenwonders.model.boards.Science as ApiScience
internal fun InternalBoard.toApiBoard(player: Player, lastMove: Move?, currentAge: Age): ApiBoard = ApiBoard(
playerIndex = playerIndex,
wonder = wonder.toApiWonder(player, lastMove),
production = production.toApiProduction(),
publicProduction = publicProduction.toApiProduction(),
science = science.toApiScience(),
military = military.toApiMilitary(),
playedCards = getPlayedCards().map { it.toTableCard(lastMove) }.toColumns(),
gold = gold,
bluePoints = getPlayedCards().filter { it.color == Color.BLUE }
.flatMap { it.effects.filterIsInstance<RawPointsIncrease>() }
.sumBy { it.points },
canPlayAnyCardForFree = canPlayFreeCard(currentAge),
)
internal fun List<TableCard>.toColumns(): List<List<TableCard>> {
val cardsByColor = this.groupBy { it.color }
val (resourceCardsCols, otherCols) = cardsByColor.values.partition { it[0].color.isResource }
val resourceCardsCol = resourceCardsCols.flatten()
val otherColsSorted = otherCols.sortedBy { it[0].color }
if (resourceCardsCol.isEmpty()) {
return otherColsSorted // we want only non-empty columns
}
return listOf(resourceCardsCol) + otherColsSorted
}
internal fun InternalWonder.toApiWonder(player: Player, lastMove: Move?): ApiWonder = ApiWonder(
name = name,
initialResource = initialResource,
stages = stages.map { it.toApiWonderStage(lastBuiltStage == it, lastMove) },
image = image,
nbBuiltStages = nbBuiltStages,
buildability = computeBuildabilityBy(player),
)
internal fun InternalWonderStage.toApiWonderStage(isLastBuiltStage: Boolean, lastMove: Move?): ApiWonderStage =
ApiWonderStage(
cardBack = cardBack,
isBuilt = isBuilt,
requirements = requirements.toApiRequirements(),
builtDuringLastMove = lastMove?.type == MoveType.UPGRADE_WONDER && isLastBuiltStage,
)
internal fun InternalProduction.toApiProduction(): ApiProduction = ApiProduction(
fixedResources = getFixedResources().toCountedResourcesList(),
alternativeResources = getAlternativeResources().sortedBy { it.size },
)
internal fun InternalRequirements.toApiRequirements(): ApiRequirements =
ApiRequirements(gold = gold, resources = resources.toCountedResourcesList())
internal fun Resources.toCountedResourcesList(): List<CountedResource> = //
quantities.filterValues { it > 0 } //
.map { (type, count) -> CountedResource(count, type) } //
.sortedBy { it.type }
internal fun InternalMilitary.toApiMilitary(): ApiMilitary =
ApiMilitary(nbShields, victoryPoints, totalPoints, nbDefeatTokens)
internal fun InternalScience.toApiScience(): ApiScience = ApiScience(
jokers = jokers,
nbWheels = getQuantity(ScienceType.WHEEL),
nbCompasses = getQuantity(ScienceType.COMPASS),
nbTablets = getQuantity(ScienceType.TABLET),
)
| mit | 99a8c9c49b94fc621070fccaf34874e2 | 47.032609 | 111 | 0.782077 | 4.161017 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/ui/AccountListFragment.kt | 1 | 4045 | /*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.ui
import android.accounts.Account
import android.accounts.AccountManager
import android.accounts.OnAccountsUpdateListener
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.fragment.app.ListFragment
import androidx.loader.app.LoaderManager
import androidx.loader.content.AsyncTaskLoader
import androidx.loader.content.Loader
import com.etesync.syncadapter.App
import com.etesync.syncadapter.R
class AccountListFragment : ListFragment(), LoaderManager.LoaderCallbacks<Array<Account>>, AdapterView.OnItemClickListener {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
listAdapter = AccountListAdapter(requireContext())
return inflater.inflate(R.layout.account_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
loaderManager.initLoader(0, arguments, this)
val list = listView
list.onItemClickListener = this
list.choiceMode = AbsListView.CHOICE_MODE_SINGLE
}
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val account = listAdapter?.getItem(position) as Account
val intent = Intent(context, AccountActivity::class.java)
intent.putExtra(AccountActivity.EXTRA_ACCOUNT, account)
startActivity(intent)
}
// loader
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Array<Account>> {
return AccountLoader(requireContext())
}
override fun onLoadFinished(loader: Loader<Array<Account>>, accounts: Array<Account>) {
val adapter = listAdapter as AccountListAdapter
adapter.clear()
adapter.addAll(*accounts)
}
override fun onLoaderReset(loader: Loader<Array<Account>>) {
(listAdapter as AccountListAdapter).clear()
}
private class AccountLoader(context: Context) : AsyncTaskLoader<Array<Account>>(context), OnAccountsUpdateListener {
private val accountManager = AccountManager.get(context)
override fun onStartLoading() =
accountManager.addOnAccountsUpdatedListener(this, null, true)
override fun onStopLoading() {
try {
accountManager.removeOnAccountsUpdatedListener(this)
} catch (e: IllegalArgumentException) {
// Do nothing. Just handle the case where for some reason the listener is not registered.
}
}
override fun onAccountsUpdated(accounts: Array<Account>) {
forceLoad()
}
@SuppressLint("MissingPermission")
override fun loadInBackground(): Array<Account>? {
return accountManager.getAccountsByType(App.accountType)
}
}
// list adapter
internal class AccountListAdapter(context: Context) : ArrayAdapter<Account>(context, R.layout.account_list_item) {
override fun getView(position: Int, _v: View?, parent: ViewGroup): View {
var v = _v
if (v == null)
v = LayoutInflater.from(context).inflate(R.layout.account_list_item, parent, false)
val account = getItem(position)
val tv = v!!.findViewById<View>(R.id.account_name) as TextView
tv.text = account!!.name
return v
}
}
}
| gpl-3.0 | 5553bd1bf88e91d45e8087a08c6b4178 | 33.547009 | 124 | 0.703365 | 4.9113 | false | false | false | false |
Tomlezen/RxCommons | lib/src/main/java/com/tlz/rxcommons/http/RxDownloader.kt | 1 | 4037 | package com.tlz.rxcommons.http
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableEmitter
import io.reactivex.android.MainThreadDisposable
import okhttp3.*
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
/**
* Created by LeiShao.
* Data 2017/5/24.
* Time 15:37.
* Email [email protected].
*/
class RxDownloader private constructor(private val httpClient: OkHttpClient) {
fun download(downloadUrl: String, saveFileDir: String): Flowable<File> =
download(downloadUrl, saveFileDir, downloadUrl.getFileName(), null)
fun download(downloadUrl: String, saveFileDir: String, saveFileName: String): Flowable<File> =
download(downloadUrl, saveFileDir, saveFileName, null)
fun download(downloadUrl: String, saveFileDir: String, progressCallback: ProgressCallback): Flowable<File> =
download(downloadUrl, saveFileDir, downloadUrl.getFileName(), progressCallback)
fun download(downloadUrl: String, saveFileDir: String, saveFileName: String?, progressCallback: ProgressCallback?): Flowable<File> =
Flowable.create({
val request = Request.Builder()
.url(downloadUrl)
.tag(downloadUrl)
.addHeader("Accept-Encoding", "identity")
.build()
val call = httpClient.newCall(request)
call.enqueue(ResponseCallback(it, saveFileDir, saveFileName, progressCallback))
it.setDisposable(object : MainThreadDisposable() {
override fun onDispose() {
call?.cancel()
}
})
}, BackpressureStrategy.LATEST)
private inner class ResponseCallback(
private val emitter: FlowableEmitter<File>,
private val saveFileDir: String,
private val saveFileName: String?,
private val progressCallback: ProgressCallback?
) : Callback {
override fun onFailure(call: Call?, e: IOException?) {
e?.let { emitter.onError(it) }
}
override fun onResponse(call: Call?, response: Response?) {
response?.body()?.let { body ->
try {
if (emitter.isCancelled) {
call?.cancel()
} else {
val totalSize = body.contentLength()
body.source()
body.byteStream()?.use {
progressCallback?.sendFileSize(totalSize)
val saveDir = File(saveFileDir).apply {
if (!exists()) {
mkdirs()
}
}
val fileName = "$saveFileName.temp"
val file = File(saveDir, fileName)
file.outputStream().use { out ->
var bytesCopied: Long = 0
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = it.read(buffer)
while (bytes >= 0 && !emitter.isCancelled) {
out.write(buffer, 0, bytes)
bytesCopied += bytes
progressCallback?.sendProgress((bytesCopied * 1.0f / totalSize * 100).toInt())
bytes = it.read(buffer)
}
if (bytesCopied == totalSize) {
val saveFile = File(saveFileDir, saveFileName)
if (file.renameTo(saveFile)) {
if (!emitter.isCancelled) {
emitter.onNext(saveFile)
emitter.onComplete()
}
} else if (!emitter.isCancelled) {
emitter.onError(FileNotFoundException())
}
} else if (!emitter.isCancelled) {
emitter.onError(FileNotFoundException())
}
}
} ?: emitter.onError(NullPointerException("InputStream is null!"))
}
} catch (e: Exception) {
emitter.onError(e)
}
} ?: emitter.onError(NullPointerException("response body is null"))
}
}
companion object {
fun newInstance(okHttpClient: OkHttpClient) = RxDownloader(okHttpClient)
}
}
| apache-2.0 | f1cfcac95239f85014afa6336965a24c | 35.7 | 134 | 0.594996 | 4.971675 | false | false | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/EmojiPopup.kt | 1 | 10927 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* 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.vanniktech.emoji
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.View
import android.view.WindowInsets
import android.view.autofill.AutofillManager
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.PopupWindow
import androidx.annotation.StyleRes
import androidx.core.view.ViewCompat
import androidx.viewpager.widget.ViewPager
import com.vanniktech.emoji.EmojiManager.verifyInstalled
import com.vanniktech.emoji.internal.EmojiResultReceiver
import com.vanniktech.emoji.internal.Utils
import com.vanniktech.emoji.internal.inputMethodManager
import com.vanniktech.emoji.listeners.OnEmojiBackspaceClickListener
import com.vanniktech.emoji.listeners.OnEmojiClickListener
import com.vanniktech.emoji.listeners.OnEmojiPopupDismissListener
import com.vanniktech.emoji.listeners.OnEmojiPopupShownListener
import com.vanniktech.emoji.listeners.OnSoftKeyboardCloseListener
import com.vanniktech.emoji.listeners.OnSoftKeyboardOpenListener
import com.vanniktech.emoji.recent.RecentEmoji
import com.vanniktech.emoji.recent.RecentEmojiManager
import com.vanniktech.emoji.search.SearchEmoji
import com.vanniktech.emoji.search.SearchEmojiManager
import com.vanniktech.emoji.variant.VariantEmoji
import com.vanniktech.emoji.variant.VariantEmojiManager
import java.lang.ref.WeakReference
class EmojiPopup @JvmOverloads constructor(
/** The root View of your layout.xml which will be used for calculating the height of the keyboard. */
rootView: View,
private val editText: EditText,
internal val theming: EmojiTheming = EmojiTheming.from(rootView.context),
/** Option to customize with your own implementation of recent emojis. To hide use [com.vanniktech.emoji.recent.NoRecentEmoji]. */
recentEmoji: RecentEmoji = RecentEmojiManager(rootView.context),
/** Option to customize with your own implementation of searching emojis. To hide use [com.vanniktech.emoji.search.NoSearchEmoji]. */
internal val searchEmoji: SearchEmoji = SearchEmojiManager(),
/** Option to customize with your own implementation of variant emojis. To hide use [com.vanniktech.emoji.variant.NoVariantEmoji]. */
variantEmoji: VariantEmoji = VariantEmojiManager(rootView.context),
pageTransformer: ViewPager.PageTransformer? = null,
@StyleRes keyboardAnimationStyle: Int = 0,
/**
* If height is not 0 then this value will be used later on. If it is 0 then the keyboard height will
* be dynamically calculated and set as [PopupWindow] height.
*/
private var popupWindowHeight: Int = 0,
private val onEmojiPopupShownListener: OnEmojiPopupShownListener? = null,
private val onSoftKeyboardCloseListener: OnSoftKeyboardCloseListener? = null,
private val onSoftKeyboardOpenListener: OnSoftKeyboardOpenListener? = null,
onEmojiBackspaceClickListener: OnEmojiBackspaceClickListener? = null,
onEmojiClickListener: OnEmojiClickListener? = null,
private val onEmojiPopupDismissListener: OnEmojiPopupDismissListener? = null,
) {
internal val rootView: View = rootView.rootView
internal val context: Activity = Utils.asActivity(rootView.context)
private val emojiView: EmojiView = EmojiView(context)
private val popupWindow: PopupWindow = PopupWindow(context)
private var isPendingOpen = false
private var isKeyboardOpen = false
private var globalKeyboardHeight = 0
private var delay = 0
private var originalImeOptions = -1
private val emojiResultReceiver = EmojiResultReceiver(Handler(Looper.getMainLooper()))
private val onDismissListener = PopupWindow.OnDismissListener {
onEmojiPopupDismissListener?.onEmojiPopupDismiss()
}
init {
verifyInstalled()
emojiView.setUp(
rootView = rootView,
onEmojiClickListener = onEmojiClickListener,
onEmojiBackspaceClickListener = onEmojiBackspaceClickListener,
editText = editText,
theming = theming,
recentEmoji = recentEmoji,
searchEmoji = searchEmoji,
variantEmoji = variantEmoji,
pageTransformer = pageTransformer,
)
popupWindow.contentView = emojiView
popupWindow.inputMethodMode = PopupWindow.INPUT_METHOD_NOT_NEEDED
popupWindow.setBackgroundDrawable(BitmapDrawable(context.resources, null as Bitmap?)) // To avoid borders and overdraw.
popupWindow.setOnDismissListener(onDismissListener)
if (keyboardAnimationStyle != 0) {
popupWindow.animationStyle = keyboardAnimationStyle
}
// Root view might already be laid out in which case we need to manually call start()
if (rootView.parent != null) {
start()
}
rootView.addOnAttachStateChangeListener(EmojiPopUpOnAttachStateChangeListener(this))
}
internal fun start() {
context.window.decorView.setOnApplyWindowInsetsListener(EmojiPopUpOnApplyWindowInsetsListener(this))
}
internal fun stop() {
dismiss()
context.window.decorView.setOnApplyWindowInsetsListener(null)
popupWindow.setOnDismissListener(null)
}
internal fun updateKeyboardStateOpened(keyboardHeight: Int) {
if (popupWindowHeight > 0 && popupWindow.height != popupWindowHeight) {
popupWindow.height = popupWindowHeight
} else if (popupWindowHeight == 0 && popupWindow.height != keyboardHeight) {
popupWindow.height = keyboardHeight
}
delay = if (globalKeyboardHeight != keyboardHeight) {
globalKeyboardHeight = keyboardHeight
APPLY_WINDOW_INSETS_DURATION
} else {
0
}
val properWidth = Utils.getProperWidth(context)
if (popupWindow.width != properWidth) {
popupWindow.width = properWidth
}
if (!isKeyboardOpen) {
isKeyboardOpen = true
onSoftKeyboardOpenListener?.onKeyboardOpen(keyboardHeight)
}
if (isPendingOpen) {
showAtBottom()
}
}
internal fun updateKeyboardStateClosed() {
isKeyboardOpen = false
onSoftKeyboardCloseListener?.onKeyboardClose()
if (isShowing) {
dismiss()
}
}
fun toggle() {
if (!popupWindow.isShowing) {
// this is needed because something might have cleared the insets listener
start()
ViewCompat.requestApplyInsets(context.window.decorView)
show()
} else {
dismiss()
}
}
fun show() {
if (Utils.shouldOverrideRegularCondition(context, editText) && originalImeOptions == -1) {
originalImeOptions = editText.imeOptions
}
editText.isFocusableInTouchMode = true
editText.requestFocus()
showAtBottomPending()
}
private fun showAtBottomPending() {
isPendingOpen = true
val inputMethodManager = context.inputMethodManager
if (Utils.shouldOverrideRegularCondition(context, editText)) {
editText.imeOptions = editText.imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI
inputMethodManager.restartInput(editText)
}
emojiResultReceiver.setReceiver { resultCode, _ ->
if (resultCode == 0 || resultCode == 1) {
showAtBottom()
}
}
inputMethodManager.showSoftInput(editText, InputMethodManager.RESULT_UNCHANGED_SHOWN, emojiResultReceiver)
}
val isShowing: Boolean
get() = popupWindow.isShowing
fun dismiss() {
popupWindow.dismiss()
emojiView.tearDown()
emojiResultReceiver.setReceiver(null)
if (originalImeOptions != -1) {
editText.imeOptions = originalImeOptions
val inputMethodManager = context.inputMethodManager
inputMethodManager.restartInput(editText)
if (VERSION.SDK_INT >= VERSION_CODES.O) {
val autofillManager = context.getSystemService(AutofillManager::class.java)
autofillManager?.cancel()
}
}
}
private fun showAtBottom() {
isPendingOpen = false
editText.postDelayed({
popupWindow.showAtLocation(
rootView, Gravity.NO_GRAVITY, 0,
Utils.getProperHeight(context) + popupWindowHeight,
)
}, delay.toLong(),)
onEmojiPopupShownListener?.onEmojiPopupShown()
}
internal class EmojiPopUpOnAttachStateChangeListener(emojiPopup: EmojiPopup) : View.OnAttachStateChangeListener {
private val emojiPopup: WeakReference<EmojiPopup> = WeakReference(emojiPopup)
override fun onViewAttachedToWindow(v: View) {
val popup = emojiPopup.get()
popup?.start()
}
override fun onViewDetachedFromWindow(v: View) {
val popup = emojiPopup.get()
popup?.stop()
emojiPopup.clear()
v.removeOnAttachStateChangeListener(this)
}
}
internal class EmojiPopUpOnApplyWindowInsetsListener(emojiPopup: EmojiPopup) : View.OnApplyWindowInsetsListener {
private val emojiPopup: WeakReference<EmojiPopup> = WeakReference(emojiPopup)
private var previousOffset = 0
override fun onApplyWindowInsets(v: View, insets: WindowInsets): WindowInsets {
val popup = emojiPopup.get()
if (popup != null) {
val systemWindowInsetBottom = if (VERSION.SDK_INT >= VERSION_CODES.R) {
insets.getInsets(WindowInsets.Type.ime()).bottom
} else {
@Suppress("DEPRECATION")
insets.systemWindowInsetBottom
}
val stableInsetBottom = if (VERSION.SDK_INT >= VERSION_CODES.R) {
insets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars()).bottom
} else {
@Suppress("DEPRECATION")
insets.stableInsetBottom
}
val offset = if (systemWindowInsetBottom < stableInsetBottom) {
systemWindowInsetBottom
} else {
systemWindowInsetBottom - stableInsetBottom
}
if (offset != previousOffset || offset == 0) {
previousOffset = offset
if (offset > Utils.dpToPx(popup.context, MIN_KEYBOARD_HEIGHT.toFloat())) {
popup.updateKeyboardStateOpened(offset)
} else {
popup.updateKeyboardStateClosed()
}
}
return popup.context.window.decorView.onApplyWindowInsets(insets)
}
return insets
}
}
private companion object {
private const val MIN_KEYBOARD_HEIGHT = 50
private const val APPLY_WINDOW_INSETS_DURATION = 250
}
}
| apache-2.0 | 1f05c54a7cf748b9cf703202edd87637 | 35.416667 | 135 | 0.739771 | 4.745873 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/types/commandline-argument.kt | 1 | 1437 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.types.Commandline.Argument
import org.apache.tools.ant.types.Path
import org.apache.tools.ant.types.Reference
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Argument._init(
value: String?,
line: String?,
path: String?,
pathref: String?,
file: String?,
prefix: String?,
suffix: String?)
{
if (value != null)
setValue(value)
if (line != null)
setLine(line)
if (path != null)
setPath(Path(project, path))
if (pathref != null)
setPathref(Reference(project, pathref))
if (file != null)
setFile(project.resolveFile(file))
if (prefix != null)
setPrefix(prefix)
if (suffix != null)
setSuffix(suffix)
}
| apache-2.0 | e6f8516c61d6b4e31326cf0afaa0ffe7 | 27.74 | 79 | 0.640919 | 3.832 | false | false | false | false |
wireapp/wire-android | app/src/test/kotlin/com/waz/zclient/core/extension/ByteArrayExtensionsTest.kt | 1 | 1347 | package com.waz.zclient.core.extension
import com.waz.zclient.UnitTest
import org.amshove.kluent.shouldContain
import org.amshove.kluent.shouldEqual
import org.junit.Test
class ByteArrayExtensionsTest : UnitTest() {
@Test
fun `given a byte array of size below 2x split size, when describe() is called, the result should be the same as in contentToString + the size`() {
val byteArray = byteArrayOf(10, 20, 30, 40, 50, 60, 70)
val res = byteArray.describe(splitAt = 4)
res shouldContain byteArray.contentToString()
res shouldContain "(${byteArray.size})"
}
@Test
fun `given an empty byte array, when describe() is called, the result should be the empty array + zero as the size`() {
val byteArray = byteArrayOf()
byteArray.describe() shouldEqual "[] (0)"
}
@Test
fun `given a byte array of size above 2x split size, when describe() is called, the result should show first and last bytes + the size`() {
val byteArray = byteArrayOf(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
val res = byteArray.describe(splitAt = 4)
res shouldContain byteArray.take(4).joinToString(", ")
res shouldContain "..."
res shouldContain byteArray.drop(byteArray.size - 4).joinToString(", ")
res shouldContain "(${byteArray.size})"
}
} | gpl-3.0 | 64ec66c6cbf3842119148eaee22ab14d | 39.848485 | 151 | 0.668894 | 4.262658 | false | true | false | false |
proxer/ProxerLibJava | library/src/test/kotlin/me/proxer/library/KotlinExtensionsKtTest.kt | 1 | 1941 | package me.proxer.library
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import org.amshove.kluent.AnyException
import org.amshove.kluent.coInvoking
import org.amshove.kluent.shouldBe
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldNotThrow
import org.amshove.kluent.shouldThrow
import org.amshove.kluent.with
import org.junit.jupiter.api.Test
class KotlinExtensionsKtTest : ProxerTest() {
@Test
fun testAwait(): Unit = runBlocking {
server.enqueue(MockResponse().setBody(fromResource("news.json")))
coInvoking { api.notifications.news().build().await() } shouldNotThrow AnyException
}
@Test
fun testNullableAwait(): Unit = runBlocking {
server.enqueue(MockResponse().setBody(fromResource("empty.json")))
coInvoking { api.messenger.sendMessage("123", "test").build().await() } shouldNotThrow AnyException
}
@Test
fun testUnitAwait(): Unit = runBlocking {
server.enqueue(MockResponse().setBody(fromResource("empty.json")))
coInvoking { api.messenger.report("123", "test").build().await() } shouldNotThrow AnyException
}
@Test
fun testAwaitWithError(): Unit = runBlocking {
server.enqueue(MockResponse().setBody(fromResource("news.json")).setResponseCode(404))
coInvoking { api.notifications.news().build().await() } shouldThrow ProxerException::class with
{ errorType shouldBe ProxerException.ErrorType.IO }
}
@Test
fun testCancel(): Unit = runBlocking {
server.enqueue(MockResponse().setBody(fromResource("news.json")))
with(async { api.notifications.news().build().await() }) {
cancel()
coInvoking { await() } shouldThrow CancellationException::class
}
server.requestCount shouldBeEqualTo 0
}
}
| mit | 0dd0e28913d502f097a24f3caf69907d | 31.898305 | 107 | 0.709943 | 4.722628 | false | true | false | false |
toastkidjp/Jitte | app/src/main/java/jp/toastkid/yobidashi/notification/morning/RemoteViewsFactory.kt | 1 | 3160 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.notification.morning
import android.app.PendingIntent
import android.content.Context
import android.net.Uri
import android.widget.RemoteViews
import androidx.annotation.LayoutRes
import androidx.core.net.toUri
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.main.launch.MainActivityIntentFactory
import jp.toastkid.yobidashi.wikipedia.random.RandomWikipedia
import jp.toastkid.yobidashi.wikipedia.today.DateArticleUrlFactory
import java.util.Calendar
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* @author toastkidjp
*/
class RemoteViewsFactory {
private val dateArticleUrlFactory = DateArticleUrlFactory()
private val mainActivityIntentFactory = MainActivityIntentFactory()
/**
* Make RemoteViews.
*
* @param context
* @return RemoteViews
*/
operator fun invoke(context: Context): RemoteViews {
val remoteViews = RemoteViews(context.packageName, APPWIDGET_LAYOUT_ID)
remoteViews.setOnClickPendingIntent(
R.id.what_happened,
makeWhatHappenedPendingIntent(context)
)
val countDownLatch = CountDownLatch(1)
RandomWikipedia().fetchWithAction { title, uri ->
remoteViews.setTextViewText(
R.id.today_wikipedia1,
"Today's Wikipedia article - '$title'"
)
remoteViews.setOnClickPendingIntent(
R.id.today_wikipedia1,
makeArticleLinkPendingIntent(context, uri)
)
countDownLatch.countDown()
}
countDownLatch.await(30, TimeUnit.SECONDS)
return remoteViews
}
private fun makeWhatHappenedPendingIntent(context: Context): PendingIntent =
PendingIntent.getActivity(
context,
0,
mainActivityIntentFactory.browser(context, makeArticleUri(context)),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
private fun makeArticleLinkPendingIntent(context: Context, uri: Uri): PendingIntent =
PendingIntent.getActivity(
context,
1,
mainActivityIntentFactory.browser(context, uri),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
private fun makeArticleUri(context: Context): Uri {
val calendar = Calendar.getInstance()
return dateArticleUrlFactory(
context,
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
).toUri()
}
companion object {
@LayoutRes
private const val APPWIDGET_LAYOUT_ID = R.layout.notification_morning
}
} | epl-1.0 | ee45eb26cfdbd1b5e63b4fe8265dc9d8 | 31.587629 | 89 | 0.661076 | 5.197368 | false | false | false | false |
7hens/KDroid | sample/src/main/java/cn/thens/kdroid/sample/test/TestChartActivity.kt | 1 | 5674 | package cn.thens.kdroid.sample.test
import android.content.Context
import android.graphics.*
import android.os.Bundle
import android.util.AttributeSet
import android.view.View
import cn.thens.kdroid.sample.common.app.BaseActivity
import cn.thens.kdroid.sample.common.view.color
import cn.thens.kdroid.sample.R
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_chart_main.*
class BirdMainActivity : BaseActivity() {
private var showsAll = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chart_main)
}
override fun onResume() {
super.onResume()
vBird.post {
refreshChart()
}
vToggle.setOnClickListener {
showsAll = showsAll.not()
vToggle.text = if (showsAll) "RGB" else "ALL"
refreshChart()
}
vUp.setOnClickListener {
vBird.moveLineHeight(-7)
refreshChart()
}
vDown.setOnClickListener {
vBird.moveLineHeight(8)
refreshChart()
}
}
private fun refreshChart() {
vBird.pixel()
.observeOn(Schedulers.io())
.toList()
.map {
val allEntryList = ArrayList<Entry>()
val redEntryList = ArrayList<Entry>()
val greenEntryList = ArrayList<Entry>()
val blueEntryList = ArrayList<Entry>()
it.forEach {
val x = it.first.toFloat()
val color = it.second
val all = (Int.MAX_VALUE.toLong() and color.toLong()).toFloat()
val red = Color.red(color).toFloat()
val green = Color.green(color).toFloat()
val blue = Color.blue(color).toFloat()
allEntryList.add(Entry(x, all))
redEntryList.add(Entry(x, red))
greenEntryList.add(Entry(x, green))
blueEntryList.add(Entry(x, blue))
}
val dataSet = { list: ArrayList<Entry>, label: String, color: Int ->
val dataSet = LineDataSet(list, label)
dataSet.color = color
dataSet.setDrawCircles(false)
dataSet
}
if (showsAll) {
listOf(dataSet(allEntryList, "ALL", Color.BLACK))
} else {
listOf(
// dataSet(allEntryList, "ALL", Color.BLACK),
dataSet(redEntryList, "RED", Color.RED),
dataSet(greenEntryList, "GREEN", Color.GREEN),
dataSet(blueEntryList, "BLUE", Color.BLUE)
)
}
}
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess {
if (it.isNotEmpty()) {
vLineChart.data = LineData(it)
vLineChart.invalidate()
}
}
.subscribe()
}
}
class BirdView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
private val paint = Paint()
private val bitmap: Bitmap by lazy { BitmapFactory.decodeResource(context.resources, R.drawable.ic_bird) }
private var lineHeight = 0
private val rect = Rect()
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawBitmap(bitmap, null, rect.reset(0, 0, canvas.width, canvas.height), paint)
paint.color = color(R.color.colorAccent)
canvas.drawLine(0F, lineHeight.toFloat(), width.toFloat(), lineHeight.toFloat(), paint)
}
private fun Rect.reset(left: Int, top: Int, right: Int, bottom: Int): Rect {
this.left = left
this.right = right
this.top = top
this.bottom = bottom
return this
}
fun pixel(): Observable<Pair<Int, Int>> {
return Observable.create {
val bitmap = getBitmapFromView(this)
for (i in 0 until width step 5) {
val pixel = bitmap.getPixel(i, lineHeight - 1)
it.onNext(i to pixel)
}
bitmap.recycle()
it.onComplete()
}
}
private fun getBitmapFromView(v: View): Bitmap {
val b = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.RGB_565)
val c = Canvas(b)
v.layout(v.left, v.top, v.right, v.bottom)
// Draw background
val bgDrawable = v.background
if (bgDrawable != null)
bgDrawable.draw(c)
else
c.drawColor(Color.WHITE)
// Draw view to canvas
v.draw(c)
return b
}
fun moveLineHeight(delta: Int) {
lineHeight += delta
invalidate()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
lineHeight = height / 2
}
} | apache-2.0 | 1d776f7fbfb5d799668785cadc534738 | 33.924051 | 110 | 0.525731 | 4.708714 | false | false | false | false |
CarrotCodes/Warren | src/main/kotlin/chat/willow/warren/event/WarrenEvents.kt | 1 | 1660 | package chat.willow.warren.event
import chat.willow.kale.irc.message.rfc1459.ModeMessage
import chat.willow.kale.irc.prefix.Prefix
import chat.willow.kale.irc.tag.ITagStore
import chat.willow.kale.irc.tag.TagStore
import chat.willow.warren.WarrenChannel
import chat.willow.warren.WarrenChannelUser
import chat.willow.warren.state.LifecycleState
interface IWarrenEvent
typealias IMetadataStore = ITagStore
typealias MetadataStore = TagStore
data class ChannelMessageEvent(val user: WarrenChannelUser, val channel: WarrenChannel, val message: String, val metadata: IMetadataStore = MetadataStore()) : IWarrenEvent
data class ChannelActionEvent(val user: WarrenChannelUser, val channel: WarrenChannel, val message: String, val metadata: IMetadataStore = MetadataStore()) : IWarrenEvent
data class ChannelModeEvent(val user: Prefix?, val channel: WarrenChannel, val modifier: ModeMessage.ModeModifier, val metadata: IMetadataStore = MetadataStore()) : IWarrenEvent
data class UserModeEvent(val user: String, val modifier: ModeMessage.ModeModifier, val metadata: IMetadataStore = MetadataStore()) : IWarrenEvent
data class PrivateMessageEvent(val user: Prefix, val message: String, val metadata: IMetadataStore = MetadataStore()) : IWarrenEvent
data class PrivateActionEvent(val user: Prefix, val message: String, val metadata: IMetadataStore = MetadataStore()) : IWarrenEvent
data class InvitedToChannelEvent(val source: Prefix, val channel: String, val metadata: IMetadataStore = MetadataStore()) : IWarrenEvent
data class RawIncomingLineEvent(val line: String) : IWarrenEvent
data class ConnectionLifecycleEvent(val lifecycle: LifecycleState) : IWarrenEvent | isc | c05117cb38e929349bed76ec8237d2dc | 65.44 | 177 | 0.826506 | 4.450402 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsModDeclItem.kt | 1 | 2141 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsBlock
import org.rust.lang.core.psi.RsModDeclItem
import org.rust.lang.core.psi.RsPsiImplUtil
import org.rust.lang.core.resolve.ref.RsModReferenceImpl
import org.rust.lang.core.resolve.ref.RsReference
import org.rust.lang.core.stubs.RsModDeclItemStub
import javax.swing.Icon
fun RsModDeclItem.getOrCreateModuleFile(): PsiFile? {
val existing = reference.resolve()?.containingFile
if (existing != null) return existing
return suggestChildFileName?.let { containingMod.ownedDirectory?.createFile(it) }
}
val RsModDeclItem.isLocal: Boolean
get() = stub?.isLocal ?: (parentOfType<RsBlock>() != null)
//TODO: use explicit path if present.
private val RsModDeclItem.suggestChildFileName: String?
get() = implicitPaths.firstOrNull()
private val RsModDeclItem.implicitPaths: List<String> get() {
val name = name ?: return emptyList()
return if (isLocal) emptyList() else listOf("$name.rs", "$name/mod.rs")
}
val RsModDeclItem.pathAttribute: String? get() = queryAttributes.lookupStringValueForKey("path")
abstract class RsModDeclItemImplMixin : RsStubbedNamedElementImpl<RsModDeclItemStub>,
RsModDeclItem {
constructor(node: ASTNode) : super(node)
constructor(stub: RsModDeclItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getReference(): RsReference = RsModReferenceImpl(this)
override val referenceNameElement: PsiElement get() = identifier
override val referenceName: String get() = name!!
override fun getIcon(flags: Int): Icon? = iconWithVisibility(flags, RsIcons.MODULE)
override val isPublic: Boolean get() = RsPsiImplUtil.isPublic(this, stub)
}
val RsModDeclItem.hasMacroUse: Boolean get() =
queryAttributes.hasAttribute("macro_use")
| mit | e3bd1b579844119481bc9d3a3538742c | 32.984127 | 98 | 0.751051 | 4.214567 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/fixes/RemoveTypeParameter.kt | 2 | 1070 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.fixes
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsCompositeElement
class RemoveTypeParameter(val element: RsCompositeElement) : LocalQuickFix {
override fun getName() = "Remove all type parameters"
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val typeArgumentList = when (element) {
is RsMethodCall -> element.typeArgumentList
is RsCallExpr -> (element.expr as RsPathExpr?)?.path?.typeArgumentList
is RsBaseType -> element.path?.typeArgumentList
else -> null
} ?: return
val lifetime = typeArgumentList.lifetimeList.size
if (lifetime == 0) {
typeArgumentList.delete()
}
}
}
| mit | 6393bcd4a2c5873cb878da6a1f94400a | 32.4375 | 82 | 0.701869 | 4.81982 | false | false | false | false |
alex-tavella/MooV | feature/bookmark-movie/impl/src/test/java/br/com/bookmark/movie/data/DefaultBookmarkRepositoryTest.kt | 1 | 1932 | /*
* Copyright 2021 Alex Almeida Tavella
*
* 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 br.com.bookmark.movie.data
import br.com.bookmark.movie.testdoubles.TestBookmarkDataSource
import br.com.moov.bookmark.movie.BookmarkError
import br.com.moov.bookmark.movie.UnbookmarkError
import br.com.moov.core.result.Result
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
class DefaultBookmarkRepositoryTest {
private val bookmarkDataSource = TestBookmarkDataSource(listOf(123, 789))
private val bookmarkRepository = DefaultBookmarkRepository(bookmarkDataSource)
@Test
fun bookmarkMovie_insertsOnDataSource() = runBlocking {
bookmarkRepository.bookmarkMovie(456)
assertEquals(listOf(123, 789, 456), bookmarkDataSource.getBookmarks())
}
@Test
fun bookmarkMovie_fails_returnsError() = runBlocking {
val actual = bookmarkRepository.bookmarkMovie(123)
assertEquals(Result.Err(BookmarkError), actual)
}
@Test
fun unBookmarkMovie_removesFromDataSource() = runBlocking {
bookmarkRepository.unBookmarkMovie(123)
assertEquals(listOf(789), bookmarkDataSource.getBookmarks())
}
@Test
fun unBookmarkMovie_fails_returnsError() = runBlocking {
val actual = bookmarkRepository.unBookmarkMovie(456)
assertEquals(Result.Err(UnbookmarkError), actual)
}
}
| apache-2.0 | a1b8abc363ef6870398fd030b016f79a | 32.310345 | 82 | 0.75 | 4.441379 | false | true | false | false |
tschuchortdev/kotlin-compile-testing | core/src/test/kotlin/com/tschuchort/compiletesting/KotlinTestProcessor.kt | 1 | 3400 | package com.tschuchort.compiletesting
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.TypeSpec as JavaTypeSpec
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.TypeSpec
import java.io.File
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement
import javax.tools.Diagnostic
annotation class ProcessElem
data class ProcessedElemMessage(val elementSimpleName: String) {
fun print() = MSG_PREFIX + elementSimpleName + MSG_SUFFIX
init {
require(elementSimpleName.isNotEmpty())
}
companion object {
private const val MSG_PREFIX = "processed element{"
private const val MSG_SUFFIX = "}"
fun parseAllIn(s: String): List<ProcessedElemMessage> {
val pattern = Regex(Regex.escape(MSG_PREFIX) + "(.+)?" + Regex.escape(MSG_SUFFIX))
return pattern.findAll(s)
.map { match ->
ProcessedElemMessage(match.destructured.component1())
}.toList()
}
}
}
class KotlinTestProcessor : AbstractProcessor() {
companion object {
private const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated"
private const val GENERATE_KOTLIN_CODE_OPTION = "generate.kotlin.value"
private const val GENERATE_ERRORS_OPTION = "generate.error"
private const val FILE_SUFFIX_OPTION = "suffix"
const val ON_INIT_MSG = "kotlin processor init"
const val GENERATED_PACKAGE = "com.tschuchort.compiletesting"
const val GENERATED_JAVA_CLASS_NAME = "KotlinGeneratedJavaClass"
const val GENERATED_KOTLIN_CLASS_NAME = "KotlinGeneratedKotlinClass"
}
private val kaptKotlinGeneratedDir by lazy { processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME] }
override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latest()
override fun getSupportedOptions() = setOf(
KAPT_KOTLIN_GENERATED_OPTION_NAME,
GENERATE_KOTLIN_CODE_OPTION,
GENERATE_ERRORS_OPTION
)
override fun getSupportedAnnotationTypes(): Set<String> = setOf(ProcessElem::class.java.canonicalName)
override fun init(processingEnv: ProcessingEnvironment) {
processingEnv.messager.printMessage(Diagnostic.Kind.WARNING, ON_INIT_MSG)
super.init(processingEnv)
}
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
processingEnv.messager.printMessage(Diagnostic.Kind.WARNING, "kotlin processor was called")
for (annotatedElem in roundEnv.getElementsAnnotatedWith(ProcessElem::class.java)) {
processingEnv.messager.printMessage(Diagnostic.Kind.WARNING,
ProcessedElemMessage(annotatedElem.simpleName.toString()).print())
}
if(annotations.isEmpty()) {
FileSpec.builder(GENERATED_PACKAGE, GENERATED_KOTLIN_CLASS_NAME + ".kt")
.addType(
TypeSpec.classBuilder(GENERATED_KOTLIN_CLASS_NAME).build()
).build()
.let { writeKotlinFile(it) }
JavaFile.builder(GENERATED_PACKAGE, JavaTypeSpec.classBuilder(GENERATED_JAVA_CLASS_NAME).build())
.build().writeTo(processingEnv.filer)
}
return false
}
private fun writeKotlinFile(fileSpec: FileSpec, fileName: String = fileSpec.name, packageName: String = fileSpec.packageName) {
val relativePath = packageName.replace('.', File.separatorChar)
val outputFolder = File(kaptKotlinGeneratedDir!!, relativePath)
outputFolder.mkdirs()
// finally write to output file
File(outputFolder, fileName).writeText(fileSpec.toString())
}
} | mpl-2.0 | bdf50209f094c735b58a4cb70c45d5aa | 35.180851 | 128 | 0.765588 | 4.062127 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/entity/player/PlayerBossBarManager.kt | 1 | 3247 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.entity.player
import org.lanternpowered.api.boss.BossBar
import org.lanternpowered.api.boss.BossBarColor
import org.lanternpowered.api.boss.BossBarFlag
import org.lanternpowered.api.boss.BossBarOverlay
import org.lanternpowered.api.text.Text
import org.lanternpowered.api.util.collections.concurrentHashMapOf
import org.lanternpowered.api.util.collections.toImmutableMap
import org.lanternpowered.server.network.vanilla.packet.type.play.BossBarPacket
import java.util.UUID
/**
* The boss bar manager of a specific player.
*/
class PlayerBossBarManager(
private val player: LanternPlayer
) : net.kyori.adventure.bossbar.BossBar.Listener {
private val bossBars = concurrentHashMapOf<BossBar, UUID>()
override fun bossBarColorChanged(bar: BossBar, oldColor: BossBarColor, newColor: BossBarColor) {
val uniqueId = this.bossBars[bar] ?: return
this.player.connection.send(BossBarPacket.UpdateStyle(uniqueId, newColor, bar.overlay()))
}
override fun bossBarFlagsChanged(bar: BossBar, oldFlags: Set<BossBarFlag>, newFlags: Set<BossBarFlag>) {
val uniqueId = this.bossBars[bar] ?: return
this.player.connection.send(BossBarPacket.UpdateFlags(uniqueId, newFlags))
}
override fun bossBarNameChanged(bar: BossBar, oldName: Text, newName: Text) {
val uniqueId = this.bossBars[bar] ?: return
this.player.connection.send(BossBarPacket.UpdateName(uniqueId, newName))
}
override fun bossBarOverlayChanged(bar: BossBar, oldOverlay: BossBarOverlay, newOverlay: BossBarOverlay) {
val uniqueId = this.bossBars[bar] ?: return
this.player.connection.send(BossBarPacket.UpdateStyle(uniqueId, bar.color(), newOverlay))
}
override fun bossBarPercentChanged(bar: BossBar, oldPercent: Float, newPercent: Float) {
val uniqueId = this.bossBars[bar] ?: return
this.player.connection.send(BossBarPacket.UpdatePercent(uniqueId, newPercent))
}
fun show(bossBar: BossBar) {
if (this.bossBars.containsKey(bossBar))
return
val uniqueId = UUID.randomUUID()
if (this.bossBars.put(bossBar, uniqueId) != null)
return
val packet = BossBarPacket.Add(uniqueId, bossBar.name(), bossBar.color(),
bossBar.overlay(), bossBar.percent(), bossBar.flags())
this.player.connection.send(packet)
bossBar.addListener(this)
}
fun hide(bossBar: BossBar) {
val uniqueId = this.bossBars.remove(bossBar) ?: return
bossBar.removeListener(this)
this.player.connection.send(BossBarPacket.Remove(uniqueId))
}
fun clear() {
val all = this.bossBars.toImmutableMap()
this.bossBars.clear()
for ((bossBar, uniqueId) in all) {
bossBar.removeListener(this)
this.player.connection.send(BossBarPacket.Remove(uniqueId))
}
}
}
| mit | e40d5fdb3642f4fc41ec7dec53b2f60d | 38.120482 | 110 | 0.708962 | 3.935758 | false | false | false | false |
jonninja/node.kt | src/main/kotlin/node/express/servers/ExpressNetty.kt | 1 | 3622 | package node.express.servers
import node.express.Express
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.http.HttpRequestDecoder
import io.netty.handler.codec.http.HttpObjectAggregator
import io.netty.handler.codec.http.HttpResponseEncoder
import io.netty.handler.stream.ChunkedWriteHandler
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.channel.ChannelHandlerContext
import node.express.Response
import node.express.Request
import java.net.InetSocketAddress
import node.util.log
import io.netty.channel.socket.SocketChannel
import io.netty.channel.ChannelInitializer
import io.netty.handler.codec.http.HttpServerCodec
import io.netty.handler.codec.http.DefaultFullHttpResponse
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelFutureListener
import io.netty.handler.codec.http.HttpVersion
import io.netty.handler.codec.http.HttpResponseStatus
import io.netty.util.CharsetUtil
import io.netty.handler.codec.http.HttpHeaders
import io.netty.channel.ChannelInboundHandlerAdapter
/**
* Implementation of the express API using the Netty server engine
*/
public class ExpressNetty(): Express() {
private val bootstrap: ServerBootstrap
init {
val bossGroup = NioEventLoopGroup()
val workerGroup = NioEventLoopGroup()
bootstrap = ServerBootstrap()
bootstrap.group(bossGroup, workerGroup).
channel(javaClass<NioServerSocketChannel>()).
childHandler(ServerInitializer())
}
/**
* Initializes the request pipeline
*/
private inner class ServerInitializer: ChannelInitializer<SocketChannel>() {
override fun initChannel(ch: SocketChannel?) {
val p = ch!!.pipeline()
p.addLast("httpDecoder", HttpRequestDecoder());
p.addLast("httpAggregator", HttpObjectAggregator(1048576))
p.addLast("httpEncoder", HttpResponseEncoder())
p.addLast("handler", RequestHandler())
p.addLast("exception", ExceptionHandler())
}
}
/**
* Our main Netty callback
*/
private inner class RequestHandler(): SimpleChannelInboundHandler<FullHttpRequest>() {
override fun channelRead0(ctx: ChannelHandlerContext?, msg: FullHttpRequest?) {
val req = Request(this@ExpressNetty, msg!!, ctx!!.channel()!!)
val res = Response(req, msg, ctx)
try {
handleRequest(req, res, 0)
} catch (t: Throwable) {
errorHandler(t, req, res)
}
}
}
/**
* A handler at the end of the chain that handles any exceptions that occurred
* during processing.
*/
private inner class ExceptionHandler(): ChannelInboundHandlerAdapter() {
override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {
val response = DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.INTERNAL_SERVER_ERROR);
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);
ctx!!.writeAndFlush(response);
ctx.close();
}
}
/**
* Start the server listening on the given port
*/
fun listen(port: Int? = null) {
var aPort = port;
if (aPort == null) {
aPort = get("port") as Int
}
bootstrap.bind(InetSocketAddress(aPort))
this.log("Express listening on port " + port)
}
} | mit | cffeb6c0645c4b85844767d772e65ca6 | 34.871287 | 90 | 0.688018 | 4.734641 | false | false | false | false |
crunchersaspire/worshipsongs-android | app/src/main/java/org/worshipsongs/fragment/ServiceSongsFragment.kt | 3 | 11571 | package org.worshipsongs.fragment
import android.app.Activity
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.activity.SongContentViewActivity
import org.worshipsongs.adapter.TitleAdapter
import org.worshipsongs.domain.ServiceSong
import org.worshipsongs.domain.Setting
import org.worshipsongs.domain.Song
import org.worshipsongs.listener.SongContentViewListener
import org.worshipsongs.service.PopupMenuService
import org.worshipsongs.service.SongService
import org.worshipsongs.service.UserPreferenceSettingService
import org.worshipsongs.utils.CommonUtils
import org.worshipsongs.utils.PropertyUtils
import java.io.File
import java.util.ArrayList
/**
* @author : Madasamy
* @since : 3.x
*/
class ServiceSongsFragment : Fragment(), TitleAdapter.TitleAdapterListener<ServiceSong>, AlertDialogFragment.DialogListener
{
private var songListView: ListView? = null
private var titleAdapter: TitleAdapter<ServiceSong>? = null
private var serviceName: String? = null
private var songService: SongService? = null
private var serviceSongs: ArrayList<ServiceSong>? = null
private val titles = ArrayList<String>()
private val preferenceSettingService = UserPreferenceSettingService()
private var songContentViewListener: SongContentViewListener? = null
private val popupMenuService = PopupMenuService()
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
serviceName = arguments!!.getString(CommonConstants.SERVICE_NAME_KEY)
songService = SongService(activity!!.applicationContext)
setHasOptionsMenu(true)
loadSongs()
}
private fun loadSongs()
{
Log.i(CLASS_NAME, "Preparing to find songs")
val serviceFile = PropertyUtils.getPropertyFile(activity as Activity, CommonConstants.SERVICE_PROPERTY_TEMP_FILENAME)
val property = PropertyUtils.getProperty(serviceName!!, serviceFile!!)
val propertyValues = property.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
songService = SongService(activity!!.applicationContext)
serviceSongs = ArrayList()
for (title in propertyValues)
{
val song = songService!!.findContentsByTitle(title)
serviceSongs!!.add(ServiceSong(title, song))
titles.add(title)
}
Log.i(CLASS_NAME, "No of songs " + serviceSongs!!)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
val view = inflater.inflate(R.layout.songs_layout, container, false)
setListView(view)
return view
}
private fun setListView(view: View)
{
songListView = view.findViewById<View>(R.id.song_list_view) as ListView
titleAdapter = TitleAdapter((activity as AppCompatActivity?)!!, R.layout.songs_layout)
titleAdapter!!.setTitleAdapterListener(this)
titleAdapter!!.addObjects(serviceSongs!!)
songListView!!.adapter = titleAdapter
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater)
{
inflater.inflate(R.menu.action_bar_menu, menu)
val searchManager = activity!!.getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView = menu!!.findItem(R.id.menu_search).actionView as SearchView
searchView.setSearchableInfo(searchManager.getSearchableInfo(activity!!.componentName))
searchView.setIconifiedByDefault(true)
searchView.maxWidth = Integer.MAX_VALUE
searchView.queryHint = getString(R.string.action_search)
val image = searchView.findViewById<View>(R.id.search_close_btn) as ImageView
val drawable = image.drawable
drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
val textChangeListener = object : SearchView.OnQueryTextListener
{
override fun onQueryTextChange(newText: String): Boolean
{
titleAdapter!!.addObjects(songService!!.filteredServiceSongs(newText, serviceSongs))
return true
}
override fun onQueryTextSubmit(query: String): Boolean
{
titleAdapter!!.addObjects(songService!!.filteredServiceSongs(query, serviceSongs))
return true
}
}
searchView.setOnQueryTextListener(textChangeListener)
menu.getItem(0).isVisible = false
}
//Adapter listener methods
override fun setViews(objects: Map<String, Any>, serviceSong: ServiceSong?)
{
val titleTextView = objects[CommonConstants.TITLE_KEY] as TextView?
titleTextView!!.text = songService!!.getTitle(preferenceSettingService.isTamil, serviceSong!!)
titleTextView.setOnClickListener(SongOnClickListener(serviceSong!!))
titleTextView.setOnLongClickListener(SongOnLongClickListener(serviceSong))
val playImageView = objects[CommonConstants.PLAY_IMAGE_KEy] as ImageView?
playImageView!!.visibility = if (isShowPlayIcon(serviceSong.song!!)) View.VISIBLE else View.GONE
playImageView.setOnClickListener(imageOnClickListener(serviceSong.song, serviceSong.title!!))
val optionsImageView = objects[CommonConstants.OPTIONS_IMAGE_KEY] as ImageView?
optionsImageView!!.visibility = View.VISIBLE
optionsImageView.setOnClickListener(imageOnClickListener(serviceSong.song, serviceSong.title!!))
}
internal fun isShowPlayIcon(song: Song): Boolean
{
try
{
val urlKey = song.urlKey
return urlKey != null && urlKey.length > 0 && preferenceSettingService.isPlayVideo
} catch (e: Exception)
{
return false
}
}
private fun imageOnClickListener(song: Song?, title: String): View.OnClickListener
{
return View.OnClickListener { view ->
if (song != null)
{
popupMenuService.showPopupmenu(activity as AppCompatActivity, view, song.title!!, true)
} else
{
val bundle = Bundle()
bundle.putString(CommonConstants.TITLE_KEY, getString(R.string.warning))
bundle.putString(CommonConstants.MESSAGE_KEY, getString(R.string.message_song_not_available, "\"" + title + "\""))
val alertDialogFragment = AlertDialogFragment.newInstance(bundle)
alertDialogFragment.setVisibleNegativeButton(false)
alertDialogFragment.show(activity!!.supportFragmentManager, "WarningDialogFragment")
}
}
}
//Dialog listener methods
override fun onClickPositiveButton(bundle: Bundle?, tag: String?)
{
if ("DeleteDialogFragment".equals(tag!!, ignoreCase = true))
{
removeSong(bundle!!.getString(CommonConstants.NAME_KEY))
}
}
private fun removeSong(serviceSong: String?)
{
try
{
val serviceFile = PropertyUtils.getPropertyFile(activity!!, CommonConstants.SERVICE_PROPERTY_TEMP_FILENAME)
PropertyUtils.removeSong(serviceFile!!, serviceName!!, serviceSong!!)
serviceSongs!!.remove(getSongToBeRemoved(serviceSong, serviceSongs!!))
titleAdapter!!.addObjects(serviceSongs!!)
} catch (e: Exception)
{
Log.e(this.javaClass.name, "Error occurred while removing song", e)
}
}
internal fun getSongToBeRemoved(title: String?, serviceSongs: List<ServiceSong>): ServiceSong?
{
for (serviceSong in serviceSongs)
{
if (serviceSong.title.equals(title!!, ignoreCase = true))
{
return serviceSong
}
}
return null
}
override fun onClickNegativeButton()
{
//Do nothing
}
private inner class SongOnClickListener internal constructor(private val serviceSong: ServiceSong) : View.OnClickListener
{
override fun onClick(view: View)
{
if (serviceSong.song != null)
{
if (CommonUtils.isPhone(context!!))
{
val intent = Intent(activity, SongContentViewActivity::class.java)
val bundle = Bundle()
val titles = ArrayList<String>()
titles.add(serviceSong.title!!)
bundle.putStringArrayList(CommonConstants.TITLE_LIST_KEY, titles)
bundle.putInt(CommonConstants.POSITION_KEY, 0)
Setting.instance.position = 0
intent.putExtras(bundle)
activity!!.startActivity(intent)
} else
{
Setting.instance.position = titleAdapter!!.getPosition(serviceSong)
songContentViewListener!!.displayContent(serviceSong.title!!, titles, titleAdapter!!.getPosition(serviceSong))
}
} else
{
val bundle = Bundle()
bundle.putString(CommonConstants.TITLE_KEY, getString(R.string.warning))
bundle.putString(CommonConstants.MESSAGE_KEY, getString(R.string.message_song_not_available, "\"" + serviceSong.title + "\""))
val alertDialogFragment = AlertDialogFragment.newInstance(bundle)
alertDialogFragment.setVisibleNegativeButton(false)
alertDialogFragment.show(activity!!.supportFragmentManager, "WarningDialogFragment")
}
}
}
private inner class SongOnLongClickListener internal constructor(private val serviceSong: ServiceSong) : View.OnLongClickListener
{
override fun onLongClick(view: View): Boolean
{
val bundle = Bundle()
bundle.putString(CommonConstants.TITLE_KEY, getString(R.string.remove_favourite_song_title))
bundle.putString(CommonConstants.MESSAGE_KEY, getString(R.string.remove_favourite_song_message))
bundle.putString(CommonConstants.NAME_KEY, serviceSong.title)
val deleteAlertDialogFragment = AlertDialogFragment.newInstance(bundle)
deleteAlertDialogFragment.setDialogListener(this@ServiceSongsFragment)
deleteAlertDialogFragment.show(activity!!.supportFragmentManager, "DeleteDialogFragment")
return true
}
}
fun setSongContentViewListener(songContentViewListener: SongContentViewListener)
{
this.songContentViewListener = songContentViewListener
}
companion object
{
private val CLASS_NAME = ServiceSongsFragment::class.java.simpleName
fun newInstance(bundle: Bundle): ServiceSongsFragment
{
val serviceSongsFragment = ServiceSongsFragment()
serviceSongsFragment.arguments = bundle
return serviceSongsFragment
}
}
}
| gpl-3.0 | 268bba4361570abc2bb67f82b53c3e79 | 38.9 | 142 | 0.678334 | 5.186463 | false | false | false | false |
KasparPeterson/Globalwave | app/src/main/java/com/kasparpeterson/globalwave/spotify/search/SpotifySearchManager.kt | 1 | 2312 | package com.kasparpeterson.globalwave.spotify.search
import android.util.Log
import com.google.gson.Gson
import com.kasparpeterson.globalwave.language.LanguageProcessor
import com.kasparpeterson.globalwave.language.ProcessorResult
import com.kasparpeterson.globalwave.spotify.search.model.Item
import com.kasparpeterson.globalwave.spotify.search.model.SearchResult
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import rx.Observable
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
/**
* Created by kaspar on 24/02/2017.
*/
class SpotifySearchManager {
private val TAG = SpotifySearchManager::class.java.simpleName
private val BASE_URL = "https://api.spotify.com/v1/"
private val service: SpotifyService
init {
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build()
service = retrofit.create(SpotifyService::class.java)
}
fun search(processorResult: ProcessorResult): Observable<SearchResult> {
Log.d(TAG, "search, processorResult: " + processorResult)
return service.search(processorResult.name, ProcessorResult.SearchType.ARTIST.type)
}
fun getBestMatch(processorResult: ProcessorResult): Observable<Item> {
return Observable.just(processorResult)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.flatMap { processorResult -> search(processorResult) }
.map { searchResult -> getBestMatch(searchResult) }
}
private fun getBestMatch(result: SearchResult): Item? {
var mostPopularInt = 0
var mostPopularItem: Item? = null
if (result.artists != null && result.artists!!.items != null) {
for (item in result.artists!!.items!!) {
if (item.popularity != null && item.popularity!! > mostPopularInt) {
mostPopularInt = item.popularity!!
mostPopularItem = item
}
}
}
return mostPopularItem
}
} | mit | 81a2c58dcb78980bbf73ef36c53f3768 | 34.045455 | 91 | 0.682093 | 4.578218 | false | false | false | false |
Mauin/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/CodeSmell.kt | 1 | 1570 | package io.gitlab.arturbosch.detekt.api
/**
* A code smell is a finding, implementing its behaviour. Use this class to store
* rule violations.
*
* @author Artur Bosch
*/
open class CodeSmell(final override val issue: Issue,
override val entity: Entity,
override val message: String,
override val metrics: List<Metric> = listOf(),
override val references: List<Entity> = listOf()) : Finding {
override val id: String = issue.id
override fun compact() = "$id - ${entity.compact()}"
override fun compactWithSignature() = compact() + " - Signature=" + entity.signature
override fun toString(): String {
return "CodeSmell(issue=$issue, " +
"entity=$entity, " +
"message=$message, " +
"metrics=$metrics, " +
"references=$references, " +
"id='$id')"
}
override fun messageOrDescription() = when {
message.isEmpty() -> issue.description
else -> message
}
}
/**
* Represents a code smell for which a specific metric can be determined which is responsible
* for the existence of this rule violation.
*/
open class ThresholdedCodeSmell(
issue: Issue,
entity: Entity,
val metric: Metric,
message: String,
references: List<Entity> = emptyList()) : CodeSmell(
issue, entity, message, metrics = listOf(metric), references = references) {
val value: Int
get() = metric.value
val threshold: Int
get() = metric.threshold
override fun compact() = "$id - $metric - ${entity.compact()}"
override fun messageOrDescription() = when {
message.isEmpty() -> issue.description
else -> message
}
}
| apache-2.0 | 7a7da5100f94397204e4a0e3741cfcd0 | 26.068966 | 93 | 0.677707 | 3.747017 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/view/activity/TodoDetailsActivity.kt | 1 | 7809 | package za.org.grassroot2.view.activity
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.Menu
import android.view.View
import android.widget.EditText
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_todo_details.*
import timber.log.Timber
import za.org.grassroot2.R
import za.org.grassroot2.dagger.activity.ActivityComponent
import za.org.grassroot2.model.task.Todo
import za.org.grassroot2.presenter.activity.TodoDetailsPresenter
import za.org.grassroot2.util.DateFormatter
import za.org.grassroot2.view.adapter.PostAdapter
import za.org.grassroot2.view.dialog.OptionPickDialog
import javax.inject.Inject
class TodoDetailsActivity : GrassrootActivity(), TodoDetailsPresenter.TodoDetailsView {
private var todoUid: String? = null
@Inject lateinit var presenter: TodoDetailsPresenter
@Inject lateinit var rxPermissions: RxPermissions
@Inject lateinit var postAdapter: PostAdapter
override val layoutResourceId: Int
get(): Int = R.layout.activity_todo_details
override fun onInject(component: ActivityComponent) = component.inject(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val triggeredByNotification = intent.getBooleanExtra(TRIGGERED_BY_NOTIFICATION, false)
todoUid = intent.getStringExtra(EXTRA_TODO_UID)
Timber.d("In TodoDetailsActivity, extracted this uid from HomeFrag: %s", todoUid)
initView()
presenter.attach(this)
presenter.init(todoUid!!, triggeredByNotification)
todoStatusText.setOnClickListener {
val attendenceDialog = OptionPickDialog.attendenceChoiceDialog()
disposables.add(attendenceDialog.clickAction().subscribe( { clickId ->
attendenceDialog.dismiss()
when (clickId) {
// Do some stuff
R.id.optionA -> presenter.respondToTodo(todoUid!!, Todo.TODO_YES)
R.id.optionB -> presenter.respondToTodo(todoUid!!, Todo.TODO_NO)
}
}, {t -> t.printStackTrace() }))
attendenceDialog.show(supportFragmentManager, "")
}
// todofab.setOnClickListener { CreateActionActivity.start(activity, todoUid) }
writePostButton.setOnClickListener { writePost() }
posts.adapter = postAdapter
// todo: get this adapter committed again
// todo_results.adapter = resultsAdapter
// todo_results.layoutManager = LinearLayoutManager(this)
// posts.layoutManager = LinearLayoutManager(this)
}
private fun writePost() {
CreatePostActivity.start(this, presenter.todo.uid, presenter.todo.parentUid)
}
override fun onResume() {
super.onResume()
Timber.d("inside activity, telling presenter to load data");
presenter.loadData()
}
override fun onDestroy() {
super.onDestroy()
presenter.detach()
}
private fun initView() {
initToolbar()
}
private fun initToolbar() {
setSupportActionBar(todo_toolbar)
todo_toolbar.title = ""
todo_toolbar.setNavigationIcon(R.drawable.ic_arrow_left_white_24dp)
todo_toolbar.setNavigationOnClickListener { v -> finish() }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_group_details, menu)
return super.onCreateOptionsMenu(menu)
}
override fun render(todo: Todo) {
todoTitle.text = todo.name
// Timber.d("The contents of todo are: %s", todo.toString())
// Timber.d("The contents of todo.toString() are: %s", todo.toString())
if (todo.todoType == "VOLUNTEERS_NEEDED") {
theBigQuestion.visibility = View.VISIBLE
optionA.visibility = View.VISIBLE
optionB.visibility = View.VISIBLE
theBigQuestion.text = "Will You Volunteer?"
}
else if (todo.todoType == "VALIDATION_REQUIRED") {
theBigQuestion.visibility = View.VISIBLE
optionA.visibility = View.VISIBLE
optionB.visibility = View.VISIBLE
theBigQuestion.text = "Is The Action Complete?"
}
else if (todo.todoType == "INFORMATION_REQUIRED") {
todoTextBoxButton.visibility = View.VISIBLE
todoTextBox.visibility = View.VISIBLE
}
else if (todo.todoType == "ACTION_REQUIRED") {
// This option is informative so display no additional info
}
todo.deadlineMillis?.let { todoDate.text = DateFormatter.formatMeetingDate(it) }
renderDescription(todo)
renderResponseSection(todo)
}
private fun renderResponseSection(todo: Todo) {
// Here we display available options.
if (todo.hasResponded()) {
if (todo.todoType != "INFORMATION_REQUIRED" && todo.todoType != "ACTION_REQUIRED") {
todoStatusText.visibility = View.VISIBLE
when (todo.response) {
Todo.TODO_YES -> {
todoStatusText.text = "YES"
todoStatusText.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_attend, 0, 0)
}
Todo.TODO_NO -> {
todoStatusText.text = "NO"
todoStatusText.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_not_attending, 0, 0)
}
}
}
else if (todo.todoType == "INFORMATION_REQUIRED") {
todoStatusText.text = "You Have Responded"
todoTextBox.visibility = View.GONE
}
optionContainer.visibility = View.GONE
} else {
if (todo.todoType != "INFORMATION_REQUIRED" && todo.todoType != "ACTION_REQUIRED") {
optionA.setOnClickListener({ _ -> presenter.respondToTodo(todo.uid, Todo.TODO_YES) })
optionB.setOnClickListener({ _ -> presenter.respondToTodo(todo.uid, Todo.TODO_NO) })
}
else if (todo.todoType == "INFORMATION_REQUIRED") {
var mEdit = findViewById(R.id.todoTextBox) as EditText
todoTextBoxButton.setOnClickListener({ _ -> presenter.respondToTodo(todo.uid, mEdit.text.toString())})
}
}
}
private fun renderDescription(todo: Todo) {
if (TextUtils.isEmpty(todo.description)) {
todoDescription.visibility = View.GONE
} else {
todoDescription.visibility = View.VISIBLE
todoDescription.text = todo.description
}
}
override fun renderResponses(todoResponses: Map<String, String>) {
// resultsAdapter.setData(convertTodoResponses(todoResponses));
}
//
// private fun convertTodoResponses(todoResponse: Map<String, String>): List<TodoResponse> {
// if (todoResponse == null) {
// val list = listOf<TodoResponse>()
// return list
// } else {
// return todoResponse.map { entry -> TodoResponse(entry.key, entry.value) }
// }
// }
/*override fun renderPosts(posts: List<Post>) {
if (posts.isNotEmpty()) {
listTitle.visibility = View.VISIBLE
postAdapter.setData(posts)
}
}*/
companion object {
val EXTRA_TODO_UID = "todo_uid"
val TRIGGERED_BY_NOTIFICATION = "triggered_by_notification"
fun start(activity: Activity, todoUid: String) {
val intent = Intent(activity, TodoDetailsActivity::class.java)
intent.putExtra(EXTRA_TODO_UID, todoUid)
activity.startActivity(intent)
}
}
}
| bsd-3-clause | a45bfb6be4ea22b452a1c4112df460d9 | 38.241206 | 118 | 0.634652 | 4.545402 | false | false | false | false |
ansman/okhttp | okhttp/src/main/kotlin/okhttp3/RequestBody.kt | 2 | 8283 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.io.File
import java.io.IOException
import java.nio.charset.Charset
import kotlin.text.Charsets.UTF_8
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.internal.checkOffsetAndCount
import okio.BufferedSink
import okio.ByteString
import okio.source
abstract class RequestBody {
/** Returns the Content-Type header for this body. */
abstract fun contentType(): MediaType?
/**
* Returns the number of bytes that will be written to sink in a call to [writeTo],
* or -1 if that count is unknown.
*/
@Throws(IOException::class)
open fun contentLength(): Long = -1L
/** Writes the content of this request to [sink]. */
@Throws(IOException::class)
abstract fun writeTo(sink: BufferedSink)
/**
* A duplex request body is special in how it is **transmitted** on the network and
* in the **API contract** between OkHttp and the application.
*
* This method returns false unless it is overridden by a subclass.
*
* ### Duplex Transmission
*
* With regular HTTP calls the request always completes sending before the response may begin
* receiving. With duplex the request and response may be interleaved! That is, request body bytes
* may be sent after response headers or body bytes have been received.
*
* Though any call may be initiated as a duplex call, only web servers that are specially
* designed for this nonstandard interaction will use it. As of 2019-01, the only widely-used
* implementation of this pattern is [gRPC][grpc].
*
* Because the encoding of interleaved data is not well-defined for HTTP/1, duplex request
* bodies may only be used with HTTP/2. Calls to HTTP/1 servers will fail before the HTTP request
* is transmitted. If you cannot ensure that your client and server both support HTTP/2, do not
* use this feature.
*
* ### Duplex APIs
*
* With regular request bodies it is not legal to write bytes to the sink passed to
* [RequestBody.writeTo] after that method returns. For duplex requests bodies that condition is
* lifted. Such writes occur on an application-provided thread and may occur concurrently with
* reads of the [ResponseBody]. For duplex request bodies, [writeTo] should return
* quickly, possibly by handing off the provided request body to another thread to perform
* writing.
*
* [grpc]: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
*/
open fun isDuplex(): Boolean = false
/**
* Returns true if this body expects at most one call to [writeTo] and can be transmitted
* at most once. This is typically used when writing the request body is destructive and it is not
* possible to recreate the request body after it has been sent.
*
* This method returns false unless it is overridden by a subclass.
*
* By default OkHttp will attempt to retransmit request bodies when the original request fails
* due to any of:
*
* * A stale connection. The request was made on a reused connection and that reused connection
* has since been closed by the server.
* * A client timeout (HTTP 408).
* * A authorization challenge (HTTP 401 and 407) that is satisfied by the [Authenticator].
* * A retryable server failure (HTTP 503 with a `Retry-After: 0` response header).
* * A misdirected request (HTTP 421) on a coalesced connection.
*/
open fun isOneShot(): Boolean = false
companion object {
/**
* Returns a new request body that transmits this string. If [contentType] is non-null and lacks
* a charset, this will use UTF-8.
*/
@JvmStatic
@JvmName("create")
fun String.toRequestBody(contentType: MediaType? = null): RequestBody {
var charset: Charset = UTF_8
var finalContentType: MediaType? = contentType
if (contentType != null) {
val resolvedCharset = contentType.charset()
if (resolvedCharset == null) {
charset = UTF_8
finalContentType = "$contentType; charset=utf-8".toMediaTypeOrNull()
} else {
charset = resolvedCharset
}
}
val bytes = toByteArray(charset)
return bytes.toRequestBody(finalContentType, 0, bytes.size)
}
/** Returns a new request body that transmits this. */
@JvmStatic
@JvmName("create")
fun ByteString.toRequestBody(contentType: MediaType? = null): RequestBody {
return object : RequestBody() {
override fun contentType() = contentType
override fun contentLength() = size.toLong()
override fun writeTo(sink: BufferedSink) {
sink.write(this@toRequestBody)
}
}
}
/** Returns a new request body that transmits this. */
@JvmOverloads
@JvmStatic
@JvmName("create")
fun ByteArray.toRequestBody(
contentType: MediaType? = null,
offset: Int = 0,
byteCount: Int = size
): RequestBody {
checkOffsetAndCount(size.toLong(), offset.toLong(), byteCount.toLong())
return object : RequestBody() {
override fun contentType() = contentType
override fun contentLength() = byteCount.toLong()
override fun writeTo(sink: BufferedSink) {
sink.write(this@toRequestBody, offset, byteCount)
}
}
}
/** Returns a new request body that transmits the content of this. */
@JvmStatic
@JvmName("create")
fun File.asRequestBody(contentType: MediaType? = null): RequestBody {
return object : RequestBody() {
override fun contentType() = contentType
override fun contentLength() = length()
override fun writeTo(sink: BufferedSink) {
source().use { source -> sink.writeAll(source) }
}
}
}
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.toRequestBody(contentType)",
imports = ["okhttp3.RequestBody.Companion.toRequestBody"]
),
level = DeprecationLevel.WARNING)
fun create(contentType: MediaType?, content: String) = content.toRequestBody(contentType)
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.toRequestBody(contentType)",
imports = ["okhttp3.RequestBody.Companion.toRequestBody"]
),
level = DeprecationLevel.WARNING)
fun create(
contentType: MediaType?,
content: ByteString
): RequestBody = content.toRequestBody(contentType)
@JvmOverloads
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.toRequestBody(contentType, offset, byteCount)",
imports = ["okhttp3.RequestBody.Companion.toRequestBody"]
),
level = DeprecationLevel.WARNING)
fun create(
contentType: MediaType?,
content: ByteArray,
offset: Int = 0,
byteCount: Int = content.size
) = content.toRequestBody(contentType, offset, byteCount)
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'file' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "file.asRequestBody(contentType)",
imports = ["okhttp3.RequestBody.Companion.asRequestBody"]
),
level = DeprecationLevel.WARNING)
fun create(contentType: MediaType?, file: File) = file.asRequestBody(contentType)
}
}
| apache-2.0 | 51a4ff9cca7cfb448c056f0b40a95e35 | 36.479638 | 100 | 0.679826 | 4.637738 | false | false | false | false |
MisumiRize/HackerNews-Android | app/src/androidTest/kotlin/org/misumirize/hackernews/app/DisableAnimationsRule.kt | 1 | 1909 | package org.misumirize.hackernews.app
import android.os.IBinder
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.lang.reflect.Method
import java.util.*
class DisableAnimationsRule : TestRule {
val setAnimationScalesMethod: Method;
val getAnimationScalesMethod: Method;
val windowManagerObject: Any;
init {
val windowManagerStubClazz = Class.forName("android.view.IWindowManager\$Stub");
val asInterface = windowManagerStubClazz.getDeclaredMethod("asInterface", IBinder::class.java);
val serviceManagerClazz = Class.forName("android.os.ServiceManager");
val getService = serviceManagerClazz.getDeclaredMethod("getService", String::class.java);
val windowManagerClazz = Class.forName("android.view.IWindowManager");
setAnimationScalesMethod = windowManagerClazz.getDeclaredMethod("setAnimationScales", FloatArray::class.java);
getAnimationScalesMethod = windowManagerClazz.getDeclaredMethod("getAnimationScales");
val windowManagerBinder = getService.invoke(null, "window") as IBinder;
windowManagerObject = asInterface.invoke(null, windowManagerBinder);
}
override fun apply(base: Statement?, description: Description?): Statement? {
return object: Statement() {
override fun evaluate() {
setAnimationScaleFactors(0.0f)
try {
base?.evaluate()
} finally {
setAnimationScaleFactors(1.0f)
}
}
}
}
private fun setAnimationScaleFactors(scaleFactor: Float) {
val scaleFactors = getAnimationScalesMethod.invoke(windowManagerObject) as FloatArray;
Arrays.fill(scaleFactors, scaleFactor);
setAnimationScalesMethod.invoke(windowManagerObject, scaleFactors);
}
}
| mit | 930449cc16a9fb9fdbf20580d93d5551 | 37.18 | 118 | 0.700891 | 5.173442 | false | false | false | false |
ExMCL/ExMCL | ExMCL Forge Mods/src/main/kotlin/com/n9mtq4/exmcl/forgemods/data/ModData.kt | 1 | 2977 | /*
* MIT License
*
* Copyright (c) 2016 Will (n9Mtq4) Bresnahan
*
* 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.n9mtq4.exmcl.forgemods.data
import com.n9mtq4.exmcl.forgemods.utils.msg
import com.n9mtq4.exmcl.forgemods.utils.readForgeDataFromFile
import com.n9mtq4.exmcl.forgemods.utils.writeToFile
import com.n9mtq4.kotlin.extlib.syntax.def
import java.io.File
import java.io.IOException
import java.util.ArrayList
import javax.swing.JOptionPane
/**
* Created by will on 2/14/16 at 10:10 PM.
*
* @author Will "n9Mtq4" Bresnahan
*/
class ModData(val profiles: ProfileList, var selectedProfileIndex: Int) {
private typealias ProfileList = ArrayList<ModProfile>
companion object {
private const val MOD_LOCATION = "data/forgemods.json.lzma"
}
object Loader {
fun load(): ModData {
val file = File(MOD_LOCATION)
if (!file.exists()) return createNewModData()
try {
val modData: ModData = readForgeDataFromFile(file)
return modData
}catch (e: Exception) {
e.printStackTrace()
msg(msg = "There was an error loading the ModData\nWe are generating a new one.", title = "Error", msgType = JOptionPane.ERROR_MESSAGE)
return createNewModData()
}
}
private fun createNewModData() = def {
val modData = ModData()
val defaultProfile = ModProfile("Default")
modData.addProfile(defaultProfile)
modData
}
}
constructor(): this(ProfileList(), 0)
@Throws(IOException::class)
fun save() = save(File(MOD_LOCATION))
@Throws(IOException::class)
private fun save(file: File) {
file.parentFile.mkdirs()
writeToFile(file)
}
fun getSelectedProfile() = profiles[selectedProfileIndex]
fun addProfile(profile: ModProfile) = profiles.add(profile)
fun getProfileByName(name: String) = profiles.find { it.profileName == name }
fun getProfileNames() = profiles.map { it.profileName }
fun removeProfile(profileIndex: Int) = profiles.removeAt(profileIndex)
}
| mit | c7114b88879ad8fafc051acee85e0065 | 32.077778 | 139 | 0.741686 | 3.758838 | false | false | false | false |
fallGamlet/DnestrCinema | app/src/main/java/com/fallgamlet/dnestrcinema/ui/base/BaseFragment.kt | 1 | 2422 | package com.fallgamlet.dnestrcinema.ui.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.fallgamlet.dnestrcinema.R
import com.fallgamlet.dnestrcinema.utils.ViewUtils
import com.google.android.material.snackbar.Snackbar
abstract class BaseFragment: Fragment() {
private var errorLive: MutableLiveData<Throwable?> = MutableLiveData()
private var loadingLive: MutableLiveData<Boolean?> = MutableLiveData()
abstract val layoutId: Int
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(layoutId, container, false)
}
protected fun setErrorLive(errorLive: MutableLiveData<Throwable?>) {
this.errorLive.removeObservers(this)
this.errorLive = errorLive
errorLive.observe(this, Observer { onError(it) } )
}
protected fun setLoadingLive(loadingLive: MutableLiveData<Boolean?>) {
this.loadingLive.removeObservers(this)
this.loadingLive = loadingLive
loadingLive.observe(this, Observer { onLoading(it) } )
}
open protected fun onError(throwable: Throwable?) {
throwable ?: return
errorLive.value = null
showError(throwable)
}
open protected fun showError(throwable: Throwable) {
val view = this.view?: return
val message = throwable.toString()
ViewUtils.makeSnackbar(view, message, Snackbar.LENGTH_LONG)
.setAction(R.string.label_more) { showErrorDetails(throwable) }
.show()
}
open protected fun showErrorDetails(throwable: Throwable) {
val context = this.context ?: return
val message = "${throwable.message}\n\n$throwable"
AlertDialog.Builder(context)
.setMessage(message)
.create()
.show()
}
open protected fun onLoading(value: Boolean?) {
}
protected fun getViewModelProvider(): ViewModelProvider {
return activity?.let { ViewModelProviders.of(it) }
?: ViewModelProviders.of(this)
}
}
| gpl-3.0 | cd69a0a1756c62b06148f7ba63858d2a | 29.275 | 75 | 0.699835 | 4.815109 | false | false | false | false |
wiltonlazary/kotlin-native | runtime/src/main/kotlin/kotlin/native/concurrent/Atomics.kt | 1 | 12071 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin.native.concurrent
import kotlin.native.internal.ExportTypeInfo
import kotlin.native.internal.Frozen
import kotlin.native.internal.LeakDetectorCandidate
import kotlin.native.internal.NoReorderFields
import kotlin.native.SymbolName
import kotlinx.cinterop.NativePtr
/**
* Atomic values and freezing: atomics [AtomicInt], [AtomicLong], [AtomicNativePtr] and [AtomicReference]
* are unique types with regard to freezing. Namely, they provide mutating operations, while can participate
* in frozen subgraphs. So shared frozen objects can have fields of atomic types.
*/
@Frozen
public class AtomicInt(private var value_: Int) {
/**
* The value being held by this class.
*/
public var value: Int
get() = getImpl()
set(new) = setImpl(new)
/**
* Increments the value by [delta] and returns the new value.
*
* @param delta the value to add
* @return the new value
*/
@SymbolName("Kotlin_AtomicInt_addAndGet")
external public fun addAndGet(delta: Int): Int
/**
* Compares value with [expected] and replaces it with [new] value if values matches.
*
* @param expected the expected value
* @param new the new value
* @return the old value
*/
@SymbolName("Kotlin_AtomicInt_compareAndSwap")
external public fun compareAndSwap(expected: Int, new: Int): Int
/**
* Compares value with [expected] and replaces it with [new] value if values matches.
*
* @param expected the expected value
* @param new the new value
* @return true if successful
*/
@SymbolName("Kotlin_AtomicInt_compareAndSet")
external public fun compareAndSet(expected: Int, new: Int): Boolean
/**
* Increments value by one.
*/
public fun increment(): Unit {
addAndGet(1)
}
/**
* Decrements value by one.
*/
public fun decrement(): Unit {
addAndGet(-1)
}
/**
* Returns the string representation of this object.
*
* @return the string representation
*/
public override fun toString(): String = value.toString()
// Implementation details.
@SymbolName("Kotlin_AtomicInt_set")
private external fun setImpl(new: Int): Unit
@SymbolName("Kotlin_AtomicInt_get")
private external fun getImpl(): Int
}
@Frozen
public class AtomicLong(private var value_: Long = 0) {
/**
* The value being held by this class.
*/
public var value: Long
get() = getImpl()
set(new) = setImpl(new)
/**
* Increments the value by [delta] and returns the new value.
*
* @param delta the value to add
* @return the new value
*/
@SymbolName("Kotlin_AtomicLong_addAndGet")
external public fun addAndGet(delta: Long): Long
/**
* Increments the value by [delta] and returns the new value.
*
* @param delta the value to add
* @return the new value
*/
public fun addAndGet(delta: Int): Long = addAndGet(delta.toLong())
/**
* Compares value with [expected] and replaces it with [new] value if values matches.
*
* @param expected the expected value
* @param new the new value
* @return the old value
*/
@SymbolName("Kotlin_AtomicLong_compareAndSwap")
external public fun compareAndSwap(expected: Long, new: Long): Long
/**
* Compares value with [expected] and replaces it with [new] value if values matches.
*
* @param expected the expected value
* @param new the new value
* @return true if successful, false if state is unchanged
*/
@SymbolName("Kotlin_AtomicLong_compareAndSet")
external public fun compareAndSet(expected: Long, new: Long): Boolean
/**
* Increments value by one.
*/
public fun increment(): Unit {
addAndGet(1L)
}
/**
* Decrements value by one.
*/
fun decrement(): Unit {
addAndGet(-1L)
}
/**
* Returns the string representation of this object.
*
* @return the string representation of this object
*/
public override fun toString(): String = value.toString()
// Implementation details.
@SymbolName("Kotlin_AtomicLong_set")
private external fun setImpl(new: Long): Unit
@SymbolName("Kotlin_AtomicLong_get")
private external fun getImpl(): Long
}
@Frozen
public class AtomicNativePtr(private var value_: NativePtr) {
/**
* The value being held by this class.
*/
public var value: NativePtr
get() = getImpl()
set(new) = setImpl(new)
/**
* Compares value with [expected] and replaces it with [new] value if values matches.
* If [new] value is not null, it must be frozen or permanent object.
*
* @param expected the expected value
* @param new the new value
* @throws InvalidMutabilityException if [new] is not frozen or a permanent object
* @return the old value
*/
@SymbolName("Kotlin_AtomicNativePtr_compareAndSwap")
external public fun compareAndSwap(expected: NativePtr, new: NativePtr): NativePtr
/**
* Compares value with [expected] and replaces it with [new] value if values matches.
*
* @param expected the expected value
* @param new the new value
* @return true if successful
*/
@SymbolName("Kotlin_AtomicNativePtr_compareAndSet")
external public fun compareAndSet(expected: NativePtr, new: NativePtr): Boolean
/**
* Returns the string representation of this object.
*
* @return string representation of this object
*/
public override fun toString(): String = value.toString()
// Implementation details.
@SymbolName("Kotlin_AtomicNativePtr_set")
private external fun setImpl(new: NativePtr): Unit
@SymbolName("Kotlin_AtomicNativePtr_get")
private external fun getImpl(): NativePtr
}
private fun idString(value: Any) = "${value.hashCode().toUInt().toString(16)}"
private fun debugString(value: Any?): String {
if (value == null) return "null"
return "${value::class.qualifiedName}: ${idString(value)}"
}
/**
* An atomic reference to a frozen Kotlin object. Can be used in concurrent scenarious
* but frequently shall be of nullable type and be zeroed out once no longer needed.
* Otherwise memory leak could happen. To detect such leaks [kotlin.native.internal.GC.detectCycles]
* in debug mode could be helpful.
*/
@Frozen
@LeakDetectorCandidate
@NoReorderFields
public class AtomicReference<T> {
private var value_: T
// A spinlock to fix potential ARC race.
private var lock: Int = 0
// Optimization for speeding up access.
private var cookie: Int = 0
/**
* Creates a new atomic reference pointing to given [ref].
* @throws InvalidMutabilityException if reference is not frozen.
*/
constructor(value: T) {
checkIfFrozen(value)
value_ = value
}
/**
* The referenced value.
* Gets the value or sets the [new] value. If [new] value is not null,
* it must be frozen or permanent object.
*
* @throws InvalidMutabilityException if the value is not frozen or a permanent object
*/
public var value: T
get() = @Suppress("UNCHECKED_CAST")(getImpl() as T)
set(new) = setImpl(new)
/**
* Compares value with [expected] and replaces it with [new] value if values matches.
* Note that comparison is identity-based, not value-based.
* If [new] value is not null, it must be frozen or permanent object.
*
* @param expected the expected value
* @param new the new value
* @throws InvalidMutabilityException if the value is not frozen or a permanent object
* @return the old value
*/
@SymbolName("Kotlin_AtomicReference_compareAndSwap")
external public fun compareAndSwap(expected: T, new: T): T
/**
* Compares value with [expected] and replaces it with [new] value if values matches.
* Note that comparison is identity-based, not value-based.
*
* @param expected the expected value
* @param new the new value
* @return true if successful
*/
@SymbolName("Kotlin_AtomicReference_compareAndSet")
external public fun compareAndSet(expected: T, new: T): Boolean
/**
* Returns the string representation of this object.
*
* @return string representation of this object
*/
public override fun toString(): String =
"${debugString(this)} -> ${debugString(value)}"
// Implementation details.
@SymbolName("Kotlin_AtomicReference_set")
private external fun setImpl(new: Any?): Unit
@SymbolName("Kotlin_AtomicReference_get")
private external fun getImpl(): Any?
}
/**
* An atomic reference to a Kotlin object. Can be used in concurrent scenarious, but must be frozen first,
* otherwise behaves as regular box for the value. If frozen, shall be zeroed out once no longer needed.
* Otherwise memory leak could happen. To detect such leaks [kotlin.native.internal.GC.detectCycles]
* in debug mode could be helpful.
*/
@NoReorderFields
@LeakDetectorCandidate
@ExportTypeInfo("theFreezableAtomicReferenceTypeInfo")
public class FreezableAtomicReference<T>(private var value_: T) {
// A spinlock to fix potential ARC race.
private var lock: Int = 0
// Optimization for speeding up access.
private var cookie: Int = 0
/**
* The referenced value.
* Gets the value or sets the [new] value. If [new] value is not null,
* and `this` is frozen - it must be frozen or permanent object.
*
* @throws InvalidMutabilityException if the value is not frozen or a permanent object
*/
public var value: T
get() = @Suppress("UNCHECKED_CAST")(getImpl() as T)
set(new) {
if (this.isFrozen)
setImpl(new)
else
value_ = new
}
/**
* Compares value with [expected] and replaces it with [new] value if values matches.
* If [new] value is not null and object is frozen, it must be frozen or permanent object.
*
* @param expected the expected value
* @param new the new value
* @throws InvalidMutabilityException if the value is not frozen or a permanent object
* @return the old value
*/
public fun compareAndSwap(expected: T, new: T): T {
return if (this.isFrozen) @Suppress("UNCHECKED_CAST")(compareAndSwapImpl(expected, new) as T) else {
val old = value_
if (old === expected) value_ = new
old
}
}
/**
* Compares value with [expected] and replaces it with [new] value if values matches.
* Note that comparison is identity-based, not value-based.
*
* @param expected the expected value
* @param new the new value
* @return true if successful
*/
public fun compareAndSet(expected: T, new: T): Boolean {
if (this.isFrozen) return compareAndSetImpl(expected, new)
val old = value_
if (old === expected) {
value_ = new
return true
} else {
return false
}
}
/**
* Returns the string representation of this object.
*
* @return string representation of this object
*/
public override fun toString(): String =
"${debugString(this)} -> ${debugString(value)}"
// Implementation details.
@SymbolName("Kotlin_AtomicReference_set")
private external fun setImpl(new: Any?): Unit
@SymbolName("Kotlin_AtomicReference_get")
private external fun getImpl(): Any?
@SymbolName("Kotlin_AtomicReference_compareAndSwap")
private external fun compareAndSwapImpl(expected: Any?, new: Any?): Any?
@SymbolName("Kotlin_AtomicReference_compareAndSet")
private external fun compareAndSetImpl(expected: Any?, new: Any?): Boolean
}
| apache-2.0 | 50fef7fa5e5ab36fed31fb066dccd2cc | 30.599476 | 108 | 0.65355 | 4.368802 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-chart/src/main/java/net/nemerosa/ontrack/extension/chart/support/PercentageChart.kt | 1 | 1606 | package net.nemerosa.ontrack.extension.chart.support
import net.nemerosa.ontrack.extension.chart.Chart
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics
import java.time.LocalDateTime
data class PercentageChart(
val dates: List<String>,
val data: List<Double>,
): Chart {
companion object {
fun compute(items: List<PercentageChartItemData>, interval: Interval, period: String): PercentageChart {
// Period based formatting
val intervalPeriod = parseIntervalPeriod(period)
// Gets all the intervals for the given period
val intervals = interval.split(intervalPeriod)
// Chart
return PercentageChart(
dates = intervals.map {
intervalPeriod.format(it.start)
},
data = computeData(items, intervals)
)
}
private fun computeData(items: List<PercentageChartItemData>, intervals: List<Interval>) =
intervals.map { interval ->
computeDataPoint(items, interval)
}
private fun computeDataPoint(items: List<PercentageChartItemData>, interval: Interval): Double {
val sample = items.filter {
it.timestamp in interval
}.mapNotNull {
it.value
}
val stats = DescriptiveStatistics()
sample.forEach { stats.addValue(it) }
return stats.mean
}
}
}
data class PercentageChartItemData(
val timestamp: LocalDateTime,
val value: Double?,
) | mit | 799beca097fd60d8441b142a88f939cb | 29.903846 | 112 | 0.612702 | 5.050314 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/adapter/LinkAdapter.kt | 1 | 2892 | package treehou.se.habit.ui.adapter
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import java.util.ArrayList
import se.treehou.ng.ohcommunicator.connector.models.OHLink
import treehou.se.habit.R
class LinkAdapter : RecyclerView.Adapter<LinkAdapter.LinkHolder>() {
private val items = ArrayList<OHLink>()
private var itemListener: ItemListener = DummyItemListener()
inner class LinkHolder(view: View) : RecyclerView.ViewHolder(view) {
private val lblItem: TextView
private val lblChannel: TextView
init {
lblItem = view.findViewById<View>(R.id.lbl_item) as TextView
lblChannel = itemView.findViewById<View>(R.id.lbl_channel) as TextView
}
fun update(link: OHLink) {
lblChannel.text = link.channelUID
lblItem.text = link.itemName
itemView.setOnClickListener { view -> itemListener.onItemClickListener(link) }
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): LinkHolder {
return LinkHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.item_link, viewGroup, false))
}
override fun onBindViewHolder(holder: LinkHolder, position: Int) {
val item = items[position]
holder.update(item)
}
override fun getItemCount(): Int {
return items.size
}
fun setItemListener(itemListener: ItemListener?) {
if (itemListener == null) {
this.itemListener = DummyItemListener()
return
}
this.itemListener = itemListener
}
fun addItem(item: OHLink) {
items.add(0, item)
notifyItemInserted(0)
}
fun addAll(items: List<OHLink>) {
for (item in items) {
this.items.add(0, item)
}
notifyDataSetChanged()
}
fun removeItem(position: Int) {
Log.d(TAG, "removeItem: " + position)
items.removeAt(position)
notifyItemRemoved(position)
}
fun removeItem(item: OHLink) {
val position = items.indexOf(item)
items.removeAt(position)
notifyItemRemoved(position)
}
/**
* Remove all items from adapter
*/
fun clear() {
this.items.clear()
notifyDataSetChanged()
}
interface ItemListener {
fun onItemClickListener(item: OHLink)
fun onItemLongClickListener(item: OHLink): Boolean
}
private inner class DummyItemListener : ItemListener {
override fun onItemClickListener(item: OHLink) {}
override fun onItemLongClickListener(item: OHLink): Boolean {
return false
}
}
companion object {
private val TAG = LinkAdapter::class.java.simpleName
}
}
| epl-1.0 | 5d48e5018cde423e59085a6b6612dab4 | 25.290909 | 111 | 0.649032 | 4.490683 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/feature/player/filter/BaseFilterFragment.kt | 1 | 2876 | package be.florien.anyflow.feature.player.filter
import android.content.DialogInterface
import android.os.Bundle
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import be.florien.anyflow.R
import be.florien.anyflow.feature.BaseFragment
import be.florien.anyflow.feature.menu.ConfirmMenuHolder
import be.florien.anyflow.feature.menu.MenuCoordinator
import be.florien.anyflow.feature.menu.SaveFilterGroupMenuHolder
import be.florien.anyflow.feature.player.PlayerActivity
abstract class BaseFilterFragment : BaseFragment() {
protected val menuCoordinator = MenuCoordinator()
protected abstract val baseViewModel: BaseFilterViewModel
private val confirmMenuHolder = ConfirmMenuHolder {
baseViewModel.confirmChanges()
}
protected val saveMenuHolder = SaveFilterGroupMenuHolder {
val editText = EditText(requireActivity())
editText.inputType = EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES
AlertDialog.Builder(requireActivity())
.setView(editText)
.setTitle(R.string.filter_group_name)
.setPositiveButton(R.string.ok) { _: DialogInterface, _: Int ->
baseViewModel.saveFilterGroup(editText.text.toString())
}
.setNegativeButton(R.string.cancel) { dialog: DialogInterface, _: Int ->
dialog.cancel()
}
.show()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
menuCoordinator.addMenuHolder(confirmMenuHolder)
menuCoordinator.addMenuHolder(saveMenuHolder)
setHasOptionsMenu(true)
}
override fun onResume() {
super.onResume()
confirmMenuHolder.isVisible = baseViewModel.hasChangeFromCurrentFilters.value == true
baseViewModel.hasChangeFromCurrentFilters.observe(viewLifecycleOwner) {
confirmMenuHolder.isVisible = it == true
}
baseViewModel.areFiltersInEdition.observe(viewLifecycleOwner) {
if (!it) {
(requireActivity() as PlayerActivity).displaySongList()
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
menuCoordinator.inflateMenus(menu, inflater)
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menuCoordinator.prepareMenus(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return menuCoordinator.handleMenuClick(item.itemId)
}
override fun onDestroy() {
super.onDestroy()
menuCoordinator.removeMenuHolder(confirmMenuHolder)
menuCoordinator.removeMenuHolder(saveMenuHolder)
}
} | gpl-3.0 | acecd777815e4bbf16d42697b11de7c4 | 35.884615 | 98 | 0.710709 | 4.866328 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/tasker/TaskerInitActivity.kt | 1 | 1478 | package treehou.se.habit.tasker
import android.app.Activity
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import treehou.se.habit.R
class TaskerInitActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tasker_init)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val actionbar = supportActionBar
if (actionbar != null) {
actionbar.setDisplayHomeAsUpEnabled(true)
actionbar.setHomeButtonEnabled(true)
}
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.add(R.id.container, ActionSelectFragment())
.commit()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
// Respond to the action bar's Up/Home button
android.R.id.home -> {
if (supportFragmentManager.backStackEntryCount >= 1) {
supportFragmentManager.popBackStack()
} else {
setResult(Activity.RESULT_CANCELED)
finish()
}
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| epl-1.0 | 67a1ff5cbfbd04a747492f7eaddc57e1 | 30.446809 | 70 | 0.614344 | 5.297491 | false | false | false | false |
nextcloud/android | app/src/main/java/com/owncloud/android/utils/glide/HttpStreamFetcher.kt | 1 | 3284 | /*
* Nextcloud Android client application
*
* @author Alejandro Bautista
* @author Chris Narkiewicz
*
* Copyright (C) 2017 Alejandro Bautista
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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.owncloud.android.utils.glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.data.DataFetcher
import com.nextcloud.client.account.User
import com.nextcloud.client.network.ClientFactory
import com.owncloud.android.lib.common.operations.RemoteOperation
import com.owncloud.android.lib.common.utils.Log_OC
import org.apache.commons.httpclient.HttpStatus
import org.apache.commons.httpclient.methods.GetMethod
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
/**
* Fetcher with OwnCloudClient
*/
@Suppress("TooGenericExceptionCaught")
class HttpStreamFetcher internal constructor(
private val user: User,
private val clientFactory: ClientFactory,
private val url: String
) : DataFetcher<InputStream?> {
@Throws(Exception::class)
override fun loadData(priority: Priority): InputStream? {
val client = clientFactory.create(user)
if (client != null) {
var get: GetMethod? = null
try {
get = GetMethod(url)
get.setRequestHeader("Cookie", "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true")
get.setRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE)
val status = client.executeMethod(get)
if (status == HttpStatus.SC_OK) {
return getResponseAsInputStream(get)
} else {
client.exhaustResponse(get.responseBodyAsStream)
}
} catch (e: Exception) {
Log_OC.e(TAG, e.message, e)
} finally {
get?.releaseConnection()
}
}
return null
}
private fun getResponseAsInputStream(getMethod: GetMethod): ByteArrayInputStream {
val byteOutputStream = ByteArrayOutputStream()
getMethod.responseBodyAsStream.use { input ->
byteOutputStream.use { output ->
input.copyTo(output)
}
}
return ByteArrayInputStream(byteOutputStream.toByteArray())
}
override fun cleanup() {
Log_OC.i(TAG, "Cleanup")
}
override fun getId(): String {
return url
}
override fun cancel() {
Log_OC.i(TAG, "Cancel")
}
companion object {
private val TAG = HttpStreamFetcher::class.java.name
}
}
| gpl-2.0 | 5892c9774af63f4ccbd8007669aa0244 | 33.208333 | 106 | 0.673873 | 4.461957 | false | false | false | false |
ol-loginov/intellij-community | platform/vcs-log/graph/test/com/intellij/vcs/log/graph/StrUtils.kt | 18 | 3427 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.graph
import com.intellij.vcs.log.graph.api.LinearGraph
import com.intellij.vcs.log.graph.api.elements.GraphNode
import com.intellij.vcs.log.graph.parser.EdgeNodeCharConverter.*
import com.intellij.vcs.log.graph.api.elements.GraphEdge
import com.intellij.vcs.log.graph.parser.CommitParser
import com.intellij.vcs.log.graph.api.printer.PrintElementGenerator
import com.intellij.vcs.log.graph.api.elements.GraphElement
import com.intellij.vcs.log.graph.api.EdgeFilter
import com.intellij.vcs.log.graph.impl.print.elements.PrintElementWithGraphElement
fun LinearGraph.asString(sorted: Boolean = false): String {
val s = StringBuilder()
for (nodeIndex in 0..nodesCount() - 1) {
if (nodeIndex > 0) s.append("\n");
val node = getGraphNode(nodeIndex)
s.append(node.asString()).append(CommitParser.SEPARATOR)
var adjEdges = getAdjacentEdges(nodeIndex, EdgeFilter.ALL)
if (sorted) {
adjEdges = adjEdges.sortBy(GraphStrUtils.GRAPH_ELEMENT_COMPARATOR)
}
adjEdges.map { it.asString() }.joinTo(s, separator = " ")
}
return s.toString();
}
fun GraphNode.asString(): String = "${getNodeIndex()}_${toChar(getType())}"
fun Int?.asString() = if (this == null) "n" else toString()
fun GraphEdge.asString(): String = "${getUpNodeIndex().asString()}:${getDownNodeIndex().asString()}:${getTargetId().asString()}_${toChar(getType())}"
fun GraphElement.asString(): String = when (this) {
is GraphNode -> asString()
is GraphEdge -> asString()
else -> throw IllegalArgumentException("Uncown type of PrintElement: $this")
}
fun PrintElementWithGraphElement.asString(): String {
val element = getGraphElement().asString()
val row = getRowIndex()
val color = getColorId()
val pos = getPositionInCurrentRow()
val sel = if (isSelected()) "Select" else "Unselect"
return when (this) {
is SimplePrintElement -> {
val t = getType()
"Simple:${t}|-$row:${pos}|-$color:${sel}($element)"
}
is EdgePrintElement -> {
val t = getType()
val ls = getLineStyle()
val posO = getPositionInOtherRow()
"Edge:$t:${ls}|-$row:$pos:${posO}|-$color:$sel($element)"
}
else -> {
throw IllegalStateException("Uncown type of PrintElement: $this")
}
}
}
fun PrintElementGenerator.asString(size: Int): String {
val s = StringBuilder()
for (row in 0..size - 1) {
if (row > 0) s.append("\n")
val elements = getPrintElements(row).sortBy {
val pos = it.getPositionInCurrentRow()
if (it is SimplePrintElement) {
1024 * pos + it.getType().ordinal()
} else if (it is EdgePrintElement) {
1024 * pos + (it.getType().ordinal() + 1) * 64 + it.getPositionInOtherRow()
} else 0
}
elements.map { it.asString() }.joinTo(s, separator = "\n ")
}
return s.toString()
} | apache-2.0 | dd6b2abd1f2971d07f50747dc080409b | 33.979592 | 149 | 0.6904 | 3.708874 | false | false | false | false |
apixandru/intellij-community | plugins/git4idea/tests/git4idea/tests/GitCommitTest.kt | 2 | 8278 | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.tests
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.Executor.*
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.Change
import com.intellij.util.containers.ContainerUtil
import git4idea.GitUtil
import git4idea.checkin.GitCheckinEnvironment
import git4idea.test.*
import java.io.File
import java.util.*
class GitCommitTest : GitSingleRepoTest() {
override fun getDebugLogCategories() = super.getDebugLogCategories().plus("#" + GitCheckinEnvironment::class.java.name)
// IDEA-50318
fun `test merge commit with spaces in path`() {
val PATH = "dir with spaces/file with spaces.txt"
createFileStructure(myProjectRoot, PATH)
addCommit("created some file structure")
git("branch feature")
val file = File(myProjectPath, PATH)
assertTrue("File doesn't exist!", file.exists())
overwrite(file, "my content")
addCommit("modified in master")
checkout("feature")
overwrite(file, "brother content")
addCommit("modified in feature")
checkout("master")
git("merge feature", true) // ignoring non-zero exit-code reporting about conflicts
overwrite(file, "merged content") // manually resolving conflict
git("add .")
updateChangeListManager()
val changes = changeListManager.allChanges
assertTrue(!changes.isEmpty())
commit(changes)
assertNoChanges()
}
fun `test commit case rename`() {
generateCaseRename("a.java", "A.java")
val changes = assertChanges {
rename("a.java", "A.java")
}
commit(changes)
assertNoChanges()
myRepo.assertCommitted {
rename("a.java", "A.java")
}
}
fun `test commit case rename + one staged file`() {
generateCaseRename("a.java", "A.java")
touch("s.java")
git("add s.java")
val changes = assertChanges {
rename("a.java", "A.java")
added("s.java")
}
commit(changes)
assertNoChanges()
myRepo.assertCommitted {
rename("a.java", "A.java")
added("s.java")
}
}
fun `test commit case rename + one unstaged file`() {
tac("m.java")
generateCaseRename("a.java", "A.java")
echo("m.java", "unstaged")
val changes = assertChanges {
rename("a.java", "A.java")
modified("m.java")
}
commit(changes)
assertNoChanges()
myRepo.assertCommitted {
rename("a.java", "A.java")
modified("m.java")
}
}
fun `test commit case rename & don't commit one unstaged file`() {
tac("m.java")
generateCaseRename("a.java", "A.java")
echo("m.java", "unstaged")
val changes = assertChanges {
rename("a.java", "A.java")
modified("m.java")
}
commit(listOf(changes[0]))
assertChanges {
modified("m.java")
}
myRepo.assertCommitted {
rename("a.java", "A.java")
}
}
fun `test commit case rename & don't commit one staged file`() {
tac("s.java")
generateCaseRename("a.java", "A.java")
echo("s.java", "staged")
git("add s.java")
val changes = assertChanges {
rename("a.java", "A.java")
modified("s.java")
}
commit(listOf(changes[0]))
myRepo.assertCommitted {
rename("a.java", "A.java")
}
assertChanges {
modified("s.java")
}
myRepo.assertStagedChanges {
modified("s.java")
}
}
fun `test commit case rename & don't commit one staged simple rename, then rename should remain staged`() {
echo("before.txt", "some\ncontent\nere")
addCommit("created before.txt")
generateCaseRename("a.java", "A.java")
git("mv before.txt after.txt")
val changes = assertChanges {
rename("a.java", "A.java")
rename("before.txt", "after.txt")
}
commit(listOf(changes[0]))
myRepo.assertCommitted {
rename("a.java", "A.java")
}
assertChanges {
rename("before.txt", "after.txt")
}
myRepo.assertStagedChanges {
rename("before.txt", "after.txt")
}
}
fun `test commit case rename + one unstaged file & don't commit one staged file`() {
tac("s.java")
tac("m.java")
generateCaseRename("a.java", "A.java")
echo("s.java", "staged")
echo("m.java", "unstaged")
git("add s.java m.java")
val changes = assertChanges {
rename("a.java", "A.java")
modified("s.java")
modified("m.java")
}
commit(listOf(changes[0], changes[2]))
myRepo.assertCommitted {
rename("a.java", "A.java")
modified("m.java")
}
assertChanges {
modified("s.java")
}
myRepo.assertStagedChanges {
modified("s.java")
}
}
fun `test commit case rename & don't commit a file which is both staged and unstaged, should reset and restore`() {
tac("c.java")
generateCaseRename("a.java", "A.java")
echo("c.java", "staged")
git("add c.java")
overwrite("c.java", "unstaged")
val changes = assertChanges {
rename("a.java", "A.java")
modified("c.java")
}
commit(listOf(changes[0]))
myRepo.assertCommitted {
rename("a.java", "A.java")
}
assertChanges {
modified("c.java")
}
myRepo.assertStagedChanges {
modified("c.java")
}
// this is intentional data loss: it is a rare case, while restoring both staged and unstaged part is not so easy,
// so we are not doing it, at least until IDEA supports Git index
// (which will mean that users will be able to produce such situation intentionally with a help of IDE).
assertEquals("unstaged", git("show :c.java"))
assertEquals("unstaged", FileUtil.loadFile(File(myProjectPath, "c.java")))
}
fun `test commit case rename with additional non-staged changes should commit everything`() {
val initialContent = """
some
large
content
to let
rename
detection
work
""".trimIndent()
touch("a.java", initialContent)
addCommit("initial a.java")
git("mv -f a.java A.java")
val additionalContent = "non-staged content"
append("A.java", additionalContent)
val changes = assertChanges {
rename("a.java", "A.java")
}
commit(changes)
myRepo.assertCommitted {
rename("a.java", "A.java")
}
assertNoChanges()
assertEquals(initialContent + additionalContent, git("show HEAD:A.java"))
}
private fun generateCaseRename(from: String, to: String) {
tac(from)
git("mv -f $from $to")
}
private fun commit(changes: Collection<Change>) {
val exceptions = myVcs.checkinEnvironment!!.commit(ArrayList(changes), "comment")
assertNoExceptions(exceptions)
updateChangeListManager()
}
private fun assertNoChanges() {
val changes = changeListManager.getChangesIn(myProjectRoot)
assertTrue("We expected no changes but found these: " + GitUtil.getLogString(myProjectPath, changes), changes.isEmpty())
}
private fun assertNoExceptions(exceptions: List<VcsException>?) {
val ex = ContainerUtil.getFirstItem(exceptions)
if (ex != null) {
LOG.error(ex)
fail("Exception during executing the commit: " + ex.message)
}
}
private fun assertChanges(changes: ChangesBuilder.() -> Unit) : List<Change> {
val cb = ChangesBuilder()
cb.changes()
updateChangeListManager()
val allChanges = mutableListOf<Change>()
val actualChanges = HashSet(changeListManager.allChanges)
for (change in cb.changes) {
val found = actualChanges.find(change.matcher)
assertNotNull("The change [$change] not found", found)
actualChanges.remove(found)
allChanges.add(found!!)
}
assertTrue(actualChanges.isEmpty())
return allChanges
}
}
| apache-2.0 | 70d72e6a80d01772684c8e0496d4c246 | 25.617363 | 124 | 0.646895 | 3.945663 | false | false | false | false |
cashapp/sqldelight | sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/inspections/MismatchJoinColumnInspection.kt | 1 | 2190 | package app.cash.sqldelight.intellij.inspections
import app.cash.sqldelight.core.lang.psi.isColumnSameAs
import app.cash.sqldelight.core.lang.psi.isTypeSameAs
import app.cash.sqldelight.core.lang.util.findChildrenOfType
import com.alecstrong.sql.psi.core.psi.SqlBinaryEqualityExpr
import com.alecstrong.sql.psi.core.psi.SqlColumnExpr
import com.alecstrong.sql.psi.core.psi.SqlExpr
import com.alecstrong.sql.psi.core.psi.SqlJoinConstraint
import com.alecstrong.sql.psi.core.psi.SqlParenExpr
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.PsiFile
internal class MismatchJoinColumnInspection : LocalInspectionTool() {
override fun checkFile(
file: PsiFile,
manager: InspectionManager,
isOnTheFly: Boolean,
) = ensureFileReady(file) {
val joinConstraints = file.findChildrenOfType<SqlJoinConstraint>()
.mapNotNull { it.expr?.binaryEqualityExpr() }
return joinConstraints.mapNotNull { joinEquality ->
val exprList = joinEquality.getExprList()
if (exprList.size < 2) return@mapNotNull null
val (expr1, expr2) = exprList
if (expr1 !is SqlColumnExpr || expr2 !is SqlColumnExpr) return@mapNotNull null
val column1 = expr1.columnName
val column2 = expr2.columnName
if (column1.isColumnSameAs(column2)) {
return@mapNotNull manager.createProblemDescriptor(
joinEquality,
"Join condition always evaluates to true",
isOnTheFly,
emptyArray(),
ProblemHighlightType.WARNING,
)
}
if (!column1.isTypeSameAs(column2)) {
return@mapNotNull manager.createProblemDescriptor(
joinEquality,
"Join compares two columns of different types",
isOnTheFly,
emptyArray(),
ProblemHighlightType.WARNING,
)
}
return@mapNotNull null
}.toTypedArray()
}
private fun SqlExpr.binaryEqualityExpr(): SqlBinaryEqualityExpr? = when (this) {
is SqlParenExpr -> expr?.binaryEqualityExpr()
is SqlBinaryEqualityExpr -> this
else -> null
}
}
| apache-2.0 | 9bf2bfda967b0ff47ed4ab9b08ce7f48 | 34.322581 | 84 | 0.726027 | 4.469388 | false | false | false | false |
doerfli/hacked | app/src/main/kotlin/li/doerf/hacked/services/AccountService.kt | 1 | 2642 | package li.doerf.hacked.services
import android.app.Application
import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.work.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import li.doerf.hacked.CustomEvent
import li.doerf.hacked.R
import li.doerf.hacked.db.AppDatabase
import li.doerf.hacked.db.daos.AccountDao
import li.doerf.hacked.db.entities.Account
import li.doerf.hacked.remote.hibp.HIBPAccountCheckerWorker
import li.doerf.hacked.ui.fragments.AccountsFragment
import li.doerf.hacked.util.Analytics
import li.doerf.hacked.util.createCoroutingExceptionHandler
class AccountService(private val application: Application) {
private var context: Context = application.applicationContext
fun addAccount(aName: String) {
if ( aName.trim { it <= ' ' } == "") {
Toast.makeText(context, context.getString(R.string.toast_enter_valid_name), Toast.LENGTH_LONG).show()
Log.w(AccountsFragment.LOGTAG, "account name not valid")
return
}
val name = aName.trim { it <= ' ' }
runBlocking(context = Dispatchers.IO) {
launch(createCoroutingExceptionHandler(AccountsFragment.LOGTAG)) {
addNewAccount(name)
}
}
}
private fun addNewAccount(name: String) {
val accountDao = AppDatabase.get(context).accountDao
val count = accountDao.countByName(name)
if (count > 0) {
return
}
insertAccount(accountDao, createNewAccount(name))
}
private fun createNewAccount(name: String): Account {
val account = Account()
account.name = name
account.numBreaches = 0
account.numAcknowledgedBreaches = 0
return account
}
private fun insertAccount(accountDao: AccountDao, account: Account) {
val ids = accountDao.insert(account)
Analytics.trackCustomEvent(CustomEvent.ACCOUNT_ADDED)
checkNewAccount(ids)
}
private fun checkNewAccount(ids: MutableList<Long>) {
val inputData = Data.Builder()
.putLong(HIBPAccountCheckerWorker.KEY_ID, ids[0])
.build()
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.build()
val checker = OneTimeWorkRequest.Builder(HIBPAccountCheckerWorker::class.java)
.setInputData(inputData)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueue(checker)
}
} | apache-2.0 | b5de1c7611cd60e97f5c5da070be7eb0 | 33.324675 | 113 | 0.676003 | 4.309951 | false | false | false | false |
zserge/anvil-examples | todo-kotlin/src/main/kotlin/com/example/anvil/todo/TodoView.kt | 1 | 1960 | package com.example.anvil.todo
import android.content.Context
import android.widget.LinearLayout
import trikita.anvil.RenderableView
import trikita.anvil.RenderableAdapter
// Kotlin has a bug with importing static methods
// so we have to import whole hierarchy of classes instead
import trikita.anvil.DSL.*
// A classic to-do list application
//
// You have a list of to-do items
// You can add to this list
// You can check an item in the list as "completed"
// "Completed" items still stay in the list
// You can actually remove all "completed" items from the list
class TodoView(c: Context) : RenderableView(c) {
var message = ""
var todoAdapter = RenderableAdapter.withItems(Todo.items) { pos, value ->
linearLayout {
size(FILL, WRAP)
minHeight(dip(72))
textView {
size(0, WRAP)
weight(1f)
layoutGravity(CENTER_VERTICAL)
padding(dip(5))
text(value.message)
}
checkBox {
size(WRAP, WRAP)
margin(dip(5))
layoutGravity(CENTER_VERTICAL)
focusable(false)
focusableInTouchMode(false)
clickable(false)
checked(value.checked)
}
}
}
override fun view() {
todoAdapter.notifyDataSetChanged()
linearLayout {
size(FILL, WRAP)
orientation(LinearLayout.VERTICAL)
linearLayout {
size(FILL, WRAP)
editText {
size(0, WRAP)
weight(1f)
text(message)
onTextChanged { s ->
message = s.toString()
}
}
button {
size(WRAP, WRAP)
layoutGravity(CENTER_VERTICAL)
text("Add")
enabled(message.trim().length != 0)
onClick {
Todo.add(message)
message = ""
}
}
}
button {
size(FILL, WRAP)
padding(dip(5))
text("Clear checked tasks")
enabled(Todo.hasChecked())
onClick {
Todo.clear()
}
}
listView {
size(FILL, WRAP)
itemsCanFocus(true)
onItemClick { parent, view, pos, id ->
Todo.toggle(pos)
}
adapter(todoAdapter)
}
}
}
}
| mit | 1e7b6d1f11768eeb9b73a6b27358d6ce | 18.79798 | 74 | 0.647449 | 3.361921 | false | false | false | false |
AndroidX/androidx | wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/PickerSample.kt | 3 | 5480 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material.samples
import android.view.MotionEvent
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Picker
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.rememberPickerState
import kotlinx.coroutines.launch
@Sampled
@Composable
fun SimplePicker() {
val items = listOf("One", "Two", "Three", "Four", "Five")
val state = rememberPickerState(items.size)
val contentDescription by remember { derivedStateOf { "${state.selectedOption + 1}" } }
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
modifier = Modifier.align(Alignment.TopCenter).padding(top = 10.dp),
text = "Selected: ${items[state.selectedOption]}"
)
Picker(
modifier = Modifier.size(100.dp, 100.dp),
state = state,
contentDescription = contentDescription,
) {
Text(items[it])
}
}
}
@Sampled
@Composable
fun OptionChangePicker() {
val coroutineScope = rememberCoroutineScope()
val state = rememberPickerState(initialNumberOfOptions = 10)
val contentDescription by remember { derivedStateOf { "${state.selectedOption + 1}" } }
Picker(
state = state,
separation = 4.dp,
contentDescription = contentDescription,
) {
Chip(
onClick = {
coroutineScope.launch { state.scrollToOption(it) }
},
label = {
Text("$it")
}
)
}
}
@OptIn(ExperimentalComposeUiApi::class)
@Sampled
@Composable
fun DualPicker() {
var selectedColumn by remember { mutableStateOf(0) }
val textStyle = MaterialTheme.typography.display1
@Composable
fun Option(column: Int, text: String) = Box(modifier = Modifier.fillMaxSize()) {
Text(
text = text, style = textStyle,
color = if (selectedColumn == column) MaterialTheme.colors.secondary
else MaterialTheme.colors.onBackground,
modifier = Modifier
.align(Alignment.Center).wrapContentSize()
.pointerInteropFilter {
if (it.action == MotionEvent.ACTION_DOWN) selectedColumn = column
true
}
)
}
Row(
modifier = Modifier.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
val hourState = rememberPickerState(
initialNumberOfOptions = 12,
initiallySelectedOption = 5
)
val hourContentDescription by remember {
derivedStateOf { "${hourState.selectedOption + 1 } hours" }
}
Picker(
readOnly = selectedColumn != 0,
state = hourState,
modifier = Modifier.size(64.dp, 100.dp),
contentDescription = hourContentDescription,
option = { hour: Int -> Option(0, "%2d".format(hour + 1)) }
)
Spacer(Modifier.width(8.dp))
Text(text = ":", style = textStyle, color = MaterialTheme.colors.onBackground)
Spacer(Modifier.width(8.dp))
val minuteState =
rememberPickerState(initialNumberOfOptions = 60, initiallySelectedOption = 0)
val minuteContentDescription by remember {
derivedStateOf { "${minuteState.selectedOption} minutes" }
}
Picker(
readOnly = selectedColumn != 1,
state = minuteState,
modifier = Modifier.size(64.dp, 100.dp),
contentDescription = minuteContentDescription,
option = { minute: Int -> Option(1, "%02d".format(minute)) }
)
}
} | apache-2.0 | 994d8cec7dff332e4e62b18b142fbbc5 | 35.059211 | 91 | 0.673723 | 4.744589 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/imagepicker/PickerResultsStore.kt | 2 | 3134 | package abi44_0_0.expo.modules.imagepicker
import android.content.Context
import android.content.SharedPreferences
import android.net.Uri
import android.os.Bundle
import android.os.Parcel
import android.util.Base64
import android.util.Log
import org.apache.commons.io.IOUtils
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.util.*
import kotlin.collections.ArrayList
const val SHARED_PREFERENCES_NAME = "expo.modules.imagepicker.PickerResultsStore"
const val EXPIRE_KEY = "expire"
const val EXPIRATION_TIME = 5 * 60 * 1000 // 5 min
/**
* Class that represents a temporary store to promise's results.
* It's used if the android kills current activity and we can't resolve promise immediately.
*/
class PickerResultsStore(context: Context) {
private val sharedPreferences: SharedPreferences =
context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
fun addPendingResult(bundle: Bundle) {
bundle.putLong(EXPIRE_KEY, Date().time + EXPIRATION_TIME)
val uuid = UUID.randomUUID().toString()
val encodedBundle = Base64.encodeToString(bundleToBytes(bundle), 0)
sharedPreferences
.edit()
.putString(uuid, encodedBundle)
.apply()
}
fun getAllPendingResults(): List<Bundle> {
val result = ArrayList<Bundle>()
val now = Date().time
for ((_, value) in sharedPreferences.all) {
if (value is String) {
bytesToBundle(Base64.decode(value, 0))
?.let { decodedBundle ->
if (decodedBundle.containsKey("uri")) {
if (decodedBundle.getLong(EXPIRE_KEY) < now) {
return@let
}
val decodedPath = Uri.parse(decodedBundle.getString("uri")).path!!
// The picked file is in the cache folder, so the android could delete it.
if (!File(decodedPath).exists()) {
return@let
}
if (decodedBundle.getBoolean("base64", false)) {
readAsBase64(decodedPath)?.let {
decodedBundle.putString("base64", it)
}
}
}
decodedBundle.remove(EXPIRE_KEY)
result.add(decodedBundle)
}
}
}
sharedPreferences
.edit()
.clear()
.apply()
return result
}
private fun readAsBase64(path: String): String? {
try {
FileInputStream(File(path)).use {
val output = ByteArrayOutputStream()
IOUtils.copy(it, output)
return Base64.encodeToString(output.toByteArray(), Base64.NO_WRAP)
}
} catch (e: IOException) {
Log.e(ImagePickerConstants.TAG, e.message, e)
return null
}
}
private fun bundleToBytes(bundle: Bundle) = Parcel.obtain().run {
writeBundle(bundle)
val bytes = marshall()
recycle()
bytes
}
private fun bytesToBundle(bytes: ByteArray) = Parcel.obtain().run {
unmarshall(bytes, 0, bytes.size)
setDataPosition(0)
val bundle = readBundle(PickerResultsStore::class.java.classLoader)
recycle()
bundle
}
}
| bsd-3-clause | 7bc0b04bc60a2130098d6e4a3aa3ce17 | 28.018519 | 92 | 0.650606 | 4.27558 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/util/ParametersListLexer.kt | 3 | 1283 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.util
// Copy of com.intellij.openapi.externalSystem.service.execution.cmd.ParametersListLexer,
// which is not present in all IDEs.
class ParametersListLexer(private val myText: String) {
private var myTokenStart = -1
private var index = 0
val tokenEnd: Int
get() {
assert(myTokenStart >= 0)
return index
}
val currentToken: String
get() = myText.substring(myTokenStart, index)
fun nextToken(): Boolean {
var i = index
while (i < myText.length && Character.isWhitespace(myText[i])) {
i++
}
if (i == myText.length) return false
myTokenStart = i
var isInQuote = false
do {
val a = myText[i]
if (!isInQuote && Character.isWhitespace(a)) break
when {
a == '\\' && i + 1 < myText.length && myText[i + 1] == '"' -> i += 2
a == '"' -> {
i++
isInQuote = !isInQuote
}
else -> i++
}
} while (i < myText.length)
index = i
return true
}
}
| mit | e47195cd56d6760644875ef28765e93b | 24.156863 | 89 | 0.512081 | 4.319865 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/support/FAQDetailFragment.kt | 1 | 2364 | package com.habitrpg.android.habitica.ui.fragments.support
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.FAQRepository
import com.habitrpg.android.habitica.databinding.FragmentFaqDetailBinding
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.MarkdownParser
import javax.inject.Inject
class FAQDetailFragment : BaseMainFragment<FragmentFaqDetailBinding>() {
@Inject
lateinit var faqRepository: FAQRepository
override var binding: FragmentFaqDetailBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentFaqDetailBinding {
return FragmentFaqDetailBinding.inflate(inflater, container, false)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
hidesToolbar = true
showsBackButton = true
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
val args = FAQDetailFragmentArgs.fromBundle(it)
if (args.question != null) {
binding?.questionTextView?.text = args.question
binding?.answerTextView?.text = MarkdownParser.parseMarkdown(args.answer)
} else {
compositeSubscription.add(
faqRepository.getArticle(args.position).subscribe(
{ faq ->
binding?.questionTextView?.text = faq.question
binding?.answerTextView?.text = MarkdownParser.parseMarkdown(faq.answer)
},
RxErrorHandler.handleEmptyError()
)
)
}
}
binding?.answerTextView?.movementMethod = LinkMovementMethod.getInstance()
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
}
| gpl-3.0 | ebc1c4cdebdafef32b430d4349fdf078 | 39.067797 | 116 | 0.691624 | 5.348416 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/model/DisplayedItemType.kt | 1 | 484 | package com.sedsoftware.yaptalker.presentation.model
object DisplayedItemType {
const val NEWS = 1
const val FORUM = 2
const val TOPIC = 3
const val ACTIVE_TOPIC = 4
const val BOOKMARKED_TOPIC = 5
const val SINGLE_POST = 6
const val NAVIGATION_PANEL = 7
const val SEARCHED_TOPIC = 8
const val FORUM_INFO = 9
const val TOPIC_INFO = 10
const val GALLERY_IMAGE = 11
const val SEARCH_TOPIC_INFO = 12
const val BLACKLISTED_TOPIC = 13
}
| apache-2.0 | 2089d32878500bd1b889903ddf2569d8 | 27.470588 | 52 | 0.681818 | 3.903226 | false | false | false | false |
androidx/androidx | compose/ui/ui-unit/src/commonMain/kotlin/androidx/compose/ui/unit/Constraints.kt | 3 | 18269 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.unit
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
/**
* Immutable constraints for measuring layouts, used by [layouts][androidx.compose.ui.layout.Layout]
* or [layout modifiers][androidx.compose.ui.layout.LayoutModifier] to measure their layout
* children. The parent chooses the [Constraints] defining a range, in pixels, within which
* the measured layout should choose a size:
*
* - `minWidth` <= `chosenWidth` <= `maxWidth`
* - `minHeight` <= `chosenHeight` <= `maxHeight`
*
* For more details about how layout measurement works, see
* [androidx.compose.ui.layout.MeasurePolicy] or
* [androidx.compose.ui.layout.LayoutModifier.measure].
*
* A set of [Constraints] can have infinite maxWidth and/or maxHeight. This is a trick often
* used by parents to ask their children for their preferred size: unbounded constraints force
* children whose default behavior is to fill the available space (always size to
* maxWidth/maxHeight) to have an opinion about their preferred size. Most commonly, when measured
* with unbounded [Constraints], these children will fallback to size themselves to wrap their
* content, instead of expanding to fill the available space (this is not always true
* as it depends on the child layout model, but is a common behavior for core layout components).
*
* [Constraints] uses a [Long] to represent four values, [minWidth], [minHeight], [maxWidth],
* and [maxHeight]. The range of the values varies to allow for at most 256K in one dimension.
* There are four possible maximum ranges, 13 bits/18 bits, and 15 bits/16 bits for either width
* or height, depending on the needs. For example, a width could range up to 18 bits
* and the height up to 13 bits. Alternatively, the width could range up to 16 bits and the height
* up to 15 bits. The height and width requirements can be reversed, with a height of up to 18 bits
* and width of 13 bits or height of 16 bits and width of 15 bits. Any constraints exceeding
* this range will fail.
*/
@Immutable
@kotlin.jvm.JvmInline
value class Constraints(
@PublishedApi internal val value: Long
) {
/**
* Indicates how the bits are assigned. One of:
* * MinFocusWidth
* * MaxFocusWidth
* * MinFocusHeight
* * MaxFocusHeight
*/
private val focusIndex
get() = (value and FocusMask).toInt()
/**
* The minimum width that the measurement can take, in pixels.
*/
val minWidth: Int
get() {
val mask = WidthMask[focusIndex]
return ((value shr 2).toInt() and mask)
}
/**
* The maximum width that the measurement can take, in pixels. This will either be
* a positive value greater than or equal to [minWidth] or [Constraints.Infinity].
*/
val maxWidth: Int
get() {
val mask = WidthMask[focusIndex]
val width = ((value shr 33).toInt() and mask)
return if (width == 0) Infinity else width - 1
}
/**
* The minimum height that the measurement can take, in pixels.
*/
val minHeight: Int
get() {
val focus = focusIndex
val mask = HeightMask[focus]
val offset = MinHeightOffsets[focus]
return (value shr offset).toInt() and mask
}
/**
* The maximum height that the measurement can take, in pixels. This will either be
* a positive value greater than or equal to [minHeight] or [Constraints.Infinity].
*/
val maxHeight: Int
get() {
val focus = focusIndex
val mask = HeightMask[focus]
val offset = MinHeightOffsets[focus] + 31
val height = (value shr offset).toInt() and mask
return if (height == 0) Infinity else height - 1
}
/**
* `false` when [maxWidth] is [Infinity] and `true` if [maxWidth] is a non-[Infinity] value.
* @see hasBoundedHeight
*/
val hasBoundedWidth: Boolean
get() {
val mask = WidthMask[focusIndex]
return ((value shr 33).toInt() and mask) != 0
}
/**
* `false` when [maxHeight] is [Infinity] and `true` if [maxHeight] is a non-[Infinity] value.
* @see hasBoundedWidth
*/
val hasBoundedHeight: Boolean
get() {
val focus = focusIndex
val mask = HeightMask[focus]
val offset = MinHeightOffsets[focus] + 31
return ((value shr offset).toInt() and mask) != 0
}
/**
* Whether there is exactly one width value that satisfies the constraints.
*/
@Stable
val hasFixedWidth get() = maxWidth == minWidth
/**
* Whether there is exactly one height value that satisfies the constraints.
*/
@Stable
val hasFixedHeight get() = maxHeight == minHeight
/**
* Whether the area of a component respecting these constraints will definitely be 0.
* This is true when at least one of maxWidth and maxHeight are 0.
*/
@Stable
val isZero get() = maxWidth == 0 || maxHeight == 0
/**
* Copies the existing [Constraints], replacing some of [minWidth], [minHeight], [maxWidth],
* or [maxHeight] as desired. [minWidth] and [minHeight] must be positive and
* [maxWidth] and [maxHeight] must be greater than or equal to [minWidth] and [minHeight],
* respectively, or [Infinity].
*/
fun copy(
minWidth: Int = this.minWidth,
maxWidth: Int = this.maxWidth,
minHeight: Int = this.minHeight,
maxHeight: Int = this.maxHeight
): Constraints {
require(minHeight >= 0 && minWidth >= 0) {
"minHeight($minHeight) and minWidth($minWidth) must be >= 0"
}
require(maxWidth >= minWidth || maxWidth == Infinity) {
"maxWidth($maxWidth) must be >= minWidth($minWidth)"
}
require(maxHeight >= minHeight || maxHeight == Infinity) {
"maxHeight($maxHeight) must be >= minHeight($minHeight)"
}
return createConstraints(minWidth, maxWidth, minHeight, maxHeight)
}
override fun toString(): String {
val maxWidth = maxWidth
val maxWidthStr = if (maxWidth == Infinity) "Infinity" else maxWidth.toString()
val maxHeight = maxHeight
val maxHeightStr = if (maxHeight == Infinity) "Infinity" else maxHeight.toString()
return "Constraints(minWidth = $minWidth, maxWidth = $maxWidthStr, " +
"minHeight = $minHeight, maxHeight = $maxHeightStr)"
}
companion object {
/**
* A value that [maxWidth] or [maxHeight] will be set to when the constraint should
* be considered infinite. [hasBoundedWidth] or [hasBoundedHeight] will be
* `false` when [maxWidth] or [maxHeight] is [Infinity], respectively.
*/
const val Infinity = Int.MAX_VALUE
/**
* The bit distribution when the focus of the bits should be on the width, but only
* a minimal difference in focus.
*
* 16 bits assigned to width, 15 bits assigned to height.
*/
private const val MinFocusWidth = 0x00L
/**
* The bit distribution when the focus of the bits should be on the width, and a
* maximal number of bits assigned to the width.
*
* 18 bits assigned to width, 13 bits assigned to height.
*/
private const val MaxFocusWidth = 0x01L
/**
* The bit distribution when the focus of the bits should be on the height, but only
* a minimal difference in focus.
*
* 15 bits assigned to width, 16 bits assigned to height.
*/
private const val MinFocusHeight = 0x02L
/**
* The bit distribution when the focus of the bits should be on the height, and a
* a maximal number of bits assigned to the height.
*
* 13 bits assigned to width, 18 bits assigned to height.
*/
private const val MaxFocusHeight = 0x03L
/**
* The mask to retrieve the focus ([MinFocusWidth], [MaxFocusWidth],
* [MinFocusHeight], [MaxFocusHeight]).
*/
private const val FocusMask = 0x03L
/**
* The number of bits used for the focused dimension when there is minimal focus.
*/
private const val MinFocusBits = 16
/**
* The mask to use for the focused dimension when there is minimal focus.
*/
private const val MinFocusMask = 0xFFFF // 64K (16 bits)
/**
* The number of bits used for the non-focused dimension when there is minimal focus.
*/
private const val MinNonFocusBits = 15
/**
* The mask to use for the non-focused dimension when there is minimal focus.
*/
private const val MinNonFocusMask = 0x7FFF // 32K (15 bits)
/**
* The number of bits to use for the focused dimension when there is maximal focus.
*/
private const val MaxFocusBits = 18
/**
* The mask to use for the focused dimension when there is maximal focus.
*/
private const val MaxFocusMask = 0x3FFFF // 256K (18 bits)
/**
* The number of bits to use for the non-focused dimension when there is maximal focus.
*/
private const val MaxNonFocusBits = 13
/**
* The mask to use for the non-focused dimension when there is maximal focus.
*/
private const val MaxNonFocusMask = 0x1FFF // 8K (13 bits)
/**
* Minimum Height shift offsets into Long value, indexed by FocusMask
* Max offsets are these + 31
* Width offsets are always either 2 (min) or 33 (max)
*/
private val MinHeightOffsets = intArrayOf(
18, // MinFocusWidth: 2 + 16
20, // MaxFocusWidth: 2 + 18
17, // MinFocusHeight: 2 + 15
15 // MaxFocusHeight: 2 + 13
)
/**
* The mask to use for both minimum and maximum width.
*/
private val WidthMask = intArrayOf(
MinFocusMask, // MinFocusWidth (16 bits)
MaxFocusMask, // MaxFocusWidth (18 bits)
MinNonFocusMask, // MinFocusHeight (15 bits)
MaxNonFocusMask // MaxFocusHeight (13 bits)
)
/**
* The mask to use for both minimum and maximum height.
*/
private val HeightMask = intArrayOf(
MinNonFocusMask, // MinFocusWidth (15 bits)
MaxNonFocusMask, // MaxFocusWidth (13 bits)
MinFocusMask, // MinFocusHeight (16 bits)
MaxFocusMask // MaxFocusHeight (18 bits)
)
/**
* Creates constraints for fixed size in both dimensions.
*/
@Stable
fun fixed(
width: Int,
height: Int
): Constraints {
require(width >= 0 && height >= 0) {
"width($width) and height($height) must be >= 0"
}
return createConstraints(width, width, height, height)
}
/**
* Creates constraints for fixed width and unspecified height.
*/
@Stable
fun fixedWidth(
width: Int
): Constraints {
require(width >= 0) {
"width($width) must be >= 0"
}
return createConstraints(
minWidth = width,
maxWidth = width,
minHeight = 0,
maxHeight = Infinity
)
}
/**
* Creates constraints for fixed height and unspecified width.
*/
@Stable
fun fixedHeight(
height: Int
): Constraints {
require(height >= 0) {
"height($height) must be >= 0"
}
return createConstraints(
minWidth = 0,
maxWidth = Infinity,
minHeight = height,
maxHeight = height
)
}
/**
* Creates a [Constraints], only checking that the values fit in the packed Long.
*/
internal fun createConstraints(
minWidth: Int,
maxWidth: Int,
minHeight: Int,
maxHeight: Int
): Constraints {
val heightVal = if (maxHeight == Infinity) minHeight else maxHeight
val heightBits = bitsNeedForSize(heightVal)
val widthVal = if (maxWidth == Infinity) minWidth else maxWidth
val widthBits = bitsNeedForSize(widthVal)
if (widthBits + heightBits > 31) {
throw IllegalArgumentException(
"Can't represent a width of $widthVal and height " +
"of $heightVal in Constraints"
)
}
val focus = when (widthBits) {
MinNonFocusBits -> MinFocusHeight
MinFocusBits -> MinFocusWidth
MaxNonFocusBits -> MaxFocusHeight
MaxFocusBits -> MaxFocusWidth
else -> throw IllegalStateException("Should only have the provided constants.")
}
val maxWidthValue = if (maxWidth == Infinity) 0 else maxWidth + 1
val maxHeightValue = if (maxHeight == Infinity) 0 else maxHeight + 1
val minHeightOffset = MinHeightOffsets[focus.toInt()]
val maxHeightOffset = minHeightOffset + 31
val value = focus or
(minWidth.toLong() shl 2) or
(maxWidthValue.toLong() shl 33) or
(minHeight.toLong() shl minHeightOffset) or
(maxHeightValue.toLong() shl maxHeightOffset)
return Constraints(value)
}
private fun bitsNeedForSize(size: Int): Int {
return when {
size < MaxNonFocusMask -> MaxNonFocusBits
size < MinNonFocusMask -> MinNonFocusBits
size < MinFocusMask -> MinFocusBits
size < MaxFocusMask -> MaxFocusBits
else -> throw IllegalArgumentException(
"Can't represent a size of $size in " +
"Constraints"
)
}
}
}
}
/**
* Create a [Constraints]. [minWidth] and [minHeight] must be positive and
* [maxWidth] and [maxHeight] must be greater than or equal to [minWidth] and [minHeight],
* respectively, or [Infinity][Constraints.Infinity].
*/
@Stable
fun Constraints(
minWidth: Int = 0,
maxWidth: Int = Constraints.Infinity,
minHeight: Int = 0,
maxHeight: Int = Constraints.Infinity
): Constraints {
require(maxWidth >= minWidth) {
"maxWidth($maxWidth) must be >= than minWidth($minWidth)"
}
require(maxHeight >= minHeight) {
"maxHeight($maxHeight) must be >= than minHeight($minHeight)"
}
require(minWidth >= 0 && minHeight >= 0) {
"minWidth($minWidth) and minHeight($minHeight) must be >= 0"
}
return Constraints.createConstraints(minWidth, maxWidth, minHeight, maxHeight)
}
/**
* Takes [otherConstraints] and returns the result of coercing them in the current constraints.
* Note this means that any size satisfying the resulting constraints will satisfy the current
* constraints, but they might not satisfy the [otherConstraints] when the two set of constraints
* are disjoint.
* Examples (showing only width, height works the same):
* (minWidth=2, maxWidth=10).constrain(minWidth=7, maxWidth=12) -> (minWidth = 7, maxWidth = 10)
* (minWidth=2, maxWidth=10).constrain(minWidth=11, maxWidth=12) -> (minWidth=10, maxWidth=10)
* (minWidth=2, maxWidth=10).constrain(minWidth=5, maxWidth=7) -> (minWidth=5, maxWidth=7)
*/
fun Constraints.constrain(otherConstraints: Constraints) = Constraints(
minWidth = otherConstraints.minWidth.coerceIn(minWidth, maxWidth),
maxWidth = otherConstraints.maxWidth.coerceIn(minWidth, maxWidth),
minHeight = otherConstraints.minHeight.coerceIn(minHeight, maxHeight),
maxHeight = otherConstraints.maxHeight.coerceIn(minHeight, maxHeight)
)
/**
* Takes a size and returns the closest size to it that satisfies the constraints.
*/
@Stable
fun Constraints.constrain(size: IntSize) = IntSize(
width = size.width.coerceIn(minWidth, maxWidth),
height = size.height.coerceIn(minHeight, maxHeight)
)
/**
* Takes a width and returns the closest size to it that satisfies the constraints.
*/
@Stable
fun Constraints.constrainWidth(width: Int) = width.coerceIn(minWidth, maxWidth)
/**
* Takes a height and returns the closest size to it that satisfies the constraints.
*/
@Stable
fun Constraints.constrainHeight(height: Int) = height.coerceIn(minHeight, maxHeight)
/**
* Takes a size and returns whether it satisfies the current constraints.
*/
@Stable
fun Constraints.isSatisfiedBy(size: IntSize): Boolean {
return size.width in minWidth..maxWidth && size.height in minHeight..maxHeight
}
/**
* Returns the Constraints obtained by offsetting the current instance with the given values.
*/
@Stable
fun Constraints.offset(horizontal: Int = 0, vertical: Int = 0) = Constraints(
(minWidth + horizontal).coerceAtLeast(0),
addMaxWithMinimum(maxWidth, horizontal),
(minHeight + vertical).coerceAtLeast(0),
addMaxWithMinimum(maxHeight, vertical)
)
private fun addMaxWithMinimum(max: Int, value: Int): Int {
return if (max == Constraints.Infinity) {
max
} else {
(max + value).coerceAtLeast(0)
}
}
| apache-2.0 | 98b7fe684bce64ab142f75fc6b78590b | 35.611222 | 100 | 0.615688 | 4.599446 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-core/src/org/jetbrains/kotlin/core/model/KotlinAnalysisProjectCache.kt | 1 | 3138 | /*******************************************************************************
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.core.model
import org.eclipse.core.resources.IFile
import org.eclipse.core.resources.IProject
import org.eclipse.core.resources.IResourceChangeEvent
import org.eclipse.core.resources.IResourceChangeListener
import org.eclipse.jdt.core.IJavaProject
import org.eclipse.jdt.core.JavaCore
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.core.builder.KotlinPsiManager
import org.jetbrains.kotlin.core.resolve.EclipseAnalyzerFacadeForJVM
import org.jetbrains.kotlin.core.utils.ProjectUtils
import java.util.concurrent.ConcurrentHashMap
public object KotlinAnalysisProjectCache : IResourceChangeListener {
private val cachedAnalysisResults = ConcurrentHashMap<IProject, AnalysisResult>()
public fun resetCache(project: IProject) {
synchronized(project) {
cachedAnalysisResults.remove(project)
}
}
public fun getAnalysisResult(javaProject: IJavaProject): AnalysisResult {
val project = javaProject.getProject()
return synchronized(project) {
val analysisResult = cachedAnalysisResults.get(project) ?: run {
EclipseAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(
KotlinEnvironment.getEnvironment(project),
ProjectUtils.getSourceFiles(javaProject.getProject())).analysisResult
}
cachedAnalysisResults.putIfAbsent(project, analysisResult) ?: analysisResult
}
}
public @Synchronized fun getAnalysisResultIfCached(project: IProject): AnalysisResult? {
return cachedAnalysisResults.get(project)
}
override fun resourceChanged(event: IResourceChangeEvent) {
when (event.getType()) {
IResourceChangeEvent.PRE_DELETE,
IResourceChangeEvent.PRE_CLOSE,
IResourceChangeEvent.PRE_BUILD -> event.getDelta()?.accept { delta ->
val resource = delta.getResource()
if (resource is IFile) {
val javaProject = JavaCore.create(resource.getProject())
if (KotlinPsiManager.isKotlinSourceFile(resource, javaProject)) {
cachedAnalysisResults.remove(resource.getProject())
}
return@accept false
}
true
}
}
}
} | apache-2.0 | f9ae0534ed160504d4c2701fbf86969b | 40.302632 | 93 | 0.660612 | 5.318644 | false | false | false | false |
edx/edx-app-android | OpenEdXMobile/src/main/java/org/edx/mobile/viewModel/CourseDateViewModel.kt | 1 | 7999 | package org.edx.mobile.viewModel
import android.content.Context
import android.os.SystemClock
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.ResponseBody
import org.edx.mobile.exception.ErrorMessage
import org.edx.mobile.http.HttpStatusException
import org.edx.mobile.http.constants.ApiConstants
import org.edx.mobile.http.model.NetworkResponseCallback
import org.edx.mobile.http.model.Result
import org.edx.mobile.model.course.CourseBannerInfoModel
import org.edx.mobile.model.course.CourseDates
import org.edx.mobile.model.course.ResetCourseDates
import org.edx.mobile.repositorie.CourseDatesRepository
import org.edx.mobile.util.CalendarUtils
import retrofit2.Response
import java.util.*
class CourseDateViewModel(
private val repository: CourseDatesRepository = CourseDatesRepository.getInstance()
) : ViewModel() {
private val _syncLoader = MutableLiveData<Boolean>()
val syncLoader: LiveData<Boolean>
get() = _syncLoader
private val _showLoader = MutableLiveData<Boolean>()
val showLoader: LiveData<Boolean>
get() = _showLoader
private val _swipeRefresh = MutableLiveData<Boolean>()
val swipeRefresh: LiveData<Boolean>
get() = _swipeRefresh
private val _courseDates = MutableLiveData<CourseDates>()
val courseDates: LiveData<CourseDates>
get() = _courseDates
private val _bannerInfo = MutableLiveData<CourseBannerInfoModel>()
val bannerInfo: LiveData<CourseBannerInfoModel>
get() = _bannerInfo
private val _resetCourseDates = MutableLiveData<ResetCourseDates>()
val resetCourseDates: LiveData<ResetCourseDates>
get() = _resetCourseDates
private val _errorMessage = MutableLiveData<ErrorMessage>()
val errorMessage: LiveData<ErrorMessage>
get() = _errorMessage
private var syncingCalendarTime: Long = 0L
var areEventsUpdated: Boolean = false
fun getSyncingCalendarTime(): Long = syncingCalendarTime
fun resetSyncingCalendarTime() {
syncingCalendarTime = 0L
}
fun addOrUpdateEventsInCalendar(
context: Context,
calendarId: Long,
courseId: String,
courseName: String,
isDeepLinkEnabled: Boolean,
updatedEvent: Boolean
) {
resetSyncingCalendarTime()
val syncingCalendarStartTime: Long = Calendar.getInstance().timeInMillis
areEventsUpdated = updatedEvent
_syncLoader.value = true
viewModelScope.launch(Dispatchers.IO) {
courseDates.value?.let { courseDates ->
courseDates.courseDateBlocks?.forEach { courseDateBlock ->
CalendarUtils.addEventsIntoCalendar(
context = context,
calendarId = calendarId,
courseId = courseId,
courseName = courseName,
courseDateBlock = courseDateBlock,
isDeeplinkEnabled = isDeepLinkEnabled
)
}
syncingCalendarTime = Calendar.getInstance().timeInMillis - syncingCalendarStartTime
if (courseDates.courseDateBlocks?.size == 0) {
syncingCalendarTime = 0
} else if (syncingCalendarTime < 1000) {
// Add 1 sec delay to dismiss the dialog to avoid flickering
// if the event creation time is less then 1 sec
SystemClock.sleep(1000 - syncingCalendarTime)
}
} ?: run { syncingCalendarTime = 0 }
_syncLoader.postValue(false)
}
}
fun fetchCourseDates(courseID: String, forceRefresh: Boolean, showLoader: Boolean = false, isSwipeRefresh: Boolean = false) {
_errorMessage.value = null
_swipeRefresh.value = isSwipeRefresh
_showLoader.value = showLoader
repository.getCourseDates(
courseId = courseID,
forceRefresh = forceRefresh,
callback = object : NetworkResponseCallback<CourseDates> {
override fun onSuccess(result: Result.Success<CourseDates>) {
if (result.isSuccessful && result.data != null) {
_courseDates.postValue(result.data)
fetchCourseDatesBannerInfo(courseID, true)
} else {
setError(ErrorMessage.COURSE_DATES_CODE, result.code, result.message)
}
_showLoader.postValue(false)
_swipeRefresh.postValue(false)
}
override fun onError(error: Result.Error) {
_showLoader.postValue(false)
_errorMessage.postValue(ErrorMessage(ErrorMessage.COURSE_DATES_CODE, error.throwable))
_swipeRefresh.postValue(false)
}
}
)
}
fun fetchCourseDatesBannerInfo(courseID: String, showLoader: Boolean = false) {
_errorMessage.value = null
_showLoader.value = showLoader
repository.getCourseBannerInfo(
courseId = courseID,
callback = object : NetworkResponseCallback<CourseBannerInfoModel> {
override fun onSuccess(result: Result.Success<CourseBannerInfoModel>) {
if (result.isSuccessful && result.data != null) {
_bannerInfo.postValue(result.data)
} else {
setError(ErrorMessage.BANNER_INFO_CODE, result.code, result.message)
}
_showLoader.postValue(false)
_swipeRefresh.postValue(false)
}
override fun onError(error: Result.Error) {
_showLoader.postValue(false)
_errorMessage.postValue(ErrorMessage(ErrorMessage.BANNER_INFO_CODE, error.throwable))
_swipeRefresh.postValue(false)
}
}
)
}
fun resetCourseDatesBanner(courseID: String) {
_errorMessage.value = null
_showLoader.value = true
val courseBody = HashMap<String, String>()
courseBody[ApiConstants.COURSE_KEY] = courseID
repository.resetCourseDates(
body = courseBody,
callback = object : NetworkResponseCallback<ResetCourseDates> {
override fun onSuccess(result: Result.Success<ResetCourseDates>) {
if (result.isSuccessful && result.data != null) {
_resetCourseDates.postValue(result.data)
fetchCourseDates(courseID, forceRefresh = true, showLoader = false, isSwipeRefresh = false)
} else {
setError(ErrorMessage.COURSE_RESET_DATES_CODE, result.code, result.message)
}
_showLoader.postValue(false)
_swipeRefresh.postValue(false)
}
override fun onError(error: Result.Error) {
_showLoader.postValue(false)
_errorMessage.postValue(ErrorMessage(ErrorMessage.COURSE_RESET_DATES_CODE, error.throwable))
_swipeRefresh.postValue(false)
}
}
)
}
fun setError(errorCode: Int, httpStatusCode: Int, msg: String) {
_errorMessage.value = ErrorMessage(errorCode, HttpStatusException(Response.error<Any>(httpStatusCode,
ResponseBody.create(MediaType.parse("text/plain"), msg))))
}
}
| apache-2.0 | b67c71113f2b8b111f6efe33ad249563 | 41.322751 | 129 | 0.6032 | 5.430414 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.