repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
tasks/tasks | app/src/main/java/org/tasks/location/AndroidLocationManager.kt | 1 | 1469 | package org.tasks.location
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Context
import android.location.Location
import dagger.hilt.android.qualifiers.ApplicationContext
import timber.log.Timber
import javax.inject.Inject
class AndroidLocationManager @Inject constructor(
@ApplicationContext private val context: Context,
) : LocationManager {
private val locationManager
get() = context.getSystemService(android.location.LocationManager::class.java)
override val lastKnownLocations: List<Location>
get() = locationManager.allProviders.mapNotNull {
locationManager.getLastKnownLocationOrNull(it)
}
@SuppressLint("MissingPermission")
override fun addProximityAlert(
latitude: Double,
longitude: Double,
radius: Float,
intent: PendingIntent
) = locationManager.addProximityAlert(latitude, longitude, radius, -1, intent)
override fun removeProximityAlert(intent: PendingIntent) =
locationManager.removeProximityAlert(intent)
companion object {
@SuppressLint("MissingPermission")
private fun android.location.LocationManager.getLastKnownLocationOrNull(provider: String) =
try {
getLastKnownLocation(provider)
} catch (e: Exception) {
Timber.e(e)
null
}
}
} | gpl-3.0 |
natanieljr/droidmate | project/pcComponents/core/src/main/kotlin/org/droidmate/tools/LogcatMonitor.kt | 1 | 2730 | package org.droidmate.tools
import kotlinx.coroutines.*
import org.droidmate.configuration.ConfigurationWrapper
import org.droidmate.device.android_sdk.IAdbWrapper
import org.droidmate.logging.Markers
import org.droidmate.misc.SysCmdInterruptableExecutor
import java.nio.file.Files
import java.nio.file.Path
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.CoroutineContext
class LogcatMonitor(private val cfg: ConfigurationWrapper,
private val adbWrapper: IAdbWrapper): CoroutineScope {
private val log: Logger by lazy { LoggerFactory.getLogger(LogcatMonitor::class.java) }
override val coroutineContext: CoroutineContext
= CoroutineName("LogcatMonitor") + Job() + Dispatchers.Default
// Coverage monitor variables
private val sysCmdExecutor = SysCmdInterruptableExecutor()
private var running: AtomicBoolean = AtomicBoolean(true)
/**
* Starts the monitoring job.
*/
fun start() {
launch(start = CoroutineStart.DEFAULT) { run() }
}
/**
* Starts monitoring logcat.
*/
private suspend fun run() {
log.info(Markers.appHealth, "Start monitoring logcat. Output to ${getLogfilePath().toAbsolutePath()}")
try {
withContext(Dispatchers.IO) {
Files.createDirectories(getLogfilePath().parent)
while (running.get()) {
monitorLogcat()
delay(5)
}
}
} catch (ex: Exception) {
ex.printStackTrace()
}
}
/**
* Starts executing a command in order to monitor the logcat if the previous command is already terminated.
*/
private fun monitorLogcat() {
val path = getLogfilePath()
val output = adbWrapper.executeCommand(sysCmdExecutor, cfg.deviceSerialNumber, "", "Logcat logfile monitor",
"logcat", "-v", "time")
// Append the logcat content to the logfile
log.info("Writing logcat output into $path")
val file = path.toFile()
file.appendBytes(output.toByteArray())
}
/**
* Returns the logfile name in which the logcat content is written into.
*/
private fun getLogfilePath(): Path {
return cfg.droidmateOutputDirPath.resolve("logcat.log")
}
/**
* Notifies the logcat monitor and [sysCmdExecutor] to finish.
*/
fun terminate() {
running.set(false)
sysCmdExecutor.stopCurrentExecutionIfExisting()
log.info("Logcat monitor thread destroyed")
runBlocking { if(!coroutineContext.isActive) coroutineContext[Job]?.cancelAndJoin() }
}
} | gpl-3.0 |
arturbosch/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/internal/DefaultRuleSetProvider.kt | 2 | 373 | package io.gitlab.arturbosch.detekt.api.internal
import io.gitlab.arturbosch.detekt.api.RuleSetProvider
/**
* Interface which marks sub-classes as provided by detekt via the rules sub-module.
*
* Allows to implement "--disable-default-rulesets" effectively without the need
* to manage a list of rule set names.
*/
interface DefaultRuleSetProvider : RuleSetProvider
| apache-2.0 |
ledao/chatbot | src/main/kotlin/com/davezhao/nlp/Common.kt | 1 | 76 | package com.davezhao.nlp
data class Term(var word: String, var pos: String) | gpl-3.0 |
jonalmeida/focus-android | app/src/main/java/org/mozilla/focus/activity/InstallFirefoxActivity.kt | 2 | 2607 | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Bundle
import android.webkit.WebView
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.utils.AppConstants
import org.mozilla.focus.utils.Browsers
/**
* Helper activity that will open the Google Play store by following a redirect URL.
*/
class InstallFirefoxActivity : Activity() {
private var webView: WebView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
webView = WebView(this)
setContentView(webView)
webView!!.loadUrl(REDIRECT_URL)
}
override fun onPause() {
super.onPause()
if (webView != null) {
webView!!.onPause()
}
finish()
}
override fun onDestroy() {
super.onDestroy()
if (webView != null) {
webView!!.destroy()
}
}
companion object {
private const val REDIRECT_URL = "https://app.adjust.com/gs1ao4"
fun resolveAppStore(context: Context): ActivityInfo? {
val resolveInfo = context.packageManager.resolveActivity(createStoreIntent(), 0)
if (resolveInfo?.activityInfo == null) {
return null
}
return if (!resolveInfo.activityInfo.exported) {
// We are not allowed to launch this activity.
null
} else resolveInfo.activityInfo
}
private fun createStoreIntent(): Intent {
return Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + Browsers.KnownBrowser.FIREFOX.packageName))
}
fun open(context: Context) {
if (AppConstants.isKlarBuild) {
// Redirect to Google Play directly
context.startActivity(createStoreIntent())
} else {
// Start this activity to load the redirect URL in a WebView.
val intent = Intent(context, InstallFirefoxActivity::class.java)
context.startActivity(intent)
}
TelemetryWrapper.installFirefoxEvent()
}
}
}
| mpl-2.0 |
soniccat/android-taskmanager | authorization/src/main/java/com/example/alexeyglushkov/authorization/Auth/AccountStore.kt | 1 | 625 | package com.example.alexeyglushkov.authorization.Auth
/**
* Created by alexeyglushkov on 31.10.15.
*/
interface AccountStore {
@Throws(Exception::class)
fun putAccount(account: Account)
@Throws(Exception::class)
fun getAccount(key: Int): Account?
val accountCount: Int
val maxAccountId: Int
val accounts: List<Account>
fun getAccounts(serviceType: Int): List<Account>
@Throws(Exception::class)
fun removeAccount(id: Int)
@Throws(Exception::class)
fun removeAll()
// TODO: provide async loader
val isLoaded: Boolean
@Throws(Exception::class)
fun load()
} | mit |
Kotlin/kotlinx-cli | core/nativeMain/src/Utils.kt | 1 | 268 | /*
* Copyright 2010-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 kotlinx.cli
internal actual fun exitProcess(status: Int): Nothing {
kotlin.system.exitProcess(status)
} | apache-2.0 |
nemerosa/ontrack | ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/MetaInfoPropertyType.kt | 1 | 6134 | package net.nemerosa.ontrack.extension.general
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.extension.support.AbstractPropertyType
import net.nemerosa.ontrack.model.form.Form
import net.nemerosa.ontrack.model.form.MultiForm
import net.nemerosa.ontrack.model.form.Text
import net.nemerosa.ontrack.model.security.ProjectConfig
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.structure.ProjectEntity
import net.nemerosa.ontrack.model.structure.ProjectEntityType
import net.nemerosa.ontrack.model.structure.PropertySearchArguments
import net.nemerosa.ontrack.model.structure.SearchIndexService
import org.apache.commons.lang3.StringUtils
import org.springframework.stereotype.Component
import java.util.*
import java.util.function.Function
@Component
class MetaInfoPropertyType(
extensionFeature: GeneralExtensionFeature,
private val searchIndexService: SearchIndexService,
private val metaInfoSearchExtension: MetaInfoSearchExtension
) : AbstractPropertyType<MetaInfoProperty>(extensionFeature) {
override fun getName(): String = "Meta information"
override fun getDescription(): String = "List of meta information properties"
override fun getSupportedEntityTypes(): Set<ProjectEntityType> = EnumSet.allOf(ProjectEntityType::class.java)
override fun canEdit(entity: ProjectEntity, securityService: SecurityService): Boolean {
return securityService.isProjectFunctionGranted(entity, ProjectConfig::class.java)
}
override fun canView(entity: ProjectEntity, securityService: SecurityService): Boolean = true
override fun onPropertyChanged(entity: ProjectEntity, value: MetaInfoProperty) {
searchIndexService.createSearchIndex(metaInfoSearchExtension, MetaInfoSearchItem(entity, value))
}
override fun onPropertyDeleted(entity: ProjectEntity, oldValue: MetaInfoProperty) {
searchIndexService.deleteSearchIndex(metaInfoSearchExtension, MetaInfoSearchItem(entity, oldValue).id)
}
override fun getEditionForm(entity: ProjectEntity, value: MetaInfoProperty?): Form = Form.create()
.with(
MultiForm.of(
"items",
Form.create()
.name()
.with(
Text.of("value").label("Value")
)
.with(
Text.of("link").label("Link").optional()
)
.with(
Text.of("category").label("Category").optional()
)
)
.label("Items")
.value(value?.items ?: emptyList<Any>())
)
override fun fromClient(node: JsonNode): MetaInfoProperty {
return fromStorage(node)
}
override fun fromStorage(node: JsonNode): MetaInfoProperty {
return parse(node, MetaInfoProperty::class.java)
}
override fun containsValue(property: MetaInfoProperty, propertyValue: String): Boolean {
val pos = StringUtils.indexOf(propertyValue, ":")
return if (pos > 0) {
val value = StringUtils.substringAfter(propertyValue, ":")
val name = StringUtils.substringBefore(propertyValue, ":")
property.matchNameValue(name, value)
} else {
false
}
}
override fun replaceValue(value: MetaInfoProperty, replacementFunction: Function<String, String>): MetaInfoProperty {
return MetaInfoProperty(
value.items
.map { item ->
MetaInfoPropertyItem(
item.name,
item.value?.apply { replacementFunction.apply(this) },
item.link?.apply { replacementFunction.apply(this) },
item.category?.apply { replacementFunction.apply(this) }
)
}
)
}
override fun getSearchArguments(token: String): PropertySearchArguments? {
val name: String?
val value: String?
if (token.indexOf(":") >= 1) {
name = token.substringBefore(":").trim()
value = token.substringAfter(":").trimStart()
} else {
name = null
value = token
}
return if (name.isNullOrBlank()) {
if (value.isNullOrBlank()) {
// Empty
null
} else {
// Value only
PropertySearchArguments(
jsonContext = "jsonb_array_elements(pp.json->'items') as item",
jsonCriteria = "item->>'value' ilike :value",
criteriaParams = mapOf(
"value" to value.toValuePattern()
)
)
}
} else if (value.isNullOrBlank()) {
// Name only
PropertySearchArguments(
jsonContext = "jsonb_array_elements(pp.json->'items') as item",
jsonCriteria = "item->>'name' = :name",
criteriaParams = mapOf(
"name" to name
)
)
} else {
// Name & value
PropertySearchArguments(
jsonContext = "jsonb_array_elements(pp.json->'items') as item",
jsonCriteria = "item->>'name' = :name and item->>'value' ilike :value",
criteriaParams = mapOf(
"name" to name,
"value" to value.toValuePattern()
)
)
}
}
private fun String.toValuePattern(): String {
return this.replace("*", "%")
}
}
| mit |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/examples/kotlin/TrainTest.kt | 1 | 5260 | /* The MIT License (MIT)
Copyright (c) 2016 Tom Needham
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.thomas.needham.neurophidea.examples.kotlin
import org.neuroph.core.NeuralNetwork
import org.neuroph.core.learning.SupervisedTrainingElement
import org.neuroph.core.learning.TrainingSet
import org.neuroph.nnet.MultiLayerPerceptron
import org.neuroph.nnet.learning.BackPropagation
import org.neuroph.util.TransferFunctionType
import java.io.*
import java.util.*
object TrainTest {
@JvmStatic
var inputSize = 8
@JvmStatic
var outputSize = 1
@JvmStatic
var network: NeuralNetwork? = null
@JvmStatic
var trainingSet: TrainingSet<SupervisedTrainingElement>? = null
@JvmStatic
var testingSet: TrainingSet<SupervisedTrainingElement>? = null
@JvmStatic
var layers = arrayOf(8, 8, 1)
@JvmStatic
fun loadNetwork() {
network = NeuralNetwork.load("D:/GitHub/Neuroph-Intellij-Plugin/TrainTest.nnet")
}
@JvmStatic
fun trainNetwork() {
val list = ArrayList<Int>()
for (layer in layers) {
list.add(layer)
}
val network = MultiLayerPerceptron(list, TransferFunctionType.SIGMOID);
trainingSet = TrainingSet<SupervisedTrainingElement>(inputSize, outputSize)
trainingSet = TrainingSet.createFromFile("D:/GitHub/NeuralNetworkTest/Classroom Occupation Data.csv", inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>?
val learningRule = BackPropagation()
network.learningRule = learningRule
network.learn(trainingSet)
network.save("D:/GitHub/Neuroph-Intellij-Plugin/TrainTest.nnet")
}
@JvmStatic
fun testNetwork() {
var input = ""
val fromKeyboard = BufferedReader(InputStreamReader(System.`in`))
val testValues = ArrayList<Double>()
var testValuesDouble: DoubleArray
do {
try {
println("Enter test values or \"\": ")
input = fromKeyboard.readLine()
if (input == "") {
break
}
input = input.replace(" ", "")
val stringVals = input.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
testValues.clear()
for (`val` in stringVals) {
testValues.add(java.lang.Double.parseDouble(`val`))
}
} catch (ioe: IOException) {
ioe.printStackTrace(System.err)
} catch (nfe: NumberFormatException) {
nfe.printStackTrace(System.err)
}
testValuesDouble = DoubleArray(testValues.size)
for (t in testValuesDouble.indices) {
testValuesDouble[t] = testValues[t].toDouble()
}
network?.setInput(*testValuesDouble)
network?.calculate()
} while (input != "")
}
@JvmStatic
fun testNetworkAuto(setPath: String) {
var total: Double = 0.0
val list = ArrayList<Int>()
val outputLine = ArrayList<String>()
for (layer in layers) {
list.add(layer)
}
testingSet = TrainingSet.createFromFile(setPath, inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>?
val count: Int = testingSet?.elements()?.size!!
var averageDeviance = 0.0
var resultString = ""
try {
val file = File("Results " + setPath)
val fw = FileWriter(file)
val bw = BufferedWriter(fw)
for (i in 0..testingSet?.elements()?.size!! - 1) {
val expected: Double
val calculated: Double
network?.setInput(*testingSet?.elementAt(i)!!.input)
network?.calculate()
calculated = network?.output!![0]
expected = testingSet?.elementAt(i)?.idealArray!![0]
println("Calculated Output: " + calculated)
println("Expected Output: " + expected)
println("Deviance: " + (calculated - expected))
averageDeviance += Math.abs(Math.abs(calculated) - Math.abs(expected))
total += network?.output!![0]
resultString = ""
for (cols in 0..testingSet?.elementAt(i)?.inputArray?.size!! - 1) {
resultString += testingSet?.elementAt(i)?.inputArray!![cols].toString() + ", "
}
for (t in 0..network?.output!!.size - 1) {
resultString += network?.output!![t].toString() + ", "
}
resultString = resultString.substring(0, resultString.length - 2)
resultString += ""
bw.write(resultString)
bw.flush()
println()
println("Average: " + (total / count).toString())
println("Average Deviance % : " + (averageDeviance / count * 100).toString())
bw.flush()
bw.close()
}
} catch (ex: IOException) {
ex.printStackTrace()
}
}
}
| mit |
REBOOTERS/AndroidAnimationExercise | imitate/src/main/java/com/engineer/imitate/util/Throttle.kt | 1 | 701 | package com.engineer.imitate.util
import android.os.SystemClock
import java.util.concurrent.TimeUnit
class Throttle(
skipDuration: Long,
timeUnit: TimeUnit
) {
private val delayMilliseconds: Long
private var oldTime = 0L
init {
if (skipDuration < 0) {
delayMilliseconds = 0
} else {
delayMilliseconds = timeUnit.toMillis(skipDuration)
}
}
fun needSkip(): Boolean {
val nowTime = SystemClock.elapsedRealtime()
val intervalTime = nowTime - oldTime
if (oldTime == 0L || intervalTime >= delayMilliseconds) {
oldTime = nowTime
return false
}
return true
}
} | apache-2.0 |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/view/FilteredContainer.kt | 1 | 335 | package com.soywiz.korge.view
import com.soywiz.korge.render.*
class FilteredContainer : Container(), View.Reference {
override fun renderInternal(ctx: RenderContext) {
val bounds = getLocalBoundsOptimizedAnchored()
ctx.renderToTexture(bounds.width.toInt(), bounds.height.toInt(), {
super.renderInternal(ctx)
}) {
}
}
}
| apache-2.0 |
ojacquemart/spring-kotlin-euro-bets | src/main/kotlin/org/ojacquemart/eurobets/firebase/config/FirebaseSettings.kt | 2 | 420 | package org.ojacquemart.eurobets.firebase.config
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.stereotype.Component
@Component
@ConfigurationProperties(prefix = "firebase")
open class FirebaseSettings {
var app: String = ""
var secret = ""
override fun toString(): String {
return "FirebaseProperties(app='$app',secret='$secret')"
}
}
| unlicense |
soywiz/korge | korge/src/jvmTest/kotlin/com/soywiz/korge/spike/Spike1.kt | 1 | 279 | package com.soywiz.korge.spike
import com.soywiz.korge.*
import com.soywiz.korge.view.*
import com.soywiz.korim.color.*
object Spike1 {
@JvmStatic suspend fun main(args: Array<String>) {
Korge {
solidRect(100, 100, Colors.RED) {
x = 100.0
y = 100.0
}
}
}
}
| apache-2.0 |
samtstern/quickstart-android | mlkit-translate/app/src/main/java/com/google/firebase/samples/apps/mlkit/translate/EntryChoiceActivity.kt | 1 | 1493 | /*
* Copyright 2019 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.google.firebase.samples.apps.mlkit.translate
import android.content.Intent
import com.firebase.example.internal.BaseEntryChoiceActivity
import com.firebase.example.internal.Choice
class EntryChoiceActivity : BaseEntryChoiceActivity() {
override fun getChoices(): List<Choice> {
return listOf(
Choice(
"Java",
"Run the Firebase ML Kit Smart Reply quickstart written in Java.",
Intent(this, com.google.firebase.samples.apps.mlkit.translate.java.MainActivity::class.java)),
Choice(
"Kotlin",
"Run the Firebase ML Kit Smart Reply quickstart written in Kotlin.",
Intent(this, com.google.firebase.samples.apps.mlkit.translate.kotlin.MainActivity::class.java))
)
}
}
| apache-2.0 |
Orchextra/orchextra-android-sdk | core/src/main/java/com/gigigo/orchextra/core/utils/LogUtils.kt | 1 | 2973 | /*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.core.utils
import android.util.Log
import com.gigigo.orchextra.core.Orchextra
object LogUtils {
private val MAX_LOG_TAG_LENGTH = 23
var LOG_LEVEL = Log.DEBUG
var fileLogging: FileLogging? = null
fun makeLogTag(str: String): String {
return if (str.length > MAX_LOG_TAG_LENGTH) {
str.substring(0, MAX_LOG_TAG_LENGTH - 1)
} else {
str
}
}
/**
* Don't use this when obfuscating class names!
*/
fun makeLogTag(cls: Class<*>): String = makeLogTag(cls.simpleName)
fun LOGD(tag: String, message: String) {
if (Orchextra.isDebuggable()) {
if (LOG_LEVEL <= Log.DEBUG) {
Log.d(tag, message)
fileLogging?.log(Log.DEBUG, tag, message)
}
}
}
fun LOGD(tag: String, message: String, cause: Throwable) {
if (Orchextra.isDebuggable()) {
if (LOG_LEVEL <= Log.DEBUG) {
Log.d(tag, message, cause)
fileLogging?.log(Log.DEBUG, tag, message, cause)
}
}
}
fun LOGV(tag: String, message: String) {
if (Orchextra.isDebuggable()) {
if (LOG_LEVEL <= Log.VERBOSE) {
Log.v(tag, message)
fileLogging?.log(Log.VERBOSE, tag, message)
}
}
}
fun LOGV(tag: String, message: String, cause: Throwable) {
if (Orchextra.isDebuggable()) {
if (LOG_LEVEL <= Log.VERBOSE) {
Log.v(tag, message, cause)
fileLogging?.log(Log.VERBOSE, tag, message)
}
}
}
fun LOGI(tag: String, message: String) {
if (Orchextra.isDebuggable()) {
Log.i(tag, message)
fileLogging?.log(Log.INFO, tag, message)
}
}
fun LOGI(tag: String, message: String, cause: Throwable) {
if (Orchextra.isDebuggable()) {
Log.i(tag, message, cause)
fileLogging?.log(Log.INFO, tag, message)
}
}
fun LOGW(tag: String, message: String) {
Log.w(tag, message)
fileLogging?.log(Log.WARN, tag, message)
}
fun LOGW(tag: String, message: String, cause: Throwable) {
Log.w(tag, message, cause)
fileLogging?.log(Log.WARN, tag, message, cause)
}
fun LOGE(tag: String, message: String) {
Log.e(tag, message)
fileLogging?.log(Log.ERROR, tag, message)
}
fun LOGE(tag: String, message: String, cause: Throwable) {
Log.e(tag, message, cause)
fileLogging?.log(Log.ERROR, tag, message, cause)
}
} | apache-2.0 |
soywiz/korge | korge/src/commonTest/kotlin/com/soywiz/korge/view/NinePatchTest.kt | 1 | 3891 | package com.soywiz.korge.view
import com.soywiz.korge.render.*
import com.soywiz.korge.tests.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korio.file.std.*
import kotlin.test.*
class NinePatchTest : ViewsForTesting() {
@Test
fun testNinePatch() = viewsTest {
val vertices = arrayListOf<List<VertexInfo>>()
val ninePatch = resourcesVfs["npatch/9patch.9.png"].readNinePatch()
ninePatch(ninePatch, 450.0, 600.0) {
position(0, 0)
}
val log = testRenderContext { ctx ->
ctx.batch.beforeFlush { vertices.add(it.readVertices()) }
render(ctx)
}
assertEquals(1, vertices.size) // 1 batch
val batch = vertices[0]
assertEquals(36, batch.size) // 36 vertices
assertEquals(
"""
[(0,0), (1, 1)]
[(49,0), (50, 1)]
[(49,47), (50, 48)]
[(0,47), (1, 48)]
[(49,0), (50, 1)]
[(400,0), (78, 1)]
[(400,47), (78, 48)]
[(49,47), (50, 48)]
[(400,0), (78, 1)]
[(450,0), (128, 1)]
[(450,47), (128, 48)]
[(400,47), (78, 48)]
[(0,47), (1, 48)]
[(49,47), (50, 48)]
[(49,553), (50, 57)]
[(0,553), (1, 57)]
[(49,47), (50, 48)]
[(400,47), (78, 48)]
[(400,553), (78, 57)]
[(49,553), (50, 57)]
[(400,47), (78, 48)]
[(450,47), (128, 48)]
[(450,553), (128, 57)]
[(400,553), (78, 57)]
[(0,553), (1, 57)]
[(49,553), (50, 57)]
[(49,600), (50, 104)]
[(0,600), (1, 104)]
[(49,553), (50, 57)]
[(400,553), (78, 57)]
[(400,600), (78, 104)]
[(49,600), (50, 104)]
[(400,553), (78, 57)]
[(450,553), (128, 57)]
[(450,600), (128, 104)]
[(400,600), (78, 104)]
""".trimIndent(),
batch.joinToString("\n") { it.toStringXYUV() }
)
//assertEquals("--", log.getLogAsString())
}
@Test
fun testNinePatchSmaller() = viewsTest {
val ninePatch = resourcesVfs["npatch/9patch.9.png"].readNinePatch()
fun computeVertices(ninePatch: NinePatchBitmap32, width: Double, height: Double): List<List<VertexInfo>> {
val vertices = arrayListOf<List<VertexInfo>>()
stage.removeChildren()
testRenderContext { ctx ->
val view = ninePatch(ninePatch, width, height) {
position(0, 0)
}
ctx.batch.beforeFlush { vertices.add(it.readVertices()) }
view.render(ctx)
}
return vertices
}
fun computeInterestingPoints(width: Number, height: Number): String {
val batch = computeVertices(ninePatch, width.toDouble(), height.toDouble())[0]
return listOf(batch[0], batch[2], batch[32], batch[34]).joinToString(", ") { it.toStringXY() }
}
assertEquals(
"""
[0,0], [49,47], [400,553], [450,600]
[0,0], [15,14], [435,18], [450,32]
[0,0], [12,11], [20,589], [32,600]
[0,0], [12,11], [20,21], [32,32]
""".trimIndent(),
listOf(
computeInterestingPoints(450, 600),
computeInterestingPoints(450, 32),
computeInterestingPoints(32, 600),
computeInterestingPoints(32, 32)
).joinToString("\n")
)
}
}
//
// +-+--------+-+
// +-+--------+-+
// | | | |
// | | | |
// +-+--------+-+
// +-+--------+-+
| apache-2.0 |
permissions-dispatcher/PermissionsDispatcher | lint/src/test/java/permissions/dispatcher/CallNeedsPermissionDetectorTest.kt | 2 | 5184 | package permissions.dispatcher
import com.android.tools.lint.checks.infrastructure.TestFiles.java
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import org.intellij.lang.annotations.Language
import org.junit.Test
import permissions.dispatcher.Utils.onNeedsPermission
import permissions.dispatcher.Utils.runtimePermission
class CallNeedsPermissionDetectorTest {
@Test
@Throws(Exception::class)
fun callNeedsPermissionMethod() {
@Language("JAVA") val foo = """
package com.example;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;
@RuntimePermissions
public class Foo {
@NeedsPermission("Test")
void fooBar() {
}
public void hoge() {
fooBar();
}
}
""".trimMargin()
val expectedText = """
|src/com/example/Foo.java:13: Error: Trying to access permission-protected method directly [CallNeedsPermission]
| fooBar();
| ~~~~~~~~
|1 errors, 0 warnings
""".trimMargin()
lint()
.files(
java(runtimePermission),
java(onNeedsPermission),
java(foo))
.issues(CallNeedsPermissionDetector.ISSUE)
.run()
.expect(expectedText)
.expectErrorCount(1)
.expectWarningCount(0)
}
@Test
@Throws(Exception::class)
fun callNeedsPermissionMethodNoError() {
@Language("JAVA") val foo = """
package com.example;
public class Foo {
void someMethod() {
Baz baz = new Baz();
baz.noFooBar();
}
}
""".trimMargin()
@Language("JAVA") val baz = """
package com.example;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;
@RuntimePermissions
public class Baz {
@NeedsPermission("Test")
void fooBar() {
}
void noFooBar() {
}
}
""".trimMargin()
lint()
.files(
java(onNeedsPermission),
java(foo),
java(baz))
.issues(CallNeedsPermissionDetector.ISSUE)
.run()
.expectClean()
}
@Test
@Throws(Exception::class)
fun issues502() {
@Language("JAVA") val foo = """
package com.example;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;
@RuntimePermissions
public class Foo extends AppCompatActivity {
@NeedsPermission({Manifest.permission.READ_SMS})
void requestOTP() {
new PhoneVerificationInputFragment().requestOTP();
}
}
class FooFragment extends Fragment {
public void resendOTP() {
requestOTP();
}
private void requestOTP() {
}
}
""".trimMargin()
lint()
.files(
java(runtimePermission),
java(onNeedsPermission),
java(foo))
.issues(CallNeedsPermissionDetector.ISSUE)
.run()
.expectClean()
}
@Test
fun `same name methods in different class(issue602)`() {
@Language("java") val foo = """
package com.example;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;
@RuntimePermissions
public class FirstActivity extends AppCompatActivity {
@NeedsPermission({Manifest.permission.READ_SMS})
void someFun() {
}
}
@RuntimePermissions
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
someFun();
}
void someFun() {
}
@NeedsPermission({Manifest.permission.READ_SMS})
void otherFun() {
}
}
""".trimMargin()
lint()
.files(java(runtimePermission), java(onNeedsPermission), java(foo))
.issues(CallNeedsPermissionDetector.ISSUE)
.run()
.expectClean()
}
}
| apache-2.0 |
Jire/Abendigo | src/main/kotlin/org/abendigo/util/Randoms.kt | 2 | 291 | package org.abendigo.util
import java.util.concurrent.ThreadLocalRandom.current
fun random(min: Int, max: Int) = (min + current().nextDouble() * (max - min)).toInt()
fun random(max: Int) = random(0, max)
fun randomFloat(min: Float, max: Float) = min + current().nextFloat() * (max - min) | gpl-3.0 |
shlusiak/Freebloks-Android | game/src/test/java/de/saschahlusiak/freebloks/network/message/MessageRevokePlayerTest.kt | 1 | 736 | package de.saschahlusiak.freebloks.network.message
import de.saschahlusiak.freebloks.network.*
import de.saschahlusiak.freebloks.utils.hexString
import de.saschahlusiak.freebloks.utils.ubyteArrayOf
import org.junit.Assert
import org.junit.Test
import java.nio.ByteBuffer
class MessageRevokePlayerTest {
@Test
fun test_marshall() {
val bytes = ubyteArrayOf(0x09, 0x00, 0x06, 0x0d, 0xec, 0x03)
val msg = MessageRevokePlayer(3)
val newBytes = msg.toByteArray()
println(newBytes.hexString())
Assert.assertArrayEquals(bytes, newBytes)
val msg2 = Message.from(bytes) as MessageRevokePlayer
Assert.assertEquals(msg, msg2)
Assert.assertEquals(3, msg2.player)
}
}
| gpl-2.0 |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/message/MessageNewConversationFragment.kt | 1 | 16429 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment.message
import android.accounts.AccountManager
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.os.Bundle
import android.support.annotation.WorkerThread
import android.support.v4.app.LoaderManager.LoaderCallbacks
import android.support.v4.content.Loader
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ReplacementSpan
import android.view.*
import kotlinx.android.synthetic.main.fragment_messages_conversation_new.*
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.*
import org.mariotaku.library.objectcursor.ObjectCursor
import org.mariotaku.sqliteqb.library.Expression
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.adapter.SelectableUsersAdapter
import de.vanita5.twittnuker.constant.IntentConstants.*
import de.vanita5.twittnuker.constant.nameFirstKey
import de.vanita5.twittnuker.extension.model.isOfficial
import de.vanita5.twittnuker.extension.queryOne
import de.vanita5.twittnuker.extension.text.appendCompat
import de.vanita5.twittnuker.fragment.BaseFragment
import de.vanita5.twittnuker.loader.CacheUserSearchLoader
import de.vanita5.twittnuker.model.ParcelableMessageConversation
import de.vanita5.twittnuker.model.ParcelableMessageConversation.ConversationType
import de.vanita5.twittnuker.model.ParcelableUser
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.provider.TwidereDataStore.Messages.Conversations
import de.vanita5.twittnuker.task.twitter.message.SendMessageTask
import de.vanita5.twittnuker.text.MarkForDeleteSpan
import de.vanita5.twittnuker.util.IntentUtils
import de.vanita5.twittnuker.util.view.SimpleTextWatcher
import java.lang.ref.WeakReference
class MessageNewConversationFragment : BaseFragment(), LoaderCallbacks<List<ParcelableUser>?> {
private val accountKey by lazy { arguments.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY) }
private val account by lazy {
AccountUtils.getAccountDetails(AccountManager.get(context), accountKey, true)
}
private var selectedRecipients: List<ParcelableUser>
get() {
val text = editParticipants.editableText ?: return emptyList()
return text.getSpans(0, text.length, ParticipantSpan::class.java).map(ParticipantSpan::user)
}
set(value) {
val roundRadius = resources.getDimension(R.dimen.element_spacing_xsmall)
val spanPadding = resources.getDimension(R.dimen.element_spacing_xsmall)
val nameFirst = preferences[nameFirstKey]
editParticipants.text = SpannableStringBuilder().apply {
value.forEach { user ->
val displayName = userColorNameManager.getDisplayName(user, nameFirst)
val span = ParticipantSpan(user, displayName, roundRadius, spanPadding)
appendCompat(user.screen_name, span, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
append(" ")
}
}
}
private var loaderInitialized: Boolean = false
private var performSearchRequestRunnable: Runnable? = null
private lateinit var usersAdapter: SelectableUsersAdapter
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setHasOptionsMenu(true)
usersAdapter = SelectableUsersAdapter(context, requestManager)
recyclerView.adapter = usersAdapter
recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
editParticipants.addTextChangedListener(object : SimpleTextWatcher {
override fun afterTextChanged(s: Editable) {
s.getSpans(0, s.length, MarkForDeleteSpan::class.java).forEach { span ->
val deleteStart = s.getSpanStart(span)
val deleteEnd = s.getSpanEnd(span)
s.removeSpan(span)
s.delete(deleteStart, deleteEnd)
}
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
super.beforeTextChanged(s, start, count, after)
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
if (s !is Spannable) return
s.getSpans(0, s.length, PendingQuerySpan::class.java).forEach { span ->
s.removeSpan(span)
}
// Processing deletion
if (count < before) {
val spans = s.getSpans(start, start, ParticipantSpan::class.java)
if (spans.isNotEmpty()) {
spans.forEach { span ->
val deleteStart = s.getSpanStart(span)
val deleteEnd = s.getSpanEnd(span)
s.removeSpan(span)
s.setSpan(MarkForDeleteSpan(), deleteStart, deleteEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
updateCheckState()
}
return
}
}
val spaceNextStart = run {
val spaceIdx = s.indexOfLast(Char::isWhitespace)
if (spaceIdx < 0) return@run 0
return@run spaceIdx + 1
}
// Skip if last char is space
if (spaceNextStart > s.lastIndex) return
if (s.getSpans(start, start + count, ParticipantSpan::class.java).isEmpty()) {
s.setSpan(PendingQuerySpan(), spaceNextStart, start + count, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
searchUser(s.substring(spaceNextStart), true)
}
}
})
val nameFirst = preferences[nameFirstKey]
val roundRadius = resources.getDimension(R.dimen.element_spacing_xsmall)
val spanPadding = resources.getDimension(R.dimen.element_spacing_xsmall)
usersAdapter.itemCheckedListener = itemChecked@ { pos, checked ->
val text: Editable = editParticipants.editableText ?: return@itemChecked false
val user = usersAdapter.getUser(pos)
if (checked) {
text.getSpans(0, text.length, PendingQuerySpan::class.java).forEach { pending ->
val start = text.getSpanStart(pending)
val end = text.getSpanEnd(pending)
text.removeSpan(pending)
if (start < 0 || end < 0 || end < start) return@forEach
text.delete(start, end)
}
val displayName = userColorNameManager.getDisplayName(user, nameFirst)
val span = ParticipantSpan(user, displayName, roundRadius, spanPadding)
text.appendCompat(user.screen_name, span, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text.append(" ")
} else {
text.getSpans(0, text.length, ParticipantSpan::class.java).forEach { span ->
if (user != span.user) {
return@forEach
}
val start = text.getSpanStart(span)
var end = text.getSpanEnd(span)
text.removeSpan(span)
// Also remove last whitespace
if (end <= text.lastIndex && text[end].isWhitespace()) {
end += 1
}
text.delete(start, end)
}
}
editParticipants.clearComposingText()
updateCheckState()
return@itemChecked true
}
if (savedInstanceState == null) {
val users = arguments.getNullableTypedArray<ParcelableUser>(EXTRA_USERS)
if (users != null && users.isNotEmpty()) {
selectedRecipients = users.toList()
editParticipants.setSelection(editParticipants.length())
if (arguments.getBoolean(EXTRA_OPEN_CONVERSATION)) {
createOrOpenConversation()
}
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.fragment_messages_conversation_new, container, false)
}
override fun onCreateLoader(id: Int, args: Bundle): Loader<List<ParcelableUser>?> {
val query = args.getString(EXTRA_QUERY)
val fromCache = args.getBoolean(EXTRA_FROM_CACHE)
val fromUser = args.getBoolean(EXTRA_FROM_USER)
return CacheUserSearchLoader(context, accountKey, query, !fromCache, true, fromUser)
}
override fun onLoaderReset(loader: Loader<List<ParcelableUser>?>) {
usersAdapter.data = null
}
override fun onLoadFinished(loader: Loader<List<ParcelableUser>?>, data: List<ParcelableUser>?) {
usersAdapter.data = data
updateCheckState()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_messages_conversation_new, menu)
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.setItemAvailability(R.id.create_conversation, selectedRecipients.isNotEmpty())
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.create_conversation -> {
createOrOpenConversation()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun createOrOpenConversation() {
val account = this.account ?: return
val selected = this.selectedRecipients
if (selected.isEmpty()) return
val maxParticipants = if (account.isOfficial(context)) {
defaultFeatures.twitterDirectMessageMaxParticipants
} else {
1
}
if (selected.size > maxParticipants) {
editParticipants.error = getString(R.string.error_message_message_too_many_participants)
return
}
val conversation = ParcelableMessageConversation()
conversation.account_color = account.color
conversation.account_key = account.key
conversation.id = "${SendMessageTask.TEMP_CONVERSATION_ID_PREFIX}${System.currentTimeMillis()}"
conversation.local_timestamp = System.currentTimeMillis()
conversation.conversation_type = if (selected.size > 1) {
ConversationType.GROUP
} else {
ConversationType.ONE_TO_ONE
}
conversation.participants = (selected + account.user).toTypedArray()
conversation.is_temp = true
if (conversation.conversation_type == ConversationType.ONE_TO_ONE) {
val participantKeys = conversation.participants.map(ParcelableUser::key)
val existingConversation = findMessageConversation(context, accountKey, participantKeys)
if (existingConversation != null) {
activity.startActivity(IntentUtils.messageConversation(accountKey, existingConversation.id))
activity.finish()
return
}
}
val values = ObjectCursor.valuesCreatorFrom(ParcelableMessageConversation::class.java).create(conversation)
context.contentResolver.insert(Conversations.CONTENT_URI, values)
activity.startActivity(IntentUtils.messageConversation(accountKey, conversation.id))
activity.finish()
}
private fun updateCheckState() {
val selected = selectedRecipients
usersAdapter.clearCheckState()
usersAdapter.clearLockedState()
usersAdapter.setLockedState(accountKey, true)
selected.forEach { user ->
usersAdapter.setCheckState(user.key, true)
}
usersAdapter.notifyDataSetChanged()
activity?.invalidateOptionsMenu()
}
private fun searchUser(query: String, fromType: Boolean) {
if (TextUtils.isEmpty(query)) {
return
}
val args = Bundle {
this[EXTRA_ACCOUNT_KEY] = accountKey
this[EXTRA_QUERY] = query
this[EXTRA_FROM_CACHE] = fromType
}
if (loaderInitialized) {
loaderManager.initLoader(0, args, this)
loaderInitialized = true
} else {
loaderManager.restartLoader(0, args, this)
}
if (performSearchRequestRunnable != null) {
editParticipants.removeCallbacks(performSearchRequestRunnable)
}
if (fromType) {
performSearchRequestRunnable = PerformSearchRequestRunnable(query, this)
editParticipants.postDelayed(performSearchRequestRunnable, 1000L)
}
}
@WorkerThread
fun findMessageConversation(context: Context, accountKey: UserKey,
participantKeys: Collection<UserKey>): ParcelableMessageConversation? {
val resolver = context.contentResolver
val where = Expression.and(Expression.equalsArgs(Conversations.ACCOUNT_KEY),
Expression.equalsArgs(Conversations.PARTICIPANT_KEYS)).sql
val whereArgs = arrayOf(accountKey.toString(), participantKeys.sorted().joinToString(","))
return resolver.queryOne(Conversations.CONTENT_URI, Conversations.COLUMNS, where, whereArgs,
null, ParcelableMessageConversation::class.java)
}
internal class PerformSearchRequestRunnable(val query: String, fragment: MessageNewConversationFragment) : Runnable {
val fragmentRef = WeakReference(fragment)
override fun run() {
val fragment = fragmentRef.get() ?: return
fragment.searchUser(query, false)
}
}
class PendingQuerySpan
class ParticipantSpan(
val user: ParcelableUser,
val displayName: String,
val roundRadius: Float,
val padding: Float
) : ReplacementSpan() {
private var backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private var backgroundBounds = RectF()
private var nameWidth: Float = 0f
init {
backgroundPaint.color = 0x20808080
}
override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
backgroundBounds.set(x, top.toFloat() + padding / 2, x + nameWidth + padding * 2, bottom - padding / 2)
canvas.drawRoundRect(backgroundBounds, roundRadius, roundRadius, backgroundPaint)
val textSizeBackup = paint.textSize
paint.textSize = textSizeBackup - padding
canvas.drawText(displayName, x + padding, y - padding / 2, paint)
paint.textSize = textSizeBackup
}
override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
val textSizeBackup = paint.textSize
paint.textSize = textSizeBackup - padding
nameWidth = paint.measureText(displayName)
paint.textSize = textSizeBackup
return Math.round(nameWidth + padding * 2)
}
}
} | gpl-3.0 |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/events/ArticleSavedOrDeletedEvent.kt | 2 | 210 | package org.wikipedia.events
import org.wikipedia.readinglist.database.ReadingListPage
class ArticleSavedOrDeletedEvent(val isAdded: Boolean, vararg pages: ReadingListPage) {
val pages = pages.toList()
}
| apache-2.0 |
Popalay/Cardme | presentation/src/main/kotlin/com/popalay/cardme/presentation/screens/holderdetails/HolderDetailsNavigator.kt | 1 | 1206 | package com.popalay.cardme.presentation.screens.home
import android.content.Intent
import android.os.Bundle
import com.popalay.cardme.presentation.base.navigation.CustomNavigator
import com.popalay.cardme.presentation.screens.SCREEN_CARD_DETAILS
import com.popalay.cardme.presentation.screens.carddetails.CardDetailsActivity
import com.popalay.cardme.presentation.screens.holderdetails.HolderDetailsActivity
import ru.terrakok.cicerone.commands.Command
import ru.terrakok.cicerone.commands.Forward
import javax.inject.Inject
class HolderDetailsNavigator @Inject constructor(
private val activity: HolderDetailsActivity
) : CustomNavigator(activity) {
override fun createActivityIntent(screenKey: String, data: Any?) = when (screenKey) {
SCREEN_CARD_DETAILS -> CardDetailsActivity.getIntent(activity, data as String)
else -> null
}
override fun createStartActivityOptions(command: Command?, activityIntent: Intent): Bundle? {
if (command is Forward && command.screenKey == SCREEN_CARD_DETAILS) {
return activity.createCardDetailsTransition(activityIntent)
}
return super.createStartActivityOptions(command, activityIntent)
}
} | apache-2.0 |
paulofernando/localchat | app/src/main/kotlin/site/paulo/localchat/data/remote/ChatGeoService.kt | 1 | 833 | /*
* Copyright 2017 Paulo Fernando
*
* 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 site.paulo.localchat.data.remote
import io.reactivex.Maybe
import retrofit2.http.GET
import site.paulo.localchat.data.model.firebase.User
interface ChatGeoService {
@GET("users")
fun getUsers(): Maybe<List<User>>
} | apache-2.0 |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/cards/DefaultCardAccountRangeStore.kt | 1 | 1529 | package com.stripe.android.cards
import android.content.Context
import androidx.annotation.VisibleForTesting
import com.stripe.android.model.AccountRange
import com.stripe.android.model.parsers.AccountRangeJsonParser
import org.json.JSONObject
internal class DefaultCardAccountRangeStore(
private val context: Context
) : CardAccountRangeStore {
private val accountRangeJsonParser = AccountRangeJsonParser()
private val prefs by lazy {
context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
}
override suspend fun get(bin: Bin): List<AccountRange> {
return prefs.getStringSet(createPrefKey(bin), null)
.orEmpty()
.mapNotNull {
accountRangeJsonParser.parse(JSONObject(it))
}
}
override fun save(
bin: Bin,
accountRanges: List<AccountRange>
) {
val serializedAccountRanges = accountRanges.map {
accountRangeJsonParser.serialize(it).toString()
}.toSet()
prefs.edit()
.putStringSet(createPrefKey(bin), serializedAccountRanges)
.apply()
}
override suspend fun contains(
bin: Bin
): Boolean = prefs.contains(createPrefKey(bin))
@VisibleForTesting
internal fun createPrefKey(bin: Bin): String = "$PREF_KEY_ACCOUNT_RANGES:$bin"
private companion object {
private const val PREF_FILE = "InMemoryCardAccountRangeSource.Store"
private const val PREF_KEY_ACCOUNT_RANGES = "key_account_ranges"
}
}
| mit |
stripe/stripe-android | stripecardscan/src/androidTest/java/com/stripe/android/stripecardscan/scanui/util/ViewExtensionsTest.kt | 1 | 789 | package com.stripe.android.stripecardscan.scanui.util
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.stripe.android.stripecardscan.test.R
import org.junit.Test
import kotlin.test.assertEquals
class ViewExtensionsTest {
private val testContext = InstrumentationRegistry.getInstrumentation().context
@Test
@SmallTest
fun getColorByRes_matches() {
val color = testContext.getColorByRes(R.color.testColor)
val alpha = color shr 24 and 0xFF
val red = color shr 16 and 0xFF
val green = color shr 8 and 0xFF
val blue = color and 0xFF
assertEquals(0xA1, alpha)
assertEquals(0x1E, red)
assertEquals(0x90, green)
assertEquals(0xFF, blue)
}
}
| mit |
hypercube1024/kotlin_test | src/main/kotlin/com/mykotlin/alias/test/TestAlias.kt | 1 | 191 | package com.mykotlin.alias.test
import com.mykotlin.json
/**
* @author Pengtao Qiu
*/
fun main(args: Array<String>) {
val str = json.toJson(arrayOf(1..10))
println("json: $str")
} | apache-2.0 |
jitsi/ice4j | src/main/kotlin/org/ice4j/ice/AgentConfig.kt | 1 | 3051 | /*
* Copyright @ 2020 - Present, 8x8 Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ice4j.ice
import org.jitsi.metaconfig.config
import java.time.Duration
import org.jitsi.config.JitsiConfig.Companion.newConfig as configSource
class AgentConfig {
val consentFreshnessInterval: Duration by config {
"org.ice4j.ice.CONSENT_FRESHNESS_INTERVAL".from(configSource)
.convertFrom<Long> { Duration.ofMillis(it) }
"ice4j.consent-freshness.interval".from(configSource)
}
val consentFreshnessOriginalWaitInterval: Duration by config {
"org.ice4j.ice.CONSENT_FRESHNESS_WAIT_INTERVAL".from(configSource)
.convertFrom<Long> { Duration.ofMillis(it) }
"ice4j.consent-freshness.original-wait-interval".from(configSource)
}
val consentFreshnessMaxWaitInterval: Duration by config {
"org.ice4j.ice.CONSENT_FRESHNESS_MAX_WAIT_INTERVAL".from(configSource)
.convertFrom<Long> { Duration.ofMillis(it) }
"ice4j.consent-freshness.max-wait-interval".from(configSource)
}
val maxConsentFreshnessRetransmissions: Int by config {
"org.ice4j.ice.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS".from(configSource)
"ice4j.consent-freshness.max-retransmissions".from(configSource)
}
val terminationDelay: Duration by config {
"org.ice4j.TERMINATION_DELAY".from(configSource)
.convertFrom<Long> { Duration.ofMillis(it) }
"ice4j.ice.termination-delay".from(configSource)
}
val maxCheckListSize: Int by config {
"org.ice4j.MAX_CHECK_LIST_SIZE".from(configSource)
"ice4j.ice.max-check-list-size".from(configSource)
}
/** The value of the SOFTWARE attribute that ice4j should include in all outgoing messages. */
val software: String? by config {
"org.ice4j.SOFTWARE".from(configSource)
"ice4j.software".from(configSource)
}
/**
* Whether the per-component merging socket should be enabled by default (the default value can be
* overridden with the [Agent] API).
* If enabled, the user of the library must use the socket instance provided by [Component.getSocket]. Otherwise,
* the socket instance from the desired [CandidatePair] must be used.
*/
val useComponentSocket: Boolean by config {
"org.ice4j.ice.USE_COMPONENT_SOCKET".from(configSource)
"ice4j.use-component-socket".from(configSource)
}
companion object {
@JvmField
val config = AgentConfig()
}
}
| apache-2.0 |
hannesa2/owncloud-android | owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt | 2 | 2753 | /**
* ownCloud Android client application
*
* @author David González Verdugo
* @author Jesús Recio
* Copyright (C) 2020 ownCloud GmbH.
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.data.capabilities.datasources
import com.owncloud.android.data.capabilities.datasources.implementation.OCRemoteCapabilitiesDataSource
import com.owncloud.android.lib.resources.status.services.implementation.OCCapabilityService
import com.owncloud.android.data.capabilities.datasources.mapper.RemoteCapabilityMapper
import com.owncloud.android.testutil.OC_ACCOUNT_NAME
import com.owncloud.android.testutil.OC_CAPABILITY
import com.owncloud.android.utils.createRemoteOperationResultMock
import io.mockk.every
import io.mockk.mockk
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Test
class OCRemoteCapabilitiesDataSourceTest {
private lateinit var ocRemoteCapabilitiesDataSource: OCRemoteCapabilitiesDataSource
private val ocCapabilityService: OCCapabilityService = mockk()
private val remoteCapabilityMapper = RemoteCapabilityMapper()
@Before
fun init() {
ocRemoteCapabilitiesDataSource =
OCRemoteCapabilitiesDataSource(
ocCapabilityService,
remoteCapabilityMapper
)
}
@Test
fun readRemoteCapabilities() {
val accountName = OC_ACCOUNT_NAME
val remoteCapability = remoteCapabilityMapper.toRemote(OC_CAPABILITY)!!
val getRemoteCapabilitiesOperationResult = createRemoteOperationResultMock(remoteCapability, true)
every { ocCapabilityService.getCapabilities() } returns getRemoteCapabilitiesOperationResult
// Get capability from remote datasource
val capabilities = ocRemoteCapabilitiesDataSource.getCapabilities(accountName)
assertNotNull(capabilities)
assertEquals(OC_CAPABILITY.accountName, capabilities.accountName)
assertEquals(OC_CAPABILITY.versionMayor, capabilities.versionMayor)
assertEquals(OC_CAPABILITY.versionMinor, capabilities.versionMinor)
assertEquals(OC_CAPABILITY.versionMicro, capabilities.versionMicro)
}
}
| gpl-2.0 |
AndroidX/androidx | work/work-rxjava2/src/test/java/androidx/work/RxForegroundInfoTest.kt | 3 | 3368 | /*
* 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.work
import android.app.Notification
import android.content.Context
import androidx.work.ListenableWorker.Result
import androidx.work.impl.utils.SynchronousExecutor
import androidx.work.impl.utils.futures.SettableFuture
import com.google.common.truth.Truth.assertThat
import io.reactivex.Single
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito.mock
import java.util.UUID
import java.util.concurrent.Executor
@RunWith(JUnit4::class)
class RxForegroundInfoTest {
@Test
fun testForegroundInfo() {
val context = mock(Context::class.java)
val foregroundInfo = WorkerGetForeground(context, createWorkerParams())
.foregroundInfoAsync.get()
assertThat(foregroundInfo).isEqualTo(testForegroundInfo)
}
@Test
fun testSetForegroundInfo() {
val context = mock(Context::class.java)
var actualForegroundInfo: ForegroundInfo? = null
val foregroundUpdater = ForegroundUpdater { _, _, foregroundInfo ->
actualForegroundInfo = foregroundInfo
val future = SettableFuture.create<Void>()
future.set(null)
future
}
val worker = WorkerSetForeground(context, createWorkerParams(
foregroundUpdater = foregroundUpdater
))
val result = worker.startWork().get()
assertThat(result).isEqualTo(Result.success())
assertThat(actualForegroundInfo).isEqualTo(testForegroundInfo)
}
}
private val testForegroundInfo = ForegroundInfo(10, mock(Notification::class.java))
private class WorkerGetForeground(
appContext: Context,
workerParams: WorkerParameters
) : RxWorker(appContext, workerParams) {
override fun createWork(): Single<Result> {
throw UnsupportedOperationException()
}
override fun getForegroundInfo(): Single<ForegroundInfo> = Single.just(testForegroundInfo)
}
private class WorkerSetForeground(
appContext: Context,
workerParams: WorkerParameters
) : RxWorker(appContext, workerParams) {
override fun createWork(): Single<Result> {
setForeground(testForegroundInfo).blockingAwait()
return Single.just(Result.success())
}
}
private fun createWorkerParams(
executor: Executor = SynchronousExecutor(),
progressUpdater: ProgressUpdater = mock(ProgressUpdater::class.java),
foregroundUpdater: ForegroundUpdater = mock(ForegroundUpdater::class.java)
) = WorkerParameters(
UUID.randomUUID(),
Data.EMPTY,
emptyList(),
WorkerParameters.RuntimeExtras(),
1,
0,
executor,
RxWorkerTest.InstantWorkTaskExecutor(),
WorkerFactory.getDefaultWorkerFactory(),
progressUpdater,
foregroundUpdater
)
| apache-2.0 |
Dmedina88/SSB | example/app/src/main/kotlin/com/grayherring/devtalks/di/DataModule.kt | 1 | 3301 | package com.grayherring.devtalks.di
import android.app.Application
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.grayherring.devtalks.base.util.capture.GsonPrefRecorder
import com.grayherring.devtalks.data.repository.Repository
import com.grayherring.devtalks.data.repository.api.DevTalkApi
import com.grayherring.devtalks.data.repository.api.DevTalkApiClient
import com.grayherring.devtalks.data.repository.api.ExceptionInterceptor
import com.grayherring.devtalks.ui.home.HomeState
import com.readystatesoftware.chuck.ChuckInterceptor
import dagger.Module
import dagger.Provides
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.OkHttpClient.Builder
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.HttpLoggingInterceptor.Level.BODY
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module(includes = arrayOf(ViewModelModule::class))
class DataModule {
// @PerApp @Provides fun provideAppDatabase(context: Context) = AppDatabase.createPersistentDatabase(context)
@Provides @Singleton fun providesGson() =
GsonBuilder()
.setDateFormat("yyyy-dd-MM")
.create()
@Provides @Singleton fun provideExceptionInterceptor(gson: Gson) = ExceptionInterceptor(gson)
@Provides @Singleton fun provideOkHttpClient(exceptionInterceptor: ExceptionInterceptor,
application: Application): OkHttpClient {
val clientBuilder = Builder()
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = BODY
clientBuilder.addInterceptor(ChuckInterceptor(application))
clientBuilder.addInterceptor(httpLoggingInterceptor)
clientBuilder.addInterceptor(exceptionInterceptor)
return clientBuilder.build()
}
@Provides @Singleton fun provideHttpUrl(): HttpUrl =
HttpUrl.parse("https://dev-talk-test.herokuapp.com") as HttpUrl
@Provides @Singleton fun provideDevTalkApiClient(devTalkApi: DevTalkApi) = DevTalkApiClient(
devTalkApi)
@Provides @Singleton fun provideRepository(devTalkApi: DevTalkApiClient) = Repository(devTalkApi)
@Provides @Singleton fun provideRetrofit(baseUrl: HttpUrl,
client: OkHttpClient,
gson: Gson): Retrofit {
return Retrofit.Builder()
.client(client)
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
@Provides @Singleton fun provideDevTalkApi(retrofit: Retrofit): DevTalkApi {
return retrofit.create(DevTalkApi::class.java)
}
@Provides @Singleton fun provideHomeCapturer(application: Application,
gson: Gson): GsonPrefRecorder<HomeState> {
return GsonPrefRecorder<HomeState>(application.applicationContext.getSharedPreferences("preft",
0), "stat", Array<HomeState>::class.java, gson)
}
// @Provides @Singleton fun provideLocalTalkDB(context: Context): TalkDB
// = Room.databaseBuilder(context, TalkDB::class.java, "database-name").build()
}
| apache-2.0 |
hannesa2/owncloud-android | owncloudData/src/test/java/com/owncloud/android/data/user/db/UserQuotaEntityTest.kt | 2 | 1922 | /**
* ownCloud Android client application
*
* @author Abel García de Prada
* Copyright (C) 2020 ownCloud GmbH.
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.data.user.db
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class UserQuotaEntityTest {
@Test
fun testConstructor() {
val item = UserQuotaEntity(
"accountName",
200,
800
)
assertEquals("accountName", item.accountName)
assertEquals(800, item.available)
assertEquals(200, item.used)
}
@Test
fun testEqualsOk() {
val item1 = UserQuotaEntity(
accountName = "accountName",
available = 200,
used = 800
)
val item2 = UserQuotaEntity(
"accountName",
800,
200
)
assertTrue(item1 == item2)
assertFalse(item1 === item2)
}
@Test
fun testEqualsKo() {
val item1 = UserQuotaEntity(
accountName = "accountName",
available = 800,
used = 200
)
val item2 = UserQuotaEntity(
"accountName2",
200,
800
)
assertFalse(item1 == item2)
assertFalse(item1 === item2)
}
}
| gpl-2.0 |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/floating/FloatingTestRunnerService.kt | 1 | 969 | //package com.exyui.android.debugbottle.components.floating
//
//import android.content.Intent
//import android.os.IBinder
//import com.exyui.android.debugbottle.components.RunningFeatureMgr
//
///**
// * Created by yuriel on 9/19/16.
// */
//@Deprecated(
// message = "use __TestingRunnerBubble instead",
// replaceWith = ReplaceWith("__TestingRunnerBubble", "com.exyui.android.debugbottle.components.bubbles.services.__TestingRunnerBubble")
//)
//internal class FloatingTestRunnerService: DTBaseFloatingService() {
// override val floatingViewMgr: DTDragFloatingViewMgr = FloatingTestRunnerViewMgr
// override fun onBind(intent: Intent?): IBinder? = null
//
// override fun createView() {
// super.createView()
// RunningFeatureMgr.add(RunningFeatureMgr.STRESS_TEST_RUNNER)
// }
//
// override fun onDestroy() {
// super.onDestroy()
// RunningFeatureMgr.remove(RunningFeatureMgr.STRESS_TEST_RUNNER)
// }
//} | apache-2.0 |
google/dokka | core/testdata/format/website/sample.kt | 9 | 384 | /**
* Groups elements of the original sequence by the key returned by the given [keySelector] function
* applied to each element and returns a map where each group key is associated with a list of corresponding elements.
* @sample example1
*/
fun foo(): Int {
return 0
}
fun foo(i: Int): Int {
return 1
}
fun example1(node: String) = if (true) {
println(property)
}
| apache-2.0 |
erva/CellAdapter | sample-x-kotlin/src/main/kotlin/io/erva/sample/base/cell/BetaCell.kt | 1 | 489 | package io.erva.sample.base.cell
import android.view.View
import io.erva.celladapter.Layout
import io.erva.celladapter.x.Cell
import io.erva.sample.R
import io.erva.sample.base.model.BetaModel
import kotlinx.android.synthetic.main.item_base_beta.view.*
@Layout(R.layout.item_base_beta)
class BetaCell(view: View) : Cell<BetaModel, BetaCell.Listener>(view) {
override fun bindView() {
view.tv_beta.text = item().beta
}
interface Listener : Cell.Listener<BetaModel>
} | mit |
androidx/androidx | compose/material3/material3/src/androidAndroidTest/kotlin/androidx/compose/material3/TabTest.kt | 3 | 29375 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.samples.LeadingIconTabs
import androidx.compose.material3.samples.ScrollingTextTabs
import androidx.compose.material3.samples.TextTabs
import androidx.compose.material3.tokens.PrimaryNavigationTabTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.testutils.assertIsEqualTo
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.InspectableValue
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.isDebugInspectorInfoEnabled
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.SemanticsMatcher
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.assertHasClickAction
import androidx.compose.ui.test.assertHeightIsAtLeast
import androidx.compose.ui.test.assertHeightIsEqualTo
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.assertIsNotSelected
import androidx.compose.ui.test.assertIsSelected
import androidx.compose.ui.test.assertPositionInRootIsEqualTo
import androidx.compose.ui.test.getBoundsInRoot
import androidx.compose.ui.test.getUnclippedBoundsInRoot
import androidx.compose.ui.test.isSelectable
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onParent
import androidx.compose.ui.test.performClick
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.height
import androidx.compose.ui.unit.width
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class TabTest {
private val ExpectedSmallTabHeight = 48.dp
private val ExpectedLargeTabHeight = 72.dp
private val icon = Icons.Filled.Favorite
@get:Rule
val rule = createComposeRule()
@Before
fun before() {
isDebugInspectorInfoEnabled = true
}
@After
fun after() {
isDebugInspectorInfoEnabled = false
}
@Test
fun defaultSemantics() {
rule.setMaterialContent(lightColorScheme()) {
TabRow(0) {
Tab(
selected = true,
onClick = {},
modifier = Modifier.testTag("tab"),
text = { Text("Text") }
)
}
}
rule.onNodeWithTag("tab")
.assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Tab))
.assertIsSelected()
.assertIsEnabled()
.assertHasClickAction()
rule.onNodeWithTag("tab")
.onParent()
.assert(SemanticsMatcher.keyIsDefined(SemanticsProperties.SelectableGroup))
}
@Test
fun disabledSemantics() {
rule.setMaterialContent(lightColorScheme()) {
Box {
Tab(
selected = true,
onClick = {},
modifier = Modifier.testTag("tab"),
enabled = false,
text = { Text("Text") }
)
}
}
rule.onNodeWithTag("tab")
.assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Tab))
.assertIsSelected()
.assertIsNotEnabled()
.assertHasClickAction()
}
@Test
fun leadingIconTab_defaultSemantics() {
rule.setMaterialContent(lightColorScheme()) {
TabRow(0) {
LeadingIconTab(
selected = true,
onClick = {},
text = { Text("Text") },
icon = { Icon(icon, null) },
modifier = Modifier.testTag("leadingIconTab")
)
}
}
rule.onNodeWithTag("leadingIconTab")
.assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Tab))
.assertIsSelected()
.assertIsEnabled()
.assertHasClickAction()
rule.onNodeWithTag("leadingIconTab")
.onParent()
.assert(SemanticsMatcher.keyIsDefined(SemanticsProperties.SelectableGroup))
}
@Test
fun leadingIconTab_disabledSemantics() {
rule.setMaterialContent(lightColorScheme()) {
Box {
LeadingIconTab(
selected = true,
onClick = {},
text = { Text("Text") },
icon = { Icon(icon, null) },
modifier = Modifier.testTag("leadingIconTab"),
enabled = false
)
}
}
rule.onNodeWithTag("leadingIconTab")
.assert(SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.Tab))
.assertIsSelected()
.assertIsNotEnabled()
.assertHasClickAction()
}
@Test
fun textTab_height() {
rule
.setMaterialContentForSizeAssertions {
Tab(selected = true, onClick = {}, text = { Text("Text") })
}
.assertHeightIsEqualTo(ExpectedSmallTabHeight)
}
@Test
fun iconTab_height() {
rule
.setMaterialContentForSizeAssertions {
Tab(selected = true, onClick = {}, icon = { Icon(icon, null) })
}
.assertHeightIsEqualTo(ExpectedSmallTabHeight)
}
@Test
fun textAndIconTab_height() {
rule
.setMaterialContentForSizeAssertions {
Surface {
Tab(
selected = true,
onClick = {},
text = { Text("Text and Icon") },
icon = { Icon(icon, null) }
)
}
}
.assertHeightIsEqualTo(ExpectedLargeTabHeight)
}
@Test
fun leadingIconTab_height() {
rule
.setMaterialContentForSizeAssertions {
Surface {
LeadingIconTab(
selected = true,
onClick = {},
text = { Text("Text") },
icon = { Icon(icon, null) }
)
}
}
.assertHeightIsEqualTo(ExpectedSmallTabHeight)
}
@Test
fun fixedTabRow_indicatorPosition() {
val indicatorHeight = 1.dp
rule.setMaterialContent(lightColorScheme()) {
var state by remember { mutableStateOf(0) }
val titles = listOf("TAB 1", "TAB 2")
val indicator = @Composable { tabPositions: List<TabPosition> ->
Box(
Modifier
.tabIndicatorOffset(tabPositions[state])
.fillMaxWidth()
.height(indicatorHeight)
.background(color = Color.Red)
.testTag("indicator")
)
}
Box(Modifier.testTag("tabRow")) {
TabRow(
selectedTabIndex = state,
indicator = indicator
) {
titles.forEachIndexed { index, title ->
Tab(
selected = state == index,
onClick = { state = index },
text = { Text(title) }
)
}
}
}
}
val tabRowBounds = rule.onNodeWithTag("tabRow").getUnclippedBoundsInRoot()
rule.onNodeWithTag("indicator", true)
.assertPositionInRootIsEqualTo(
expectedLeft = 0.dp,
expectedTop = tabRowBounds.height - indicatorHeight
)
// Click the second tab
rule.onAllNodes(isSelectable())[1].performClick()
// Indicator should now be placed in the bottom left of the second tab, so its x coordinate
// should be in the middle of the TabRow
rule.onNodeWithTag("indicator", true)
.assertPositionInRootIsEqualTo(
expectedLeft = (tabRowBounds.width / 2),
expectedTop = tabRowBounds.height - indicatorHeight
)
}
@Test
fun fixedTabRow_dividerHeight() {
rule.setMaterialContent(lightColorScheme()) {
val titles = listOf("TAB 1", "TAB 2")
val tabRowHeight = 100.dp
val divider = @Composable { Divider(Modifier.testTag("divider")) }
Box(Modifier.testTag("tabRow")) {
TabRow(
modifier = Modifier.height(tabRowHeight),
selectedTabIndex = 0,
divider = divider
) {
titles.forEachIndexed { index, title ->
Tab(
selected = index == 0,
onClick = {},
modifier = Modifier.height(tabRowHeight),
text = { Text(title) }
)
}
}
}
}
val tabRowBounds = rule.onNodeWithTag("tabRow").getBoundsInRoot()
rule.onNodeWithTag("divider", true)
.assertPositionInRootIsEqualTo(
expectedLeft = 0.dp,
expectedTop = tabRowBounds.height - PrimaryNavigationTabTokens.DividerHeight
)
.assertHeightIsEqualTo(PrimaryNavigationTabTokens.DividerHeight)
}
@Test
fun singleLineTab_textPosition() {
rule.setMaterialContent(lightColorScheme()) {
var state by remember { mutableStateOf(0) }
val titles = listOf("TAB")
Box {
TabRow(
modifier = Modifier.testTag("tabRow"),
selectedTabIndex = state
) {
titles.forEachIndexed { index, title ->
Tab(
selected = state == index,
onClick = { state = index },
text = {
Text(title, Modifier.testTag("text"))
}
)
}
}
}
}
val tabRowBounds = rule.onNodeWithTag("tabRow").getUnclippedBoundsInRoot()
val textBounds =
rule.onNodeWithTag("text", useUnmergedTree = true).getUnclippedBoundsInRoot()
val expectedPositionY = (tabRowBounds.height - textBounds.height) / 2
textBounds.top.assertIsEqualTo(expectedPositionY, "text bounds top y-position")
}
@Test
fun singleLineTab_withIcon_textBaseline() {
rule.setMaterialContent(lightColorScheme()) {
var state by remember { mutableStateOf(0) }
val titles = listOf("TAB")
Box {
TabRow(
modifier = Modifier.testTag("tabRow"),
selectedTabIndex = state
) {
titles.forEachIndexed { index, title ->
Tab(
selected = state == index,
onClick = { state = index },
text = {
Text(title, Modifier.testTag("text"))
},
icon = { Icon(Icons.Filled.Favorite, null) }
)
}
}
}
}
val expectedBaseline = 14.dp
val indicatorHeight = 3.dp
val expectedBaselineDistance = expectedBaseline + indicatorHeight
val tabRowBounds = rule.onNodeWithTag("tabRow").getUnclippedBoundsInRoot()
val textBounds =
rule.onNodeWithTag("text", useUnmergedTree = true).getUnclippedBoundsInRoot()
val textBaselinePos =
rule.onNodeWithTag("text", useUnmergedTree = true).getLastBaselinePosition()
val baselinePositionY = textBounds.top + textBaselinePos
val expectedPositionY = tabRowBounds.height - expectedBaselineDistance
baselinePositionY.assertIsEqualTo(expectedPositionY, "baseline y-position")
}
@Test
fun twoLineTab_textPosition() {
rule.setMaterialContent(lightColorScheme()) {
var state by remember { mutableStateOf(0) }
val titles = listOf("Two line \n text")
Box {
TabRow(
modifier = Modifier.testTag("tabRow"),
selectedTabIndex = state
) {
titles.forEachIndexed { index, title ->
Tab(
selected = state == index,
onClick = { state = index },
text = {
Text(title, Modifier.testTag("text"), maxLines = 2)
}
)
}
}
}
}
val tabRowBounds = rule.onNodeWithTag("tabRow").getUnclippedBoundsInRoot()
val textBounds =
rule.onNodeWithTag("text", useUnmergedTree = true).getUnclippedBoundsInRoot()
val expectedPositionY = (tabRowBounds.height - textBounds.height) / 2
textBounds.top.assertIsEqualTo(expectedPositionY, "text bounds top y-position")
}
@Test
fun LeadingIconTab_textAndIconPosition() {
rule.setMaterialContent(lightColorScheme()) {
Box {
TabRow(
modifier = Modifier.testTag("tabRow"),
selectedTabIndex = 0
) {
LeadingIconTab(
selected = true,
onClick = {},
text = {
Text("TAB", Modifier.testTag("text"))
},
icon = { Icon(Icons.Filled.Favorite, null, Modifier.testTag("icon")) }
)
}
}
}
val tabRowBounds =
rule.onNodeWithTag("tabRow", useUnmergedTree = true).getUnclippedBoundsInRoot()
val textBounds =
rule.onNodeWithTag("text", useUnmergedTree = true).getUnclippedBoundsInRoot()
val textDistanceFromIcon = 8.dp
val iconBounds =
rule.onNodeWithTag("icon", useUnmergedTree = true).getUnclippedBoundsInRoot()
textBounds.left.assertIsEqualTo(
iconBounds.right + textDistanceFromIcon,
"textBounds left-position"
)
val iconOffset =
(tabRowBounds.width - iconBounds.width - textBounds.width - textDistanceFromIcon) / 2
iconBounds.left.assertIsEqualTo(iconOffset, "iconBounds left-position")
}
@Test
fun scrollableTabRow_indicatorPosition() {
val indicatorHeight = 1.dp
val minimumTabWidth = 90.dp
rule.setMaterialContent(lightColorScheme()) {
var state by remember { mutableStateOf(0) }
val titles = listOf("TAB 1", "TAB 2")
val indicator = @Composable { tabPositions: List<TabPosition> ->
Box(
Modifier
.tabIndicatorOffset(tabPositions[state])
.fillMaxWidth()
.height(indicatorHeight)
.background(color = Color.Red)
.testTag("indicator")
)
}
Box {
ScrollableTabRow(
modifier = Modifier.testTag("tabRow"),
selectedTabIndex = state,
indicator = indicator
) {
titles.forEachIndexed { index, title ->
Tab(
selected = state == index,
onClick = { state = index },
text = { Text(title) }
)
}
}
}
}
val tabRowBounds = rule.onNodeWithTag("tabRow").getUnclippedBoundsInRoot()
val tabRowPadding = 52.dp
// Indicator should be placed in the bottom left of the first tab
rule.onNodeWithTag("indicator", true)
.assertPositionInRootIsEqualTo(
// Tabs in a scrollable tab row are offset 52.dp from each end
expectedLeft = tabRowPadding,
expectedTop = tabRowBounds.height - indicatorHeight
)
// Click the second tab
rule.onAllNodes(isSelectable())[1].performClick()
// Indicator should now be placed in the bottom left of the second tab, so its x coordinate
// should be in the middle of the TabRow
rule.onNodeWithTag("indicator", true)
.assertPositionInRootIsEqualTo(
expectedLeft = tabRowPadding + minimumTabWidth,
expectedTop = tabRowBounds.height - indicatorHeight
)
}
@Test
fun scrollableTabRow_dividerHeight() {
rule.setMaterialContent(lightColorScheme()) {
val titles = listOf("TAB 1", "TAB 2")
val tabRowHeight = 100.dp
val divider = @Composable { Divider(Modifier.testTag("divider")) }
Box(Modifier.testTag("tabRow")) {
ScrollableTabRow(
modifier = Modifier.height(tabRowHeight),
selectedTabIndex = 0,
divider = divider
) {
titles.forEachIndexed { index, title ->
Tab(
selected = index == 0,
onClick = {},
modifier = Modifier.height(tabRowHeight),
text = { Text(title) }
)
}
}
}
}
val tabRowBounds = rule.onNodeWithTag("tabRow").getBoundsInRoot()
rule.onNodeWithTag("divider", true)
.assertPositionInRootIsEqualTo(
expectedLeft = 0.dp,
expectedTop = tabRowBounds.height - PrimaryNavigationTabTokens.DividerHeight,
)
.assertHeightIsEqualTo(PrimaryNavigationTabTokens.DividerHeight)
}
@Test
fun fixedTabRow_initialTabSelected() {
rule
.setMaterialContent(lightColorScheme()) {
TextTabs()
}
// Only the first tab should be selected
rule.onAllNodes(isSelectable())
.assertCountEquals(3)
.apply {
get(0).assertIsSelected()
get(1).assertIsNotSelected()
get(2).assertIsNotSelected()
}
}
@Test
fun fixedTabRow_selectNewTab() {
rule
.setMaterialContent(lightColorScheme()) {
TextTabs()
}
// Only the first tab should be selected
rule.onAllNodes(isSelectable())
.assertCountEquals(3)
.apply {
get(0).assertIsSelected()
get(1).assertIsNotSelected()
get(2).assertIsNotSelected()
}
// Click the last tab
rule.onAllNodes(isSelectable())[2].performClick()
// Now only the last tab should be selected
rule.onAllNodes(isSelectable())
.assertCountEquals(3)
.apply {
get(0).assertIsNotSelected()
get(1).assertIsNotSelected()
get(2).assertIsSelected()
}
}
@Test
fun fixedLeadingIconTabRow_initialTabSelected() {
rule
.setMaterialContent(lightColorScheme()) {
LeadingIconTabs()
}
// Only the first tab should be selected
rule.onAllNodes(isSelectable())
.assertCountEquals(3)
.apply {
get(0).assertIsSelected()
get(1).assertIsNotSelected()
get(2).assertIsNotSelected()
}
}
@Test
fun LeadingIconTabRow_selectNewTab() {
rule
.setMaterialContent(lightColorScheme()) {
LeadingIconTabs()
}
// Only the first tab should be selected
rule.onAllNodes(isSelectable())
.assertCountEquals(3)
.apply {
get(0).assertIsSelected()
get(1).assertIsNotSelected()
get(2).assertIsNotSelected()
}
// Click the last tab
rule.onAllNodes(isSelectable())[2].performClick()
// Now only the last tab should be selected
rule.onAllNodes(isSelectable())
.assertCountEquals(3)
.apply {
get(0).assertIsNotSelected()
get(1).assertIsNotSelected()
get(2).assertIsSelected()
}
}
@Test
fun scrollableTabRow_initialTabSelected() {
rule
.setMaterialContent(lightColorScheme()) {
ScrollingTextTabs()
}
// Only the first tab should be selected
rule.onAllNodes(isSelectable())
.assertCountEquals(10)
.apply {
get(0).assertIsSelected()
(1..9).forEach {
get(it).assertIsNotSelected()
}
}
}
@Test
fun scrollableTabRow_offScreenTabInitiallySelected() {
rule
.setMaterialContent(lightColorScheme()) {
var state by remember { mutableStateOf(9) }
val titles = List(10) { "Tab ${it + 1}" }
ScrollableTabRow(selectedTabIndex = state) {
titles.forEachIndexed { index, title ->
Tab(
selected = state == index,
onClick = { state = index },
text = { Text(title) }
)
}
}
}
rule.onAllNodes(isSelectable())
.assertCountEquals(10)
.apply {
// The last tab should be selected and displayed (scrolled to)
get(9)
.assertIsSelected()
.assertIsDisplayed()
}
}
@Test
fun scrollableTabRow_selectNewTab() {
rule
.setMaterialContent(lightColorScheme()) {
ScrollingTextTabs()
}
// Only the first tab should be selected
rule.onAllNodes(isSelectable())
.assertCountEquals(10)
.apply {
get(0).assertIsSelected()
(1..9).forEach {
get(it).assertIsNotSelected()
}
}
// Click the second tab
rule.onAllNodes(isSelectable())[1].performClick()
// Now only the second tab should be selected
rule.onAllNodes(isSelectable())
.assertCountEquals(10)
.apply {
get(0).assertIsNotSelected()
get(1).assertIsSelected()
(2..9).forEach {
get(it).assertIsNotSelected()
}
}
}
@Test
fun tabRowIndicator_animatesWidthChange() {
rule.mainClock.autoAdvance = false
rule.setMaterialContent(lightColorScheme()) {
var state by remember { mutableStateOf(0) }
val titles = listOf("TAB 1", "TAB 2", "TAB 3 WITH LOTS OF TEXT")
val indicator = @Composable { tabPositions: List<TabPosition> ->
TabRowDefaults.Indicator(
Modifier.tabIndicatorOffset(tabPositions[state])
.testTag("indicator")
)
}
Box {
ScrollableTabRow(
selectedTabIndex = state,
indicator = indicator
) {
titles.forEachIndexed { index, title ->
Tab(
selected = state == index,
onClick = { state = index },
text = { Text(title) }
)
}
}
}
}
val initialWidth = rule.onNodeWithTag("indicator").getUnclippedBoundsInRoot().width
// Click the third tab, which is wider than the first
rule.onAllNodes(isSelectable())[2].performClick()
// Ensure animation starts
rule.mainClock.advanceTimeBy(50)
val midAnimationWidth = rule.onNodeWithTag("indicator").getUnclippedBoundsInRoot().width
assertThat(initialWidth).isLessThan(midAnimationWidth)
// Allow animation to complete
rule.mainClock.autoAdvance = true
rule.waitForIdle()
val finalWidth = rule.onNodeWithTag("indicator").getUnclippedBoundsInRoot().width
assertThat(midAnimationWidth).isLessThan(finalWidth)
}
@Test
fun testInspectorValue() {
val pos = TabPosition(10.0.dp, 200.0.dp)
rule.setContent {
val modifier = Modifier.tabIndicatorOffset(pos) as InspectableValue
assertThat(modifier.nameFallback).isEqualTo("tabIndicatorOffset")
assertThat(modifier.valueOverride).isEqualTo(pos)
assertThat(modifier.inspectableElements.asIterable()).isEmpty()
}
}
@Test
fun disabled_noClicks() {
var clicks = 0
rule.setMaterialContent(lightColorScheme()) {
Box {
Tab(
selected = true,
onClick = { clicks++ },
modifier = Modifier.testTag("tab"),
enabled = false,
text = { Text("Text") }
)
}
}
rule.onNodeWithTag("tab")
.performClick()
rule.runOnIdle {
assertThat(clicks).isEqualTo(0)
}
}
@Test
fun leadingIconTab_disabled_noClicks() {
var clicks = 0
rule.setMaterialContent(lightColorScheme()) {
Box {
LeadingIconTab(
selected = true,
onClick = { clicks++ },
text = { Text("Text") },
icon = { Icon(icon, null) },
modifier = Modifier.testTag("tab"),
enabled = false
)
}
}
rule.onNodeWithTag("tab")
.performClick()
rule.runOnIdle {
assertThat(clicks).isEqualTo(0)
}
}
@Test
fun fontScaleChange_height() {
rule
.setMaterialContentForSizeAssertions {
CompositionLocalProvider(
LocalDensity provides
Density(
density = LocalDensity.current.density,
fontScale = 2.0f
)
) {
Surface {
Tab(
selected = true,
onClick = {},
text = { Text("Text") },
icon = { Icon(icon, null) }
)
}
}
}
.assertHeightIsAtLeast(100.dp)
}
}
| apache-2.0 |
hotpodata/redchain | mobile/src/main/java/com/hotpodata/redchain/adapter/ChainAdapter.kt | 1 | 13016 | package com.hotpodata.redchain.adapter
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.provider.Settings
import android.support.v7.widget.RecyclerView
import android.transition.AutoTransition
import android.transition.Scene
import android.transition.TransitionManager
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.view.animation.Interpolator
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdView
import com.hotpodata.redchain.BuildConfig
import com.hotpodata.redchain.ChainMaster
import com.hotpodata.redchain.R
import com.hotpodata.redchain.adapter.viewholder.*
import com.hotpodata.redchain.data.Chain
import com.hotpodata.redchain.interfaces.ChainUpdateListener
import org.joda.time.Days
import org.joda.time.LocalDate
import org.joda.time.LocalDateTime
import org.joda.time.format.DateTimeFormat
import timber.log.Timber
import java.security.MessageDigest
import java.util.*
/**
* Created by jdrotos on 9/17/15.
*/
public class ChainAdapter(context: Context, argChain: Chain) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val ctx = context
val CHAIN_LINK = 0;
val VERTICAL_LINE = 1;
val CHAIN_TODAY = 2;
val CHAIN_FIRST_DAY_MESSAGE = 3;
val CHAIN_AD = 4
var chain: Chain
var rows = ArrayList<Row>()
val dtformat1 = DateTimeFormat.forPattern("EEEE")
val dtformat2 = DateTimeFormat.shortDate()
val dtformat3 = DateTimeFormat.shortTime()
val interpo: Interpolator;
val rowMaxTitleSize: Int
val rowMinTitleSize: Int
val rowMaxLineSize: Int
val rowMinLineSize: Int
var chainUpdateListener: ChainUpdateListener? = null
var todayChainAnimFlag = false
init {
chain = argChain
rowMaxTitleSize = context.resources.getDimensionPixelSize(R.dimen.row_title_max)
rowMinTitleSize = context.resources.getDimensionPixelSize(R.dimen.row_title_min)
rowMaxLineSize = context.resources.getDimensionPixelSize(R.dimen.row_vert_line_max_height)
rowMinLineSize = context.resources.getDimensionPixelSize(R.dimen.row_vert_line_min_height)
interpo = DecelerateInterpolator(10f);
buildRows()
}
private fun goToScene(vg: ViewGroup, layoutResId: Int, animate: Boolean) {
if (animate && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
var scene = Scene.getSceneForLayout(vg, layoutResId, ctx)
TransitionManager.go(scene, AutoTransition());
} else {
vg.removeAllViews()
LayoutInflater.from(ctx).inflate(layoutResId, vg, true)
}
}
@Suppress("DEPRECATION")
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (holder is ChainTodayWithStatsVh) {
if (chain.chainContainsToday()) {
if (holder.statsContainer == null) {
goToScene(holder.sceneRoot, R.layout.include_row_chain_today_with_stats_checked, todayChainAnimFlag)
holder.rebindViews()
}
holder.xview.setOnClickListener(null)
holder.xview.isClickable = false
holder.xview.boxToXPercentage = 1f
holder.xview.setColors(chain.color, ctx.resources.getColor(R.color.material_grey))
holder.todayTitleTv.invalidate()
holder.timeTv?.text = chain.newestDate?.toString(dtformat3)
holder.currentDayCountTv?.text = "" + chain.chainLength
holder.currentDayLabelTv?.text = ctx.resources.getQuantityString(R.plurals.days_and_counting, chain.chainLength)
holder.bestInChainCountTv?.text = "" + chain.longestRun
holder.bestAllChainsCountTv?.text = "" + ChainMaster.getLongestRunOfAllChains()
todayChainAnimFlag = false
} else {
if (holder.motivationBlurbTv == null) {
goToScene(holder.sceneRoot, R.layout.include_row_chain_today_with_stats_unchecked,todayChainAnimFlag)
holder.rebindViews()
}
holder.todayTitleTv.invalidate()
holder.xview.isClickable = true
holder.xview.setColors(chain.color, ctx.resources.getColor(R.color.material_grey))
holder.xview.boxToXPercentage = 0f
holder.xview.setOnClickListener {
//update data
chain.addNowToChain();
chainUpdateListener?.onChainUpdated(chain)
//start anim
var start = if (holder.xview.boxToXPercentage == 1f) 1f else 0f;
var end = if (holder.xview.boxToXPercentage == 1f) 0f else 1f;
holder.xview.boxToXPercentage = start;
var animator = ValueAnimator.ofFloat(start, end)
animator.addUpdateListener { anim ->
holder.xview.boxToXPercentage = anim.animatedFraction
}
animator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
todayChainAnimFlag = true
buildRows()
}
})
animator.interpolator = AccelerateDecelerateInterpolator()
animator.setDuration(700)
animator.start()
}
}
}
if (holder is ChainLinkVh) {
var titleHeight = Math.max(rowMinTitleSize, rowMaxTitleSize - position).toFloat()//rowMinTitleSize + (floatDepth * (rowMaxTitleSize - rowMinTitleSize))
var data = rows[position] as RowChainLink
//var headingTypeface = rowHeadingTypeface
holder.itemView.setOnClickListener(null)
holder.xview.setBox(false)
holder.xview.setColors(chain.color, ctx.resources.getColor(R.color.material_grey))
if (holder.tv1.textSize != titleHeight) {
holder.tv1.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleHeight)
}
val dateStr = if (data.dateTime.toLocalDate().plusDays(1).isEqual(LocalDate.now())) {
ctx.getText(R.string.yesterday)
} else if (Days.daysBetween(data.dateTime.toLocalDate(), LocalDate.now()).days < 7) {
data.dateTime.toString(dtformat1)
} else {
data.dateTime.toString(dtformat2)
}
val timeStr = data.dateTime.toString(dtformat3)
val depth = chain.chainLength - chain.chainDepth(data.dateTime)
holder.tv1.text = "" + depth
holder.tv2.text = "$dateStr\n$timeStr";
}
if (holder is VertLineVh) {
var lineHeight = Math.max(rowMinLineSize, rowMaxLineSize - position).toFloat()
var data = rows.get(position) as RowChainLine
if (holder.vertLine.layoutParams != null && holder.vertLine.layoutParams.height != lineHeight.toInt()) {
holder.vertLine.layoutParams.height = lineHeight.toInt()
holder.vertLine.layoutParams = holder.vertLine.layoutParams
}
holder.vertLine.setBackgroundColor(chain.color)
holder.vertLine.visibility = if (data.invisible) View.INVISIBLE else View.VISIBLE;
}
if (holder is RowFirstDayMessageVh) {
//nothing to do
}
if (holder is ChainAdVh) {
requestAd(holder.adview)
}
}
override fun getItemCount(): Int {
return rows.size;
}
override fun getItemViewType(position: Int): Int {
if (rows[position] is RowChainLine) {
return VERTICAL_LINE;
} else if (rows.get(position) is RowChainLink) {
return CHAIN_LINK;
} else if (rows.get(position) is RowChainToday) {
return CHAIN_TODAY;
} else if (rows.get(position) is RowFirstDayMessage) {
return CHAIN_FIRST_DAY_MESSAGE
} else if (rows.get(position) is RowChainAd) {
return CHAIN_AD
}
return -1;
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder? {
var inflater = LayoutInflater.from(parent?.context);
if (viewType == CHAIN_LINK) {
var chainView: View? = inflater.inflate(R.layout.card_chain_link_center, parent, false);
var vh = ChainLinkVh(chainView);
return vh;
}
if (viewType == VERTICAL_LINE) {
var lineView = inflater.inflate(R.layout.row_vertical_line_center, parent, false);
return VertLineVh(lineView);
}
if (viewType == CHAIN_TODAY) {
var view = inflater.inflate(R.layout.row_chain_today_with_stats, parent, false)
var vh = ChainTodayWithStatsVh(view);
return vh;
}
if (viewType == CHAIN_FIRST_DAY_MESSAGE) {
var messageView = inflater.inflate(R.layout.row_first_day_message, parent, false)
var vh = RowFirstDayMessageVh(messageView)
return vh
}
if (viewType == CHAIN_AD) {
var ad = inflater.inflate(R.layout.card_chain_ad, parent, false)
var vh = ChainAdVh(ad)
return vh;
}
return null;
}
public fun updateChain(chn: Chain) {
chain = chn
todayChainAnimFlag = false
buildRows()
//NOTE: buildRows() makes some assumptions, when we set a new chain, we should update all rows
notifyDataSetChanged()
}
public fun buildRows() {
var freshRows = ArrayList<Row>()
if (chain.chainLength > 0) {
var dateTimes = ArrayList<LocalDateTime>(chain.dateTimes);
for (dt in dateTimes) {
//TODAY has it's own special thing going on
if (dt.toLocalDate().isBefore(LocalDate.now())) {
if (freshRows.size > 0) {
freshRows.add(RowChainLine(false))
}
freshRows.add(RowChainLink(dt))
}
}
if (freshRows.size > 0) {
freshRows.add(RowChainLine(true))
}
}
if (freshRows.size > 0) {
freshRows.add(0, RowChainLine(false))
}
freshRows.add(0, RowChainToday());
if (freshRows.size == 1 && chain.chainContainsToday()) {
freshRows.add(RowFirstDayMessage())
}
if (!BuildConfig.IS_PRO) {
if (chain.chainLength < chain.longestRun) {
Timber.d("Adding RowChainAd()")
freshRows.add(1, RowChainLine(false))
freshRows.add(2, RowChainAd())
}
} else {
Timber.d("Skipping RowChainAd()")
}
rows = freshRows
//TODO: Be smarter about this to get free animations.
notifyDataSetChanged()
}
open class Row() {
}
class RowChainLink(dt: LocalDateTime) : Row() {
val dateTime = dt
}
class RowChainLine(invis: Boolean) : Row() {
val invisible = invis
}
class RowChainToday() : Row() {
}
class RowFirstDayMessage() : Row() {
}
class RowChainAd() : Row() {
}
/*
ADD STUFF
*/
private fun requestAd(adview: AdView?) {
if (!BuildConfig.IS_PRO) {
var adRequest = with(AdRequest.Builder()) {
if (BuildConfig.IS_DEBUG_BUILD) {
addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
var andId = Settings.Secure.getString(ctx.contentResolver, Settings.Secure.ANDROID_ID)
var hash = md5(andId).toUpperCase()
Timber.d("Adding test device. hash:" + hash)
addTestDevice(hash)
}
build()
}
adview?.loadAd(adRequest);
}
}
private fun md5(s: String): String {
try {
var digest = MessageDigest.getInstance("MD5")
digest.update(s.toByteArray())
var messageDigest = digest.digest()
var hexString = StringBuffer()
for (i in messageDigest.indices) {
var h = Integer.toHexString(0xFF and messageDigest[i].toInt())
while (h.length < 2)
h = "0" + h
hexString.append(h)
}
return hexString.toString()
} catch(ex: Exception) {
Timber.e(ex, "Fail in md5");
}
return ""
}
} | apache-2.0 |
stoyicker/dinger | data/src/main/kotlin/data/tinder/recommendation/RecommendationUserTeaserEntity.kt | 1 | 447 | package data.tinder.recommendation
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Index
import android.arch.persistence.room.PrimaryKey
@Entity(indices = [Index("id")])
internal class RecommendationUserTeaserEntity(
@PrimaryKey
var id: String,
var description: String,
var type: String?) {
companion object {
fun createId(description: String, type: String?) = "${description}_$type"
}
}
| mit |
androidx/androidx | core/core-remoteviews/src/androidTest/java/androidx/core/widget/TestAppWidgetProvider.kt | 3 | 747 | /*
* 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.core.widget
import android.appwidget.AppWidgetProvider
public class TestAppWidgetProvider : AppWidgetProvider() | apache-2.0 |
androidx/androidx | compose/ui/ui-tooling/src/androidAndroidTest/kotlin/androidx/compose/ui/tooling/animation/TransitionComposeAnimationTest.kt | 3 | 4560 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.tooling.animation
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.tooling.ComposeAnimationType
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.tooling.animation.clock.TransitionClockTest
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
class TransitionComposeAnimationTest {
@get:Rule
val rule = createComposeRule()
@Test
fun parseIntComposeAnimation() {
val targetState by mutableStateOf(1)
rule.setContent {
val transition = updateTransition(targetState, label = "TestTransition")
val composeAnimation = transition.parse()!!
Assert.assertEquals("TestTransition", composeAnimation.label)
Assert.assertEquals(ComposeAnimationType.TRANSITION_ANIMATION, composeAnimation.type)
Assert.assertEquals(transition, composeAnimation.animationObject)
Assert.assertEquals(setOf(targetState), composeAnimation.states)
}
}
@Test
fun parseNullableIntComposeAnimation() {
val targetState: MutableState<Int?> = mutableStateOf(1)
rule.setContent {
val transition = updateTransition(targetState, label = "TestTransition")
val composeAnimation = transition.parse()!!
Assert.assertEquals("TestTransition", composeAnimation.label)
Assert.assertEquals(ComposeAnimationType.TRANSITION_ANIMATION, composeAnimation.type)
Assert.assertEquals(transition, composeAnimation.animationObject)
Assert.assertEquals(setOf(targetState), composeAnimation.states)
}
}
@Test
fun parseEnumComposeAnimation() {
val targetState by mutableStateOf(TransitionClockTest.EnumState.One)
rule.setContent {
val transition = updateTransition(targetState, label = "TestTransition")
val composeAnimation = transition.parse()!!
Assert.assertEquals("TestTransition", composeAnimation.label)
Assert.assertEquals(ComposeAnimationType.TRANSITION_ANIMATION, composeAnimation.type)
Assert.assertEquals(transition, composeAnimation.animationObject)
Assert.assertEquals(
setOf(
TransitionClockTest.EnumState.One,
TransitionClockTest.EnumState.Two,
TransitionClockTest.EnumState.Three
),
composeAnimation.states
)
}
}
@Test
fun parseStringComposeAnimation() {
val targetState by mutableStateOf("State")
rule.setContent {
val transition = updateTransition(targetState, label = "TestTransition")
val composeAnimation = transition.parse()!!
Assert.assertEquals("TestTransition", composeAnimation.label)
Assert.assertEquals(ComposeAnimationType.TRANSITION_ANIMATION, composeAnimation.type)
Assert.assertEquals(transition, composeAnimation.animationObject)
Assert.assertEquals(setOf("State"), composeAnimation.states)
}
}
@Test
fun parseCustomComposeAnimation() {
val targetState by mutableStateOf(TransitionClockTest.CustomState(0))
rule.setContent {
val transition = updateTransition(targetState, label = "TestTransition")
val composeAnimation = transition.parse()!!
Assert.assertEquals("TestTransition", composeAnimation.label)
Assert.assertEquals(ComposeAnimationType.TRANSITION_ANIMATION, composeAnimation.type)
Assert.assertEquals(transition, composeAnimation.animationObject)
Assert.assertEquals(setOf(TransitionClockTest.CustomState(0)), composeAnimation.states)
}
}
} | apache-2.0 |
Gazer/localshare | app/src/main/java/ar/com/p39/localshare/receiver/presenters/DownloadPresenter.kt | 1 | 3569 | package ar.com.p39.localshare.receiver.presenters
import android.util.Log
import ar.com.p39.localshare.common.presenters.Presenter
import ar.com.p39.localshare.receiver.models.DownloadFile
import ar.com.p39.localshare.receiver.models.DownloadList
import ar.com.p39.localshare.receiver.network.SharerClient
import ar.com.p39.localshare.receiver.views.DownloadView
import okhttp3.OkHttpClient
import okhttp3.Request
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.BufferedInputStream
import java.io.InputStream
class DownloadPresenter(val client: SharerClient, val httpClient: OkHttpClient) : Presenter<DownloadView>() {
lateinit var downloadFiles: DownloadList
fun inspectUrl(bssid: String) {
client.getShareInfo()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
list: DownloadList ->
if (bssid != list.ssid) {
view()?.connectToWifi(list.ssid)
} else {
downloadFiles = list
view()?.showFiles(list.files)
}
},
{
error ->
Log.e("Download", "Connect failed : $error")
view()?.showError("Connect failed : $error")
}
)
}
fun startDownload() {
view()?.disableUi()
Observable.just((downloadFiles as DownloadList).files)
.flatMapIterable { it }
.flatMap { file ->
file.status = 1
view()?.downloadStart()
downloadFileObserver(file)
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
file: DownloadFile ->
if (file.data != null) {
Log.d("Download", "Completed")
file.status = 2
view()?.downloadCompleted(file.data as ByteArray)
}
},
{
error ->
Log.e("Download", "Connect failed to url : $error")
view()?.showError("Connect failed to url")
},
{
view()?.downloadFinished()
}
)
}
private fun downloadFileObserver(file: DownloadFile): Observable<DownloadFile> {
return Observable.defer {
Observable.create(Observable.OnSubscribe<DownloadFile> { subscriber ->
Log.d("Download", "Map : $file")
val request = Request.Builder().url(file.url).build();
val response = httpClient.newCall(request).execute();
val stream: InputStream = response.body().byteStream();
val input: BufferedInputStream = BufferedInputStream(stream);
file.data = input.readBytes()
subscriber.onNext(file)
subscriber.onCompleted()
stream.close()
input.close()
}).subscribeOn(Schedulers.io())
}
}
}
| apache-2.0 |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/note/NoteAdapter.kt | 1 | 3348 | /*
* Copyright (c) 2015 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.note
import android.view.View
import android.view.ViewGroup
import org.andstatus.app.R
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.timeline.TimelineActivity
import org.andstatus.app.timeline.TimelineData
import org.andstatus.app.util.MyUrlSpan
/**
* @author [email protected]
*/
class NoteAdapter(contextMenu: NoteContextMenu, listData: TimelineData<NoteViewItem>) :
BaseNoteAdapter<NoteViewItem>(contextMenu, listData) {
private var positionPrev = -1
private var itemNumberShownCounter = 0
private val TOP_TEXT: String?
override fun showAvatarEtc(view: ViewGroup, item: NoteViewItem) {
if (showAvatars) {
showAvatar(view, item)
} else {
val noteView = view.findViewById<View?>(R.id.note_indented)
noteView?.setPadding(dpToPixes(2), 0, dpToPixes(6), dpToPixes(2))
}
}
private fun preloadAttachments(position: Int) {
if (positionPrev < 0 || position == positionPrev) {
return
}
var positionToPreload = position
for (i in 0..4) {
positionToPreload = positionToPreload + if (position > positionPrev) 1 else -1
if (positionToPreload < 0 || positionToPreload >= count) {
break
}
val item = getItem(positionToPreload)
if (!preloadedImages.contains(item.getNoteId())) {
preloadedImages.add(item.getNoteId())
item.attachedImageFiles.preloadImagesAsync()
break
}
}
}
override fun showNoteNumberEtc(view: ViewGroup, item: NoteViewItem, position: Int) {
preloadAttachments(position)
val text: String? = when (position) {
0 -> if (mayHaveYoungerPage()) "1" else TOP_TEXT
1, 2 -> Integer.toString(position + 1)
else -> if (itemNumberShownCounter < 3) Integer.toString(position + 1) else ""
}
MyUrlSpan.showText(view, R.id.note_number, text, linkify = false, showIfEmpty = false)
itemNumberShownCounter++
positionPrev = position
}
override fun onClick(v: View) {
var handled = false
if (MyPreferences.isLongPressToOpenContextMenu()) {
val item = getItem(v)
if (TimelineActivity::class.java.isAssignableFrom(contextMenu.getActivity().javaClass)) {
(contextMenu.getActivity() as TimelineActivity<*>).onItemClick(item)
handled = true
}
}
if (!handled) {
super.onClick(v)
}
}
init {
TOP_TEXT = myContext.context.getText(R.string.top).toString()
}
}
| apache-2.0 |
JetBrains/kotlin-web-site | .teamcity/builds/apiReferences/kotlinx/coroutines/KotlinxCoroutinesBuildApiReference.kt | 1 | 715 | package builds.apiReferences.kotlinx.coroutines
import builds.apiReferences.dependsOnDokkaTemplate
import builds.apiReferences.templates.BuildApiReference
import jetbrains.buildServer.configs.kotlin.BuildType
import jetbrains.buildServer.configs.kotlin.triggers.vcs
object KotlinxCoroutinesBuildApiReference: BuildType({
name = "kotlinx.coroutines API reference"
templates(BuildApiReference)
params {
param("release.tag", BuildParams.KOTLINX_COROUTINES_RELEASE_TAG)
}
vcs {
root(builds.apiReferences.vcsRoots.KotlinxCoroutines)
}
triggers {
vcs {
branchFilter = "+:<default>"
}
}
dependencies {
dependsOnDokkaTemplate(KotlinxCoroutinesPrepareDokkaTemplates)
}
}) | apache-2.0 |
CruGlobal/android-gto-support | gto-support-androidx-compose-material3/src/main/kotlin/org/ccci/gto/android/common/androidx/compose/material3/Color.kt | 1 | 200 | package org.ccci.gto.android.common.androidx.compose.material3
import androidx.compose.ui.graphics.Color
fun Color.disabledAlphaIf(state: Boolean) = if (state) copy(alpha = DisabledAlpha) else this
| mit |
Tvede-dk/CommonsenseAndroidKotlin | system/src/test/kotlin/com/commonsense/android/kotlin/system/imaging/PictureRetriverTest.kt | 1 | 476 | package com.commonsense.android.kotlin.system.imaging
import org.junit.*
import org.junit.jupiter.api.Test
/**
*
*/
internal class PictureRetriverTest {
@Ignore
@Test
fun getThumbnail() {
}
@Ignore
@Test
fun setThumbnail() {
}
@Ignore
@Test
fun useCamera() {
}
@Ignore
@Test
fun useGallery() {
}
@Ignore
@Test
fun onActivityResult() {
}
@Ignore
@Test
fun getImage() {
}
} | mit |
Tvede-dk/CommonsenseAndroidKotlin | base/src/test/kotlin/com/commonsense/android/kotlin/base/extensions/generic/ForeachKtTest.kt | 1 | 268 | package com.commonsense.android.kotlin.base.extensions.generic
import org.junit.*
import org.junit.jupiter.api.Test
/**
*
*/
internal class ForeachKtTest {
@Ignore
@Test
fun forEach2() {
}
@Ignore
@Test
fun forEach2Indexed() {
}
} | mit |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/stubs/LuaClosureExprStub.kt | 2 | 2756 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.stubs
import com.intellij.psi.stubs.IndexSink
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.stubs.StubInputStream
import com.intellij.psi.stubs.StubOutputStream
import com.tang.intellij.lua.psi.LuaClosureExpr
import com.tang.intellij.lua.psi.LuaElementTypes
import com.tang.intellij.lua.psi.LuaParamInfo
import com.tang.intellij.lua.psi.impl.LuaClosureExprImpl
import com.tang.intellij.lua.psi.overloads
import com.tang.intellij.lua.ty.IFunSignature
import com.tang.intellij.lua.ty.ITy
import com.tang.intellij.lua.ty.TyParameter
class LuaClosureExprType : LuaStubElementType<LuaClosureExprStub, LuaClosureExpr>("CLOSURE_EXPR") {
override fun indexStub(stub: LuaClosureExprStub, sink: IndexSink) {
}
override fun serialize(stub: LuaClosureExprStub, outputStream: StubOutputStream) {
outputStream.writeParamInfoArray(stub.params)
outputStream.writeSignatures(stub.overloads)
}
override fun createPsi(stub: LuaClosureExprStub): LuaClosureExpr {
return LuaClosureExprImpl(stub, this)
}
override fun createStub(expr: LuaClosureExpr, parentStub: StubElement<*>?): LuaClosureExprStub {
val varargTy = expr.varargType
val params = expr.params
val overloads = expr.overloads
return LuaClosureExprStub(null, varargTy, params, overloads, parentStub)
}
override fun deserialize(inputStream: StubInputStream, parentStub: StubElement<*>?): LuaClosureExprStub {
val params = inputStream.readParamInfoArray()
val overloads = inputStream.readSignatures()
return LuaClosureExprStub(null, null, params, overloads, parentStub)
}
}
class LuaClosureExprStub(
override val returnDocTy: ITy?,
override val varargTy: ITy?,
override val params: Array<LuaParamInfo>,
override val overloads: Array<IFunSignature>,
parent: StubElement<*>?
) : LuaStubBase<LuaClosureExpr>(parent, LuaElementTypes.CLOSURE_EXPR), LuaFuncBodyOwnerStub<LuaClosureExpr>, LuaExprStub<LuaClosureExpr> {
override val tyParams: Array<TyParameter>
get() = emptyArray()
} | apache-2.0 |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/base/dto/BaseObjectCount.kt | 1 | 1612 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.base.dto
import com.google.gson.annotations.SerializedName
import kotlin.Int
/**
* @param count - Items count
*/
data class BaseObjectCount(
@SerializedName("count")
val count: Int? = null
)
| mit |
inorichi/tachiyomi-extensions | src/fr/mangakawaii/src/eu/kanade/tachiyomi/extension/fr/mangakawaii/MangaKawaii.kt | 1 | 7688 | package eu.kanade.tachiyomi.extension.fr.mangakawaii
import android.net.Uri
import android.util.Base64
import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.TimeUnit
import kotlin.math.absoluteValue
import kotlin.random.Random
/**
* Heavily customized MyMangaReaderCMS source
*/
class MangaKawaii : ParsedHttpSource() {
override val name = "Mangakawaii"
override val baseUrl = "https://www.mangakawaii.net"
val cdnUrl = "https://cdn.mangakawaii.net"
override val lang = "fr"
override val supportsLatest = true
private val rateLimitInterceptor = RateLimitInterceptor(1) // 1 request per second
override val client: OkHttpClient = network.cloudflareClient.newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addNetworkInterceptor(rateLimitInterceptor)
.build()
protected open val userAgentRandomizer1 = "${Random.nextInt(9).absoluteValue}"
protected open val userAgentRandomizer2 = "${Random.nextInt(10, 99).absoluteValue}"
protected open val userAgentRandomizer3 = "${Random.nextInt(100, 999).absoluteValue}"
override fun headersBuilder(): Headers.Builder = Headers.Builder()
.add(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/8$userAgentRandomizer1.0.4$userAgentRandomizer3.1$userAgentRandomizer2 Safari/537.36"
)
// Popular
override fun popularMangaRequest(page: Int) = GET(baseUrl, headers)
override fun popularMangaSelector() = "a.hot-manga__item"
override fun popularMangaNextPageSelector(): String? = null
override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply {
title = element.select("div.hot-manga__item-caption").select("div.hot-manga__item-name").text().trim()
setUrlWithoutDomain(element.select("a").attr("href"))
thumbnail_url = "$cdnUrl/uploads" + element.select("a").attr("href") + "/cover/cover_250x350.jpg"
}
// Latest
override fun latestUpdatesRequest(page: Int) = GET(baseUrl, headers)
override fun latestUpdatesSelector() = ".section__list-group li div.section__list-group-left"
override fun latestUpdatesNextPageSelector(): String? = null
override fun latestUpdatesFromElement(element: Element): SManga = SManga.create().apply {
title = element.select("a").attr("title")
setUrlWithoutDomain(element.select("a").attr("href"))
thumbnail_url = "$cdnUrl/uploads" + element.select("a").attr("href") + "/cover/cover_250x350.jpg"
}
// Search
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val uri = Uri.parse("$baseUrl/search").buildUpon()
.appendQueryParameter("query", query)
.appendQueryParameter("search_type", "manga")
return GET(uri.toString(), headers)
}
override fun searchMangaSelector() = "h1 + ul a[href*=manga]"
override fun searchMangaNextPageSelector(): String? = null
override fun searchMangaFromElement(element: Element): SManga = SManga.create().apply {
title = element.select("a").text().trim()
setUrlWithoutDomain(element.select("a").attr("href"))
thumbnail_url = "$cdnUrl/uploads" + element.select("a").attr("href") + "/cover/cover_250x350.jpg"
}
// Manga details
override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply {
thumbnail_url = document.select("div.manga-view__header-image").select("img").attr("abs:src")
description = document.select("dd.text-justify.text-break").text()
author = document.select("a[href*=author]").text()
artist = document.select("a[href*=artist]").text()
genre = document.select("a[href*=category]").joinToString { it.text() }
status = when (document.select("span.badge.bg-success.text-uppercase").text()) {
"En Cours" -> SManga.ONGOING
"Terminé" -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
}
// Chapter list
override fun chapterListSelector() = throw Exception("Not used")
override fun chapterFromElement(element: Element): SChapter = throw Exception("Not used")
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
var widgetDocument = document
val widgetPageListUrl = Regex("""['"](/arrilot/load-widget.*?)['"]""").find(document.toString())?.groupValues?.get(1)
if (widgetPageListUrl != null) {
widgetDocument = client.newCall(GET("$baseUrl$widgetPageListUrl", headers)).execute().asJsoup()
}
return widgetDocument.select("tr[class*=volume-]:has(td)").map {
SChapter.create().apply {
url = it.select("td.table__chapter").select("a").attr("href")
name = it.select("td.table__chapter").select("span").text().trim()
chapter_number = it.select("td.table__chapter").select("span").text().substringAfter("Chapitre").replace(Regex("""[,-]"""), ".").trim().toFloatOrNull()
?: -1F
date_upload = it.select("td.table__date").firstOrNull()?.text()?.let { parseDate(it) }
?: 0
scanlator = document.select("[itemprop=translator] a").joinToString { it.text().replace(Regex("""[\[\]]"""), "") }
}
}
}
private fun parseDate(date: String): Long {
return SimpleDateFormat("dd.MM.yyyy", Locale.US).parse(date)?.time ?: 0L
}
// Pages
override fun pageListParse(document: Document): List<Page> {
val selectorEncoded1 = "Wkdim" + "gsai" + "mgWQyV2lkMm" + "xrS2img" + "ppZDFoY" + "kd4ZElHaW" +
"RsdimgFp6cHVi" + "M1FvVzNOeVl5" + "bimgzlpZG" + "lkWjJsbVhT" + "a3imgNJQzVq" + "YjI1MFlpZFd" +
"saWR1WlhJdFi" + "mgpteDFhV1FnTGi" + "mg5KdmlkZHlC" + "a2FYWimgTZiaW" + "imgRtOTBL" + "QzV0ZUMxaim" +
"gGRYUnZpZEtT" + "QTZibTki" + "mgwS0imgRwdm" + "JteGlkimgNU" + "xXTm9hV3himgr" + "aWRLU0JwYldjNm" + "JtOTBpZEti" +
"mgGdHpp" + "ZGNtTXFQimg" + "V2RwWml" + "kbDBw"
val selectorEncoded2 = String(Base64.decode(selectorEncoded1.replace("img", ""), Base64.DEFAULT))
val selectorDecoded = String(Base64.decode(selectorEncoded2.replace("id", ""), Base64.DEFAULT))
val elements = document.select(selectorDecoded)
val pages = mutableListOf<Page>()
var j = 0
for (i in 0 until elements.count()) {
if (elements[i].attr("src").trim().startsWith(cdnUrl)) {
pages.add(Page(j, document.location(), elements[i].attr("src").trim()))
++j
}
}
return pages
}
override fun imageUrlParse(document: Document): String = throw Exception("Not used")
override fun imageRequest(page: Page): Request {
val imgHeaders = headersBuilder().apply {
add("Referer", page.url)
}.build()
return GET(page.imageUrl!!, imgHeaders)
}
}
| apache-2.0 |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/feedback/FeedbackActivity.kt | 1 | 10410 | package de.tum.`in`.tumcampusapp.component.tumui.feedback
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.location.Location
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL
import com.google.android.gms.location.LocationRequest
import com.jakewharton.rxbinding3.widget.checkedChanges
import com.jakewharton.rxbinding3.widget.textChanges
import com.patloew.rxlocation.RxLocation
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.other.generic.activity.BaseActivity
import de.tum.`in`.tumcampusapp.component.tumui.feedback.FeedbackPresenter.Companion.PERMISSION_CAMERA
import de.tum.`in`.tumcampusapp.component.tumui.feedback.FeedbackPresenter.Companion.PERMISSION_FILES
import de.tum.`in`.tumcampusapp.component.tumui.feedback.FeedbackPresenter.Companion.PERMISSION_LOCATION
import de.tum.`in`.tumcampusapp.component.tumui.feedback.FeedbackPresenter.Companion.REQUEST_GALLERY
import de.tum.`in`.tumcampusapp.component.tumui.feedback.FeedbackPresenter.Companion.REQUEST_TAKE_PHOTO
import de.tum.`in`.tumcampusapp.utils.Const
import de.tum.`in`.tumcampusapp.utils.Utils
import io.reactivex.Observable
import kotlinx.android.synthetic.main.activity_feedback.*
import java.io.File
import javax.inject.Inject
class FeedbackActivity : BaseActivity(R.layout.activity_feedback), FeedbackContract.View {
private lateinit var thumbnailsAdapter: FeedbackThumbnailsAdapter
private var progressDialog: AlertDialog? = null
@Inject
lateinit var presenter: FeedbackContract.Presenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val lrzId = Utils.getSetting(this, Const.LRZ_ID, "")
injector.feedbackComponent()
.lrzId(lrzId)
.build()
.inject(this)
presenter.attachView(this)
if (savedInstanceState != null) {
presenter.onRestoreInstanceState(savedInstanceState)
}
initIncludeLocation()
initPictureGallery()
if (savedInstanceState == null) {
presenter.initEmail()
}
initIncludeEmail()
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
presenter.onSaveInstanceState(outState)
}
private fun initPictureGallery() {
imageRecyclerView.layoutManager = LinearLayoutManager(this, HORIZONTAL, false)
val imagePaths = presenter.feedback.picturePaths
val thumbnailSize = resources.getDimension(R.dimen.thumbnail_size).toInt()
thumbnailsAdapter = FeedbackThumbnailsAdapter(imagePaths, { onThumbnailRemoved(it) }, thumbnailSize)
imageRecyclerView.adapter = thumbnailsAdapter
addImageButton.setOnClickListener { showImageOptionsDialog() }
}
private fun onThumbnailRemoved(path: String) {
val builder = AlertDialog.Builder(this)
val view = View.inflate(this, R.layout.picture_dialog, null)
val imageView = view.findViewById<ImageView>(R.id.feedback_big_image)
imageView.setImageURI(Uri.fromFile(File(path)))
builder.setView(view)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.feedback_remove_image) { _, _ -> removeThumbnail(path) }
val dialog = builder.create()
dialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background)
dialog.show()
}
private fun removeThumbnail(path: String) {
presenter.removeImage(path)
}
private fun showImageOptionsDialog() {
val options = arrayOf(getString(R.string.feedback_take_picture), getString(R.string.gallery))
val alertDialog = AlertDialog.Builder(this)
.setTitle(R.string.feedback_add_picture)
.setItems(options) { _, index -> presenter.onImageOptionSelected(index) }
.setNegativeButton(R.string.cancel, null)
.create()
alertDialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background)
alertDialog.show()
}
override fun getMessage(): Observable<String> =
feedbackMessage.textChanges().map { it.toString() }
override fun getEmail(): Observable<String> =
customEmailInput.textChanges().map { it.toString() }
override fun getTopicInput(): Observable<Int> = radioButtonsGroup.checkedChanges()
override fun getIncludeEmail(): Observable<Boolean> = includeEmailCheckbox.checkedChanges()
override fun getIncludeLocation(): Observable<Boolean> = includeLocationCheckBox.checkedChanges()
@SuppressLint("MissingPermission")
override fun getLocation(): Observable<Location> = RxLocation(this).location().updates(LocationRequest.create())
override fun setFeedback(message: String) {
feedbackMessage.setText(message)
}
override fun openCamera(intent: Intent) {
startActivityForResult(intent, REQUEST_TAKE_PHOTO)
}
override fun openGallery(intent: Intent) {
startActivityForResult(intent, REQUEST_GALLERY)
}
@RequiresApi(api = Build.VERSION_CODES.M)
override fun showPermissionRequestDialog(permission: String, requestCode: Int) {
requestPermissions(arrayOf(permission), requestCode)
}
private fun initIncludeLocation() {
includeLocationCheckBox.isChecked = presenter.feedback.includeLocation
}
private fun initIncludeEmail() {
val feedback = presenter.feedback
val email = feedback.email
includeEmailCheckbox.isChecked = feedback.includeEmail
if (presenter.lrzId.isEmpty()) {
includeEmailCheckbox.text = getString(R.string.feedback_include_email)
customEmailInput.setText(email)
} else {
includeEmailCheckbox.text = getString(R.string.feedback_include_email_tum_id, email)
}
}
override fun showEmailInput(show: Boolean) {
customEmailLayout.isVisible = show
}
fun onSendClicked(view: View) {
presenter.onSendFeedback()
}
override fun showEmptyMessageError() {
feedbackMessage.error = getString(R.string.feedback_empty)
}
override fun showWarning(message: String) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
override fun showDialog(title: String, message: String) {
val dialog = AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, null)
.create()
dialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background)
dialog.show()
}
override fun showProgressDialog() {
progressDialog = AlertDialog.Builder(this)
.setTitle(R.string.feedback_sending)
.setView(ProgressBar(this))
.setCancelable(false)
.setNeutralButton(R.string.cancel, null)
.create()
progressDialog?.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background)
progressDialog?.show()
}
override fun showSendErrorDialog() {
progressDialog?.dismiss()
val errorDialog = AlertDialog.Builder(this)
.setMessage(R.string.feedback_sending_error)
.setIcon(R.drawable.ic_error_outline)
.setPositiveButton(R.string.try_again) { _, _ -> presenter.feedback }
.setNegativeButton(R.string.cancel, null)
.create()
errorDialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background)
errorDialog.show()
}
override fun onFeedbackSent() {
progressDialog?.dismiss()
Toast.makeText(this, R.string.feedback_send_success, LENGTH_SHORT).show()
finish()
}
override fun showSendConfirmationDialog() {
val alertDialog = AlertDialog.Builder(this)
.setMessage(R.string.send_feedback_question)
.setPositiveButton(R.string.send) { _, _ -> presenter.onConfirmSend() }
.setNegativeButton(R.string.cancel, null)
.create()
alertDialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background)
alertDialog.show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode != Activity.RESULT_OK) {
return
}
when (requestCode) {
REQUEST_TAKE_PHOTO -> presenter.onNewImageTaken()
REQUEST_GALLERY -> {
val filePath = data?.data
presenter.onNewImageSelected(filePath)
}
}
}
override fun onImageAdded(path: String) {
thumbnailsAdapter.addImage(path)
}
override fun onImageRemoved(position: Int) {
thumbnailsAdapter.removeImage(position)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (grantResults.isEmpty()) {
return
}
val isGranted = grantResults[0] == PERMISSION_GRANTED
when (requestCode) {
PERMISSION_LOCATION -> {
includeLocationCheckBox.isChecked = isGranted
if (isGranted) {
presenter.listenForLocation()
}
}
PERMISSION_CAMERA -> {
if (isGranted) {
presenter.takePicture()
}
}
PERMISSION_FILES -> {
if (isGranted) {
presenter.openGallery()
}
}
}
}
override fun onDestroy() {
presenter.detachView()
super.onDestroy()
}
}
| gpl-3.0 |
ligee/kotlin-jupyter | src/main/kotlin/org/jetbrains/kotlinx/jupyter/repl/ContextUpdater.kt | 1 | 3189 | package org.jetbrains.kotlinx.jupyter.repl
import jupyter.kotlin.KotlinContext
import jupyter.kotlin.KotlinFunctionInfo
import jupyter.kotlin.KotlinVariableInfo
import org.slf4j.LoggerFactory
import java.lang.reflect.Field
import java.util.HashSet
import kotlin.reflect.jvm.kotlinFunction
import kotlin.reflect.jvm.kotlinProperty
import kotlin.script.experimental.jvm.BasicJvmReplEvaluator
import kotlin.script.experimental.jvm.KJvmEvaluatedSnippet
import kotlin.script.experimental.util.LinkedSnippet
/**
* ContextUpdater updates current user-defined functions and variables
* to use in completion and KotlinContext.
*/
class ContextUpdater(val context: KotlinContext, private val evaluator: BasicJvmReplEvaluator) {
private var lastProcessedSnippet: LinkedSnippet<KJvmEvaluatedSnippet>? = null
fun update() {
try {
var lastSnippet = evaluator.lastEvaluatedSnippet
val newSnippets = mutableListOf<Any>()
while (lastSnippet != lastProcessedSnippet && lastSnippet != null) {
val line = lastSnippet.get().result.scriptInstance
if (line != null) {
newSnippets.add(line)
}
lastSnippet = lastSnippet.previous
}
newSnippets.reverse()
refreshVariables(newSnippets)
refreshMethods(newSnippets)
lastProcessedSnippet = evaluator.lastEvaluatedSnippet
} catch (e: ReflectiveOperationException) {
logger.error("Exception updating current variables", e)
} catch (e: NullPointerException) {
logger.error("Exception updating current variables", e)
}
}
private fun refreshMethods(lines: List<Any>) {
for (line in lines) {
val methods = line.javaClass.methods
for (method in methods) {
if (objectMethods.contains(method) || method.name == "main") {
continue
}
val function = method.kotlinFunction ?: continue
context.functions[function.name] = KotlinFunctionInfo(function, line)
}
}
}
@Throws(ReflectiveOperationException::class)
private fun refreshVariables(lines: List<Any>) {
for (line in lines) {
val fields = line.javaClass.declaredFields
findVariables(fields, line)
}
}
@Throws(IllegalAccessException::class)
private fun findVariables(fields: Array<Field>, o: Any) {
for (field in fields) {
val fieldName = field.name
if (fieldName.contains("$\$implicitReceiver") || fieldName.contains("script$")) {
continue
}
field.isAccessible = true
val value = field.get(o)
val descriptor = field.kotlinProperty
if (descriptor != null) {
context.vars[fieldName] = KotlinVariableInfo(value, descriptor, o)
}
}
}
companion object {
private val logger = LoggerFactory.getLogger(ContextUpdater::class.java)
private val objectMethods = HashSet(listOf(*Any::class.java.methods))
}
}
| apache-2.0 |
WonderBeat/vasilich | src/main/kotlin/com/vasilich/commands/bootstrap/ReactiveCommandInitializer.kt | 1 | 1261 | package com.vasilich.commands.bootstrap
import reactor.core.Observable
import javax.annotation.PostConstruct
import reactor.event.selector.Selectors
import reactor.event.Event
import reactor.function.Consumer
import org.springframework.core.Ordered
import org.slf4j.LoggerFactory
import com.vasilich.commands.api.Command
import com.vasilich.connectors.xmpp.Topics
/**
* Grabs all available commands, sorts them by priority and listens to events
* On event, passes it through the chain of commands, looking for the first one, that can process it
*/
public class ReactiveCommandInitializer (private val reactor: Observable,
private val command: Command,
private val topics: Topics = Topics()) {
val logger = LoggerFactory.getLogger(this.javaClass)!!;
PostConstruct
private fun makeReactive() {
reactor.on(Selectors.`$`(topics.receive), Consumer<Event<String>> {
val msg = it!!.getData()!!
val response = command execute msg
if(response != null) {
logger.debug("Chat: ${msg} -> ${response}")
reactor.notify(topics.send, Event.wrap(response))
}
})
}
}
| gpl-2.0 |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/subject/nine/CollectionModel.kt | 1 | 380 | package com.intfocus.template.subject.nine
import android.content.Context
import com.intfocus.template.model.callback.LoadDataCallback
/**
* @author liuruilin
* @data 2017/10/31
* @describe
*/
interface CollectionModel<out T> {
fun getData(ctx: Context,reportId: String, templateID: String, groupId: String, callback: LoadDataCallback<T>)
fun upload(ctx: Context)
}
| gpl-3.0 |
firebase/snippets-android | functions/app/src/main/java/devrel/firebase/google/com/functions/kotlin/MainActivity.kt | 1 | 4040 | package devrel.firebase.google.com.functions.kotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.Task
import com.google.firebase.functions.FirebaseFunctions
import com.google.firebase.functions.FirebaseFunctionsException
import com.google.firebase.functions.ktx.functions
import com.google.firebase.ktx.Firebase
class MainActivity : AppCompatActivity() {
// [START define_functions_instance]
private lateinit var functions: FirebaseFunctions
// [END define_functions_instance]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// [START initialize_functions_instance]
functions = Firebase.functions
// [END initialize_functions_instance]
}
fun emulatorSettings() {
// [START functions_emulator_connect]
// 10.0.2.2 is the special IP address to connect to the 'localhost' of
// the host computer from an Android emulator.
val functions = Firebase.functions
functions.useEmulator("10.0.2.2", 5001)
// [END functions_emulator_connect]
}
// [START function_add_numbers]
private fun addNumbers(a: Int, b: Int): Task<Int> {
// Create the arguments to the callable function, which are two integers
val data = hashMapOf(
"firstNumber" to a,
"secondNumber" to b
)
// Call the function and extract the operation from the result
return functions
.getHttpsCallable("addNumbers")
.call(data)
.continueWith { task ->
// This continuation runs on either success or failure, but if the task
// has failed then task.result will throw an Exception which will be
// propagated down.
val result = task.result?.data as Map<String, Any>
result["operationResult"] as Int
}
}
// [END function_add_numbers]
// [START function_add_message]
private fun addMessage(text: String): Task<String> {
// Create the arguments to the callable function.
val data = hashMapOf(
"text" to text,
"push" to true
)
return functions
.getHttpsCallable("addMessage")
.call(data)
.continueWith { task ->
// This continuation runs on either success or failure, but if the task
// has failed then result will throw an Exception which will be
// propagated down.
val result = task.result?.data as String
result
}
}
// [END function_add_message]
private fun callAddNumbers(firstNumber: Int, secondNumber: Int) {
// [START call_add_numbers]
addNumbers(firstNumber, secondNumber)
.addOnCompleteListener { task ->
if (!task.isSuccessful) {
val e = task.exception
if (e is FirebaseFunctionsException) {
// Function error code, will be INTERNAL if the failure
// was not handled properly in the function call.
val code = e.code
// Arbitrary error details passed back from the function,
// usually a Map<String, Any>.
val details = e.details
}
}
}
// [END call_add_numbers]
}
private fun callAddMessage(inputMessage: String){
// [START call_add_message]
addMessage(inputMessage)
.addOnCompleteListener { task ->
if (!task.isSuccessful) {
val e = task.exception
if (e is FirebaseFunctionsException) {
val code = e.code
val details = e.details
}
}
}
// [END call_add_message]
}
}
| apache-2.0 |
DemonWav/StatCraftGradle | statcraft-api/src/main/kotlin/com/demonwav/statcraft/sql/DatabaseManager.kt | 1 | 7813 | /*
* StatCraft Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.sql
import com.empireminecraft.systems.db.DbRow
import com.empireminecraft.systems.db.DbStatement
import org.intellij.lang.annotations.Language
import java.sql.Connection
import java.util.UUID
/**
* The main database API for StatCraft. This handles initializing and setting up the database, making queries, and
* handling the connections.
*/
interface DatabaseManager : AutoCloseable {
/**
* Retrieve a new [Connection] instance from the connection pool.
*
* @return A new [Connection] instance from the connection pool.
*/
val connection: Connection
/**
* Setup the connection pool data source and connect to the database. If this fails then StatCraft will be
* disabled.
*/
fun initialize()
/**
* Check all tables and verify database structure is correct. Also handles database conversions when the layout
* changes.
*/
fun setupDatabase()
/**
* Using the MySQL query string, create a [DbStatement]. This DbStatement must be closed either in a finally block
* or using a try-with-resources.
*
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param query The MySQL string to make up the prepared statement
* @return A new [DbStatement] from the given query string.
*/
fun query(@Language("MySQL") query: String): DbStatement
/**
* Using the MySQL query string and the optional given parameters for the prepared statement, execute the update statement
* without returning anything.
*
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param query The MySQL string to make up the prepared statement
* @param params Array of objects for inserting into the prepared statement
*/
fun execute(@Language("MySQL") query: String, vararg params: Any?)
/**
* Using the MySQL query string and the optional given parameters for the prepared statement, execute the query and return
* the first row returned, or null if nothing is returned. This ignores all other rows that are returned.
*
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param query The MySQL string to make up the prepared statement
* @param params Array of objects for inserting into the prepared statement
* @return The [DbRow] returned from the query, or null if nothing is returned.
*/
fun getFirstRow(@Language("MySQL") query: String, vararg params: Any?): DbRow?
/**
* Using the MySQL query string and the optional given parameters for the prepared statement, execute the query and
* return the value of the first column of the first row, or null if nothing is returned. This ignores all other
* rows and columns that are returned.
*
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param query The MySQL string to make up the prepared statement
* @param params Array of objects for inserting into the prepared statement
* @return The value of the first column of the first row returned from the query, or null if nothing is returned.
*/
fun <T> getFirstColumn(@Language("MySQL") query: String, vararg params: Any?): T?
/**
* Using the MySQL query string and the optional given parameters for the prepared statement, execute the query and
* return a list of the values of the first column of every row, or an empty list if nothing is returned. This
* ignores all other columns that are returned.
*
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param query The MySQL string to make up the prepared statement
* @param params Array of objects for inserting into the prepared statement
* @return A list of the values of the first column of every row, or an empty list if nothing is returned.
* Never null.
*/
fun <T> getFirstColumnResults(@Language("MySQL") query: String, vararg params: Any?): List<T>
/**
* Using the MySQL query string and the optional given parameters for the prepared statement, execute the query and
* return a list of all the rows, or an empty list if nothing is returned.
*
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param query The MySQL string to make up the prepared statement
* @param params Array of objects for inserting into the prepared statement
* @return A list of the [DbRow]'s, or an empty list if nothing is returned. Never null.
*/
fun getResults(@Language("MySQL") query: String, vararg params: Any?): List<DbRow>
/**
* Using the MySQL query string and the optional given parameters for the prepared statement, execute the update
* and return the first auto-generated id created by the update, or null if none were created.
*
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param query The MySQL string to make up the prepared statement
* @param params Array of objects for inserting into the prepared statement
* @return The first auto-generated id created by the update, or null if none were created.
*/
fun executeUpdate(@Language("MySQL") query: String, vararg params: Any?): Long?
/**
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param uuid The player's [UUID]
* @return The int id of the player, or null if not found.
*/
fun getPlayerId(uuid: UUID): Int?
/**
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param name The player's name
* @return The int id of the player, or null if not found.
*/
fun getPlayerId(name: String): Int?
/**
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param uuid The world's [UUID]
* @return The int id of the world, or null if not found.
*/
fun getWorldId(uuid: UUID): Int?
/**
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param name The world's name
* @return The int id of the world, or null if not found.
*/
fun getWorldId(name: String): Int?
/**
* This method will run on the thread it is called and may be blocking. It should never be run on the main thread,
* use the [ThreadManager] instance for this.
*
* @param uuid The plugin's [UUID]
* @return The int id of the plugin, or null if not found.
*/
fun getPluginId(uuid: UUID): Int?
}
| mit |
rhdunn/xquery-intellij-plugin | src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/binding/Action.kt | 1 | 811 | /*
* Copyright (C) 2019 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding
class Action(private val `object`: Any, private val `class`: Class<*>) {
fun act() {
`class`.getMethod("act").invoke(`object`)
}
}
| apache-2.0 |
elect86/jAssimp | src/main/kotlin/assimp/types.kt | 2 | 1103 | package assimp
/**
* Created by elect on 16/11/2016.
*/
/** Maximum dimension for strings, ASSIMP strings are zero terminated. */
const val MAXLEN = 1024
/** Standard return type for some library functions.
* Rarely used, and if, mostly in the C API.
*/
enum class AiReturn(val i: Int) {
/** Indicates that a function was successful */
SUCCESS(0x0),
/** Indicates that a function failed */
FAILURE(-0x1),
/** Indicates that not enough memory was available to perform the requested operation */
OUTOFMEMORY(-0x3)
}
class AiMemoryInfo {
/** Storage allocated for texture data */
var textures = 0
/** Storage allocated for material data */
var materials = 0
/** Storage allocated for mesh data */
var meshes = 0
/** Storage allocated for node data */
var nodes = 0
/** Storage allocated for animation data */
var animations = 0
/** Storage allocated for camera data */
var cameras = 0
/** Storage allocated for light data */
var lights = 0
/** Total storage allocated for the full import. */
var total = 0
}
| mit |
serandel/hollywood | sample-app/src/main/kotlin/org/granchi/whatnow/StubActor.kt | 1 | 688 | package org.granchi.whatnow
import org.granchi.hollywood.Action
import org.granchi.hollywood.Actor
import org.granchi.hollywood.Model
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import io.reactivex.Observable
/**
* Stub Actor, just for using it so the app runs while building real ones.
* @author serandel
*/
class StubActor : Actor {
override val actions: Observable<Action>
get() = Observable.never<Action>()
override fun subscribeTo(models: Observable<Model>) {
models.subscribe { model -> log.info("Model received: {}", model) }
}
companion object {
private val log = LoggerFactory.getLogger(StubActor::class.java)
}
}
| apache-2.0 |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/remote/review_instruction/service/ReviewInstructionService.kt | 2 | 393 | package org.stepik.android.remote.review_instruction.service
import org.stepik.android.remote.review_instruction.model.ReviewInstructionResponse
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Query
interface ReviewInstructionService {
@GET("api/instructions")
fun getReviewInstructions(@Query("ids[]") ids: List<Long>): Single<ReviewInstructionResponse>
} | apache-2.0 |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/unit/DistanceUnit.kt | 1 | 2485 | package wangdaye.com.geometricweather.common.basic.models.options.unit
import android.content.Context
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.common.basic.models.options._basic.UnitEnum
import wangdaye.com.geometricweather.common.basic.models.options._basic.Utils
import wangdaye.com.geometricweather.common.utils.DisplayUtils
// actual distance = distance(km) * factor.
enum class DistanceUnit(
override val id: String,
override val unitFactor: Float
): UnitEnum<Float> {
KM("km", 1f),
M("m", 1000f),
MI("mi", 0.6213f),
NMI("nmi", 0.5399f),
FT("ft", 3280.8398f);
companion object {
@JvmStatic
fun getInstance(
value: String
) = when (value) {
"m" -> M
"mi" -> MI
"nmi" -> NMI
"ft" -> FT
else -> KM
}
}
override val valueArrayId = R.array.distance_unit_values
override val nameArrayId = R.array.distance_units
override val voiceArrayId = R.array.distance_unit_voices
override fun getName(context: Context) = Utils.getName(context, this)
override fun getVoice(context: Context) = Utils.getVoice(context, this)
override fun getValueWithoutUnit(valueInDefaultUnit: Float) = valueInDefaultUnit * unitFactor
override fun getValueInDefaultUnit(valueInCurrentUnit: Float) = valueInCurrentUnit / unitFactor
override fun getValueTextWithoutUnit(
valueInDefaultUnit: Float
) = Utils.getValueTextWithoutUnit(this, valueInDefaultUnit, 2)!!
override fun getValueText(
context: Context,
valueInDefaultUnit: Float
) = getValueText(context, valueInDefaultUnit, DisplayUtils.isRtl(context))
override fun getValueText(
context: Context,
valueInDefaultUnit: Float,
rtl: Boolean
) = Utils.getValueText(
context = context,
enum = this,
valueInDefaultUnit = valueInDefaultUnit,
decimalNumber = 2,
rtl = rtl
)
override fun getValueVoice(
context: Context,
valueInDefaultUnit: Float
) = getValueVoice(context, valueInDefaultUnit, DisplayUtils.isRtl(context))
override fun getValueVoice(
context: Context,
valueInDefaultUnit: Float,
rtl: Boolean
) = Utils.getVoiceText(
context = context,
enum = this,
valueInDefaultUnit = valueInDefaultUnit,
decimalNumber = 2,
rtl = rtl
)
} | lgpl-3.0 |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/video_player/model/VideoPlayerMediaData.kt | 2 | 1257 | package org.stepik.android.view.video_player.model
import android.os.Parcel
import android.os.Parcelable
import org.stepik.android.model.Video
data class VideoPlayerMediaData(
val thumbnail: String? = null,
val title: String,
val description: String? = null,
val cachedVideo: Video? = null,
val externalVideo: Video? = null
) : Parcelable {
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(thumbnail)
parcel.writeString(title)
parcel.writeString(description)
parcel.writeParcelable(cachedVideo, flags)
parcel.writeParcelable(externalVideo, flags)
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<VideoPlayerMediaData> {
override fun createFromParcel(parcel: Parcel): VideoPlayerMediaData =
VideoPlayerMediaData(
parcel.readString(),
parcel.readString()!!,
parcel.readString(),
parcel.readParcelable(Video::class.java.classLoader),
parcel.readParcelable(Video::class.java.classLoader)
)
override fun newArray(size: Int): Array<VideoPlayerMediaData?> =
arrayOfNulls(size)
}
} | apache-2.0 |
just6979/ScoreModel | ScoreModel/src/main/kotlin/net/justinwhite/scoremodel/phase10/Phase10Player.kt | 2 | 3164 | /*
* Copyright (c) 2015 Justin White <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package net.justinwhite.scoremodel.phase10
import net.justinwhite.scoremodel.Player
import net.justinwhite.scoremodel.phase10.Phase10Game.*
class Phase10Player(_name: String, _phases: Array<Phase>) : Player(_name) {
val phases: Array<Phase> = Phase10Game.getPhasePreset()
var currentPhase: Int = 0
private set
@JvmOverloads constructor(_name: String = "Player X", phasePreset: PhaseSet = PhaseSet.ALL) : this(_name, Companion.getPhasePreset(phasePreset))
init {
setActivePhases(_phases)
}
override fun toString(): String {
return "%s; Phase %d".format(super.toString(), currentPhase)
}
fun setActivePhases(_phases: Array<Phase>) {
System.arraycopy(_phases, 0, phases, 0, _phases.size)
}
fun setActivePhases(_phases: Array<Boolean>) {
for (i in 0..Phase10Game.MAX_PHASE) {
if (_phases[i]) {
phases[i] = Phase.ACTIVE
} else {
phases[i] = Phase.INACTIVE
}
}
}
fun resetCurrentPhase() {
currentPhase = 0
}
fun completeCurrentPhase() {
if (phases[currentPhase] === Phase.ACTIVE) {
phases[currentPhase] = Phase.COMPLETED
}
do {
currentPhase++
if (currentPhase > Phase10Game.MAX_PHASE) {
currentPhase = Phase10Game.MAX_PHASE
break
}
} while (phases[currentPhase] !== Phase.ACTIVE)
}
fun addScore(_score: Int?) {
score += _score!!
}
}
| bsd-3-clause |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/properties/kt10715.kt | 5 | 262 | fun box(): String {
var a = Base()
val count = a.count
if (count != 0) return "fail 1: $count"
val count2 = a.count
if (count2 != 1) return "fail 2: $count2"
return "OK"
}
class Base {
var count: Int = 0
get() = field++
} | apache-2.0 |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/util/NotificationChannelInitializer.kt | 2 | 1679 | package org.stepic.droid.util
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import org.stepic.droid.R
import org.stepic.droid.notifications.model.StepikNotificationChannel
object NotificationChannelInitializer {
fun initNotificationChannels(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
//channels were introduced only in O. Before we had used in-app channels
return
}
val stepikNotificationChannels = StepikNotificationChannel.values()
val androidChannels = ArrayList<NotificationChannel>(stepikNotificationChannels.size)
stepikNotificationChannels.forEach {
androidChannels.add(initChannel(context, it))
}
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannels(androidChannels)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun initChannel(
context: Context,
stepikChannel: StepikNotificationChannel
): NotificationChannel {
val channelName = context.getString(stepikChannel.visibleChannelNameRes)
val channel = NotificationChannel(stepikChannel.channelId, channelName, stepikChannel.importance)
channel.description = context.getString(stepikChannel.visibleChannelDescriptionRes)
channel.enableLights(true)
channel.enableVibration(true)
channel.lightColor = context.resolveColorAttribute(R.attr.colorError)
return channel
}
}
| apache-2.0 |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsSourcesController.kt | 1 | 4539 | package eu.kanade.tachiyomi.ui.setting
import android.graphics.drawable.Drawable
import android.support.v7.preference.PreferenceGroup
import android.support.v7.preference.PreferenceScreen
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.source.online.LoginSource
import eu.kanade.tachiyomi.util.LocaleHelper
import eu.kanade.tachiyomi.widget.preference.LoginCheckBoxPreference
import eu.kanade.tachiyomi.widget.preference.SourceLoginDialog
import eu.kanade.tachiyomi.widget.preference.SwitchPreferenceCategory
import exh.source.BlacklistedSources
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.*
class SettingsSourcesController : SettingsController(),
SourceLoginDialog.Listener {
private val onlineSources by lazy {
Injekt.get<SourceManager>().getOnlineSources().filter {
it.id !in BlacklistedSources.HIDDEN_SOURCES
}
}
override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) {
titleRes = R.string.pref_category_sources
// Get the list of active language codes.
val activeLangsCodes = preferences.enabledLanguages().getOrDefault()
// Get a map of sources grouped by language.
val sourcesByLang = onlineSources.groupByTo(TreeMap(), { it.lang })
// Order first by active languages, then inactive ones
val orderedLangs = sourcesByLang.keys.filter { it in activeLangsCodes } +
sourcesByLang.keys.filterNot { it in activeLangsCodes }
orderedLangs.forEach { lang ->
val sources = sourcesByLang[lang].orEmpty().sortedBy { it.name }
// Create a preference group and set initial state and change listener
SwitchPreferenceCategory(context).apply {
preferenceScreen.addPreference(this)
title = LocaleHelper.getDisplayName(lang, context)
isPersistent = false
if (lang in activeLangsCodes) {
setChecked(true)
addLanguageSources(this, sources)
}
onChange { newValue ->
val checked = newValue as Boolean
val current = preferences.enabledLanguages().getOrDefault()
if (!checked) {
preferences.enabledLanguages().set(current - lang)
removeAll()
} else {
preferences.enabledLanguages().set(current + lang)
addLanguageSources(this, sources)
}
true
}
}
}
}
override fun setDivider(divider: Drawable?) {
super.setDivider(null)
}
/**
* Adds the source list for the given group (language).
*
* @param group the language category.
*/
private fun addLanguageSources(group: PreferenceGroup, sources: List<HttpSource>) {
val hiddenCatalogues = preferences.hiddenCatalogues().getOrDefault()
sources.forEach { source ->
val sourcePreference = LoginCheckBoxPreference(group.context, source).apply {
val id = source.id.toString()
title = source.name
key = getSourceKey(source.id)
isPersistent = false
isChecked = id !in hiddenCatalogues
onChange { newValue ->
val checked = newValue as Boolean
val current = preferences.hiddenCatalogues().getOrDefault()
preferences.hiddenCatalogues().set(if (checked)
current - id
else
current + id)
true
}
setOnLoginClickListener {
val dialog = SourceLoginDialog(source)
dialog.targetController = this@SettingsSourcesController
dialog.showDialog(router)
}
}
group.addPreference(sourcePreference)
}
}
override fun loginDialogClosed(source: LoginSource) {
val pref = findPreference(getSourceKey(source.id)) as? LoginCheckBoxPreference
pref?.notifyChanged()
}
private fun getSourceKey(sourceId: Long): String {
return "source_$sourceId"
}
} | apache-2.0 |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/GestureDetectorWithLongTap.kt | 1 | 2633 | package eu.kanade.tachiyomi.ui.reader.viewer
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ViewConfiguration
import kotlin.math.abs
/**
* A custom gesture detector that also implements an on long tap confirmed, because the built-in
* one conflicts with the quick scale feature.
*/
open class GestureDetectorWithLongTap(
context: Context,
listener: Listener,
) : GestureDetector(context, listener) {
private val handler = Handler(Looper.getMainLooper())
private val slop = ViewConfiguration.get(context).scaledTouchSlop
private val longTapTime = ViewConfiguration.getLongPressTimeout().toLong()
private val doubleTapTime = ViewConfiguration.getDoubleTapTimeout().toLong()
private var downX = 0f
private var downY = 0f
private var lastUp = 0L
private var lastDownEvent: MotionEvent? = null
/**
* Runnable to execute when a long tap is confirmed.
*/
private val longTapFn = Runnable { listener.onLongTapConfirmed(lastDownEvent!!) }
override fun onTouchEvent(ev: MotionEvent): Boolean {
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
lastDownEvent?.recycle()
lastDownEvent = MotionEvent.obtain(ev)
// This is the key difference with the built-in detector. We have to ignore the
// event if the last up and current down are too close in time (double tap).
if (ev.downTime - lastUp > doubleTapTime) {
downX = ev.rawX
downY = ev.rawY
handler.postDelayed(longTapFn, longTapTime)
}
}
MotionEvent.ACTION_MOVE -> {
if (abs(ev.rawX - downX) > slop || abs(ev.rawY - downY) > slop) {
handler.removeCallbacks(longTapFn)
}
}
MotionEvent.ACTION_UP -> {
lastUp = ev.eventTime
handler.removeCallbacks(longTapFn)
}
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(longTapFn)
}
}
return super.onTouchEvent(ev)
}
/**
* Custom listener to also include a long tap confirmed
*/
open class Listener : SimpleOnGestureListener() {
/**
* Notified when a long tap occurs with the initial on down [ev] that triggered it.
*/
open fun onLongTapConfirmed(ev: MotionEvent) {
}
}
}
| apache-2.0 |
Heiner1/AndroidAPS | wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.kt | 1 | 1606 | package info.nightscout.androidaps.interaction.utils
import org.junit.Assert
import org.junit.Test
class PairTest {
@Test fun pairEqualsTest() {
// GIVEN
val left: Pair<*, *> = Pair.create("aa", "bbb")
val right: Pair<*, *> = Pair.create("ccc", "dd")
val another: Pair<*, *> = Pair.create("aa", "bbb")
val samePos1: Pair<*, *> = Pair.create("aa", "d")
val samePos2: Pair<*, *> = Pair.create("zzzzz", "bbb")
val no1: Pair<*, *> = Pair.create(12, 345L)
val no2: Pair<*, *> = Pair.create(-943, 42)
val no3: Pair<*, *> = Pair.create(12L, 345)
val no4: Pair<*, *> = Pair.create(12, 345L)
// THEN
Assert.assertNotEquals(left, right)
Assert.assertEquals(left, another)
Assert.assertNotEquals(left, samePos1)
Assert.assertNotEquals(left, samePos2)
Assert.assertNotEquals(no1, no2)
Assert.assertNotEquals(no1, no3)
Assert.assertEquals(no1, no4)
Assert.assertNotEquals("aa bbb", left.toString())
}
@Test fun pairHashTest() {
// GIVEN
val inserted: Pair<*, *> = Pair.create("aa", "bbb")
val set: MutableSet<Pair<*, *>> = HashSet()
// THEN
Assert.assertFalse(set.contains(inserted))
set.add(inserted)
Assert.assertTrue(set.contains(inserted))
}
@Test fun toStringTest() {
// GIVEN
val pair: Pair<*, *> = Pair.create("the-first", "2nd")
Assert.assertTrue(pair.toString().contains("the-first"))
Assert.assertTrue(pair.toString().contains("2nd"))
}
} | agpl-3.0 |
exponentjs/exponent | packages/expo-dev-menu/android/src/main/java/expo/modules/devmenu/DevMenuDefaultSettings.kt | 2 | 1294 | package expo.modules.devmenu
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableMap
import expo.interfaces.devmenu.DevMenuSettingsInterface
open class DevMenuDefaultSettings : DevMenuSettingsInterface {
private fun methodUnavailable() {
throw NoSuchMethodError("You cannot change the default settings. Export `DevMenuSettings` module if you want to change the settings.")
}
override var motionGestureEnabled: Boolean
get() = true
set(_) = methodUnavailable()
override var touchGestureEnabled: Boolean
get() = true
set(_) = methodUnavailable()
override var keyCommandsEnabled: Boolean
get() = true
set(_) = methodUnavailable()
override var showsAtLaunch: Boolean
get() = false
set(_) = methodUnavailable()
override var isOnboardingFinished: Boolean
get() = true
set(_) = methodUnavailable()
override fun serialize(): WritableMap =
Arguments
.createMap()
.apply {
putBoolean("motionGestureEnabled", motionGestureEnabled)
putBoolean("touchGestureEnabled", touchGestureEnabled)
putBoolean("keyCommandsEnabled", keyCommandsEnabled)
putBoolean("showsAtLaunch", showsAtLaunch)
putBoolean("isOnboardingFinished", isOnboardingFinished)
}
}
| bsd-3-clause |
maiconhellmann/pomodoro | app/src/main/kotlin/br/com/maiconhellmann/pomodoro/ui/base/BaseActivity.kt | 1 | 4332 | package br.com.maiconhellmann.pomodoro.ui.base
import android.app.ProgressDialog
import android.os.Bundle
import android.support.annotation.CallSuper
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.view.View
import br.com.maiconhellmann.pomodoro.PomodoroApplication
import br.com.maiconhellmann.pomodoro.injection.component.ActivityComponent
import br.com.maiconhellmann.pomodoro.injection.component.ConfigPersistentComponent
import br.com.maiconhellmann.pomodoro.injection.module.ActivityModule
import br.com.maiconhellmann.pomodoro.injection.module.PresenterModule
import br.com.maiconhellmann.pomodoro.util.extension.snackbar
import timber.log.Timber
import java.util.*
import java.util.concurrent.atomic.AtomicLong
open class BaseActivity: AppCompatActivity() {
private var progressDialog: ProgressDialog? = null
companion object {
@JvmStatic private val KEY_ACTIVITY_ID = "KEY_ACTIVITY_ID"
@JvmStatic private val NEXT_ID = AtomicLong(0)
@JvmStatic private val componentsMap = HashMap<Long, ConfigPersistentComponent>()
}
private var activityId: Long = 0
lateinit var activityComponent: ActivityComponent
get
@Suppress("UsePropertyAccessSyntax")
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Create the ActivityComponent and reuses cached ConfigPersistentComponent if this is
// being called after a configuration change.
activityId = savedInstanceState?.getLong(KEY_ACTIVITY_ID) ?: NEXT_ID.getAndIncrement()
if (componentsMap[activityId] != null)
Timber.i("Reusing ConfigPersistentComponent id = $activityId")
val configPersistentComponent = componentsMap.getOrPut(activityId, {
Timber.i("Creating new ConfigPersistentComponent id=$activityId")
val component = (applicationContext as PomodoroApplication).applicationComponent
component + PresenterModule()
})
activityComponent = configPersistentComponent + ActivityModule(this)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putLong(KEY_ACTIVITY_ID, activityId)
}
override fun onDestroy() {
if (!isChangingConfigurations) {
Timber.i("Clearing ConfigPersistentComponent id=$activityId")
componentsMap.remove(activityId)
}
super.onDestroy()
}
override fun setTitle(titleId: Int) {
actionBar?.title = getString(titleId)
supportActionBar?.title = getString(titleId)
}
fun displayHomeAsUpEnabled(){
actionBar?.setDisplayHomeAsUpEnabled(true)
actionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
}
open fun hideProgressIndicator() {
progressDialog?.dismiss()
progressDialog = null
}
open fun showProgressIndicator(title: String?, message: String? = null, cancelable: Boolean = true) {
val dialog = ProgressDialog(this)
if (title != null) {
dialog.setTitle(title)
}
if (message != null) {
dialog.setMessage(message)
}
dialog.isIndeterminate = true
dialog.setCancelable(cancelable)
dialog.show()
progressDialog = dialog
}
open fun showProgressIndicator() {
showProgressIndicator("aguarde")
}
override fun onLowMemory() {
super.onLowMemory()
}
fun getParentView(): View? {
return findViewById(android.R.id.content)
}
fun snack(resId: Int, duration: Int = Snackbar.LENGTH_SHORT){
getParentView()?.snackbar(resId, duration)
}
fun snack(msg: String, duration: Int = Snackbar.LENGTH_SHORT){
getParentView()?.snackbar(msg, duration)
}
fun longSnack(resId: Int){
getParentView()?.snackbar(resId, Snackbar.LENGTH_LONG)
}
fun longSnack(msg: String){
getParentView()?.snackbar(msg, Snackbar.LENGTH_LONG)
}
}
| apache-2.0 |
rlac/unitconverter | app/src/main/kotlin/au/id/rlac/util/nucleus/BaseFragment.kt | 1 | 1213 | package au.id.rlac.util.nucleus
import android.app.Fragment
import android.os.Bundle
import au.id.rlac.util.nucleus.NucleusHelper
import nucleus.factory.ReflectionPresenterFactory
import nucleus.manager.PresenterManager
import nucleus.presenter.Presenter
public abstract class BaseFragment<ViewType, PresenterType : Presenter<ViewType>> : Fragment() {
private var presenterHelper = NucleusHelper<ViewType, PresenterType>(
PresenterManager.getInstance(), ReflectionPresenterFactory.fromViewClass(javaClass))
val presenter: PresenterType get() = presenterHelper.presenter
override fun onCreate(savedInstanceState: Bundle?) {
super<Fragment>.onCreate(savedInstanceState)
@Suppress("UNCHECKED_CAST")
presenterHelper.create(this as ViewType, savedInstanceState)
}
override fun onResume() {
super<Fragment>.onResume()
presenterHelper.resume()
}
override fun onPause() {
super<Fragment>.onPause()
presenterHelper.pause()
}
override fun onDestroy() {
super<Fragment>.onDestroy()
presenterHelper.destroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super<Fragment>.onSaveInstanceState(outState)
presenterHelper.save(outState)
}
} | apache-2.0 |
abigpotostew/easypolitics | ui/src/main/kotlin/bz/stew/bracken/ui/pages/browse/view/mixins/TwitterLink.kt | 1 | 681 | package bz.stew.bracken.ui.pages.browse.view.mixins
import bz.stew.bracken.ui.extension.html.LinkTarget
import bz.stew.bracken.ui.common.view.SubTemplate
import bz.stewart.bracken.shared.data.person.Legislator
import kotlinx.html.FlowContent
import kotlinx.html.a
class TwitterLink(private val legislator: Legislator, private val target: LinkTarget = LinkTarget.BLANK) : SubTemplate {
override fun renderIn(root: FlowContent) {
val twitter = legislator.getTwitter()
val linkTarget = target
root.a {
+"@"
+twitter
href = "http://www.twitter.com/$twitter"
target = linkTarget.htmlValue()
}
}
} | apache-2.0 |
Maccimo/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/CompositeScriptConfigurationManager.kt | 2 | 8118 | // 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.core.script.configuration
import com.intellij.codeInsight.daemon.OutsidersPsiFileSupport
import com.intellij.ide.scratch.ScratchUtil
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.ProjectJdkTable.JDK_TABLE_TOPIC
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.core.script.ScriptDependenciesModificationTracker
import org.jetbrains.kotlin.idea.core.script.configuration.listener.ScriptChangesNotifier
import org.jetbrains.kotlin.idea.core.script.configuration.utils.getKtFile
import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsBuilder
import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsCache
import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsUpdater
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper
/**
* The [CompositeScriptConfigurationManager] will provide redirection of [ScriptConfigurationManager] calls to the
* custom [ScriptingSupport] or [DefaultScriptingSupport] if that script lack of custom [ScriptingSupport].
*
* The [ScriptConfigurationManager] is implemented by caching all scripts using the [ScriptClassRootsCache].
* The [ScriptClassRootsCache] is always available and never blacked by the writer, as all writes occurs
* using the copy-on-write strategy.
*
* This cache is loaded on start and will be updating asynchronously using the [updater].
* Sync updates still may be occurred from the [DefaultScriptingSupport].
*
* We are also watching all script documents:
* [notifier] will call first applicable [ScriptChangesNotifier.listeners] when editor is activated or document changed.
* Listener should do something to invalidate configuration and schedule reloading.
*/
class CompositeScriptConfigurationManager(val project: Project) : ScriptConfigurationManager {
private val notifier = ScriptChangesNotifier(project)
private val classpathRoots: ScriptClassRootsCache
get() = updater.classpathRoots
private val plugins
get() = ScriptingSupport.EPN.getPoint(project).extensionList
val default = DefaultScriptingSupport(this)
val updater = object : ScriptClassRootsUpdater(project, this) {
override fun gatherRoots(builder: ScriptClassRootsBuilder) {
default.collectConfigurations(builder)
plugins.forEach { it.collectConfigurations(builder) }
}
override fun afterUpdate() {
plugins.forEach { it.afterUpdate() }
}
}
override fun loadPlugins() {
plugins
}
fun updateScriptDependenciesIfNeeded(file: VirtualFile) {
notifier.updateScriptDependenciesIfNeeded(file)
}
fun tryGetScriptDefinitionFast(locationId: String): ScriptDefinition? {
return classpathRoots.getLightScriptInfo(locationId)?.definition
}
private fun getOrLoadConfiguration(
virtualFile: VirtualFile,
preloadedKtFile: KtFile? = null
): ScriptCompilationConfigurationWrapper? {
val scriptConfiguration = classpathRoots.getScriptConfiguration(virtualFile)
if (scriptConfiguration != null) return scriptConfiguration
// check that this script should be loaded later in special way (e.g. gradle project import)
// (and not for syntactic diff files)
if (!OutsidersPsiFileSupport.isOutsiderFile(virtualFile)) {
val plugin = plugins.firstOrNull { it.isApplicable(virtualFile) }
if (plugin != null) {
return plugin.getConfigurationImmediately(virtualFile)?.also {
updater.addConfiguration(virtualFile, it)
}
}
}
return default.getOrLoadConfiguration(virtualFile, preloadedKtFile)
}
override fun getConfiguration(file: KtFile) =
getOrLoadConfiguration(file.originalFile.virtualFile, file)
override fun hasConfiguration(file: KtFile): Boolean =
classpathRoots.contains(file.originalFile.virtualFile)
override fun isConfigurationLoadingInProgress(file: KtFile): Boolean =
plugins.firstOrNull { it.isApplicable(file.originalFile.virtualFile) }?.isConfigurationLoadingInProgress(file)
?: default.isConfigurationLoadingInProgress(file)
fun getLightScriptInfo(file: String): ScriptClassRootsCache.LightScriptInfo? =
classpathRoots.getLightScriptInfo(file)
override fun updateScriptDefinitionReferences() {
ScriptDependenciesModificationTracker.getInstance(project).incModificationCount()
default.updateScriptDefinitionsReferences()
if (classpathRoots.customDefinitionsUsed) {
updater.invalidateAndCommit()
}
}
init {
val connection = project.messageBus.connect(KotlinPluginDisposable.getInstance(project))
connection.subscribe(JDK_TABLE_TOPIC, object : ProjectJdkTable.Listener {
override fun jdkAdded(jdk: Sdk) = updater.checkInvalidSdks()
override fun jdkNameChanged(jdk: Sdk, previousName: String) = updater.checkInvalidSdks()
override fun jdkRemoved(jdk: Sdk) = updater.checkInvalidSdks(remove = jdk)
})
}
/**
* Returns script classpath roots
* Loads script configuration if classpath roots don't contain [file] yet
*/
private fun getActualClasspathRoots(file: VirtualFile): ScriptClassRootsCache {
try {
// we should run default loader if this [file] is not cached in [classpathRoots]
// and it is not supported by any of [plugins]
// getOrLoadConfiguration will do this
// (despite that it's result becomes unused, it still may populate [classpathRoots])
getOrLoadConfiguration(file, null)
} catch (cancelled: ProcessCanceledException) {
// read actions may be cancelled if we are called by impatient reader
}
return this.classpathRoots
}
override fun getScriptSdk(file: VirtualFile): Sdk? =
if (ScratchUtil.isScratch(file)) {
ProjectRootManager.getInstance(project).projectSdk
} else {
getActualClasspathRoots(file).getScriptSdk(file)
}
override fun getFirstScriptsSdk(): Sdk? =
classpathRoots.firstScriptSdk
override fun getScriptDependenciesClassFilesScope(file: VirtualFile): GlobalSearchScope =
classpathRoots.getScriptDependenciesClassFilesScope(file)
override fun getAllScriptsDependenciesClassFilesScope(): GlobalSearchScope =
classpathRoots.allDependenciesClassFilesScope
override fun getAllScriptDependenciesSourcesScope(): GlobalSearchScope =
classpathRoots.allDependenciesSourcesScope
override fun getAllScriptsDependenciesClassFiles(): Collection<VirtualFile> =
classpathRoots.allDependenciesClassFiles
override fun getAllScriptDependenciesSources(): Collection<VirtualFile> =
classpathRoots.allDependenciesSources
///////////////////
// Adapters for deprecated API
//
@Deprecated("Use getScriptClasspath(KtFile) instead")
override fun getScriptClasspath(file: VirtualFile): List<VirtualFile> {
val ktFile = project.getKtFile(file) ?: return emptyList()
return getScriptClasspath(ktFile)
}
override fun getScriptClasspath(file: KtFile): List<VirtualFile> =
ScriptConfigurationManager.toVfsRoots(getConfiguration(file)?.dependenciesClassPath.orEmpty())
}
| apache-2.0 |
abigpotostew/easypolitics | shared/src/main/kotlin/bz/stewart/bracken/shared/data/Annotations.kt | 1 | 161 | package bz.stewart.bracken.shared.data
/**
* Created by stew on 4/1/17.
*/
/**
* The field is required for an actual bill
*/
annotation class BillRequired
| apache-2.0 |
pyamsoft/pydroid | billing/src/main/java/com/pyamsoft/pydroid/billing/BillingModule.kt | 1 | 1580 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.billing
import android.content.Context
import androidx.annotation.CheckResult
import com.pyamsoft.pydroid.billing.store.PlayStoreBillingInteractor
import com.pyamsoft.pydroid.bus.EventBus
/** Billing module */
public class BillingModule(params: Parameters) {
private val impl =
PlayStoreBillingInteractor(
context = params.context.applicationContext,
errorBus = params.errorBus,
)
/** Provide a billing instance */
@CheckResult
public fun provideInteractor(): BillingInteractor {
return impl
}
/** Provide a launcher instance */
@CheckResult
public fun provideLauncher(): BillingLauncher {
return impl
}
/** Provide a connector instance */
@CheckResult
public fun provideConnector(): BillingConnector {
return impl
}
/** Module parameters */
public data class Parameters(
internal val context: Context,
internal val errorBus: EventBus<Throwable>,
)
}
| apache-2.0 |
Aenyn/ccrgkt | src/main/kotlin/fr/panicot/ccrg/botting/EasyBot.kt | 1 | 1309 | package fr.panicot.ccrg.botting
import fr.panicot.ccrg.botting.util.SchedulableTask
import fr.panicot.ccrg.core.messaging.Message
import fr.panicot.ccrg.core.messaging.MessageController
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler
import java.util.*
import java.util.concurrent.Executors
/**
* Created by William on 18/03/2017.
*/
abstract class EasyBot(messageController: MessageController, random: Random) : Bot(messageController, random) {
private val scheduler = ThreadPoolTaskScheduler()
private val executor = Executors.newSingleThreadExecutor()
private var latestId = 0L
override fun start() {
scheduler.initialize()
getTasksToSchedule().forEach { schedulableTask -> scheduler.schedule(schedulableTask.task, schedulableTask.schedule) }
executor.submit { recursivePollExecute() }
}
private fun recursivePollExecute() : Unit {
val messageBatch = messageController.longPollMessages(this.latestId)
this.latestId = messageBatch.latestId
messageBatch.messages.forEach { message -> executeOnNewMessage(message) }
executor.submit { recursivePollExecute() }
}
abstract fun getTasksToSchedule() : Collection<SchedulableTask>
abstract fun executeOnNewMessage(message: Message) : Unit
} | mit |
filpgame/kotlinx-examples | app/src/main/java/com/filpgame/kotlinx/ui/list/User.kt | 1 | 666 | package com.filpgame.kotlinx.ui.list
import android.R.drawable.*
import java.security.SecureRandom
fun <T> Array<T>.random(): T = this[SecureRandom().nextInt(this.count())]
val pictures = arrayOf(ic_media_play, ic_delete, ic_lock_lock, ic_dialog_map, ic_lock_power_off, ic_menu_zoom, ic_input_add)
val names = arrayOf("Felipe", "Cicrano", "Pedro", "Thiago", "John", "Fulano", "Beltrano")
val occupations = arrayOf("Developer", "Engineer", "QA", "Manager", "Driver", "Seller", "Customer Relationship")
data class User(
val name: String = names.random(),
val occupation: String = occupations.random(),
val picture: Int = pictures.random()
) | mit |
wordpress-mobile/WordPress-Android | WordPress/src/test/java/org/wordpress/android/ui/prefs/timezone/SiteSettingsTimezoneViewModelTest.kt | 1 | 1786 | package org.wordpress.android.ui.prefs.timezone
import android.content.Context
import org.assertj.core.api.Assertions
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.viewmodel.ResourceProvider
class SiteSettingsTimezoneViewModelTest : BaseUnitTest() {
@Mock lateinit var resourceProvider: ResourceProvider
@Mock lateinit var context: Context
private lateinit var viewModel: SiteSettingsTimezoneViewModel
@Before
fun setUp() {
viewModel = SiteSettingsTimezoneViewModel(resourceProvider)
}
@Test
fun testSearchTimezones() {
var filteredList: List<TimezonesList>? = null
viewModel.timezones.observeForever {
filteredList = it
}
viewModel.searchTimezones("Sydney")
Assertions.assertThat(filteredList).isNotNull
}
@Test
fun testGetShowEmptyView() {
var showEmptyView = false
viewModel.showEmptyView.observeForever {
showEmptyView = it
}
viewModel.filterTimezones("")
assertEquals(showEmptyView, true)
}
@Test
fun testGetSelectedTimezone() {
var selectedTimezone: String? = null
viewModel.selectedTimezone.observeForever {
selectedTimezone = it
}
viewModel.onTimezoneSelected("Australia/Sydney")
Assertions.assertThat(selectedTimezone).isNotNull
}
@Test
fun testOnSearchCancelled() {
var timezones: List<TimezonesList>? = null
viewModel.timezones.observeForever {
timezones = it
}
viewModel.onSearchCancelled()
Assertions.assertThat(timezones).isNotNull
}
}
| gpl-2.0 |
Turbo87/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustBlockImplMixin.kt | 1 | 1259 | package org.rust.lang.core.psi.impl.mixin
import com.intellij.lang.ASTNode
import com.intellij.psi.util.PsiTreeUtil
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.impl.RustCompositeElementImpl
import org.rust.lang.core.psi.util.isAfter
abstract class RustBlockImplMixin(node: ASTNode) : RustCompositeElementImpl(node)
, RustBlock {
override val declarations: Collection<RustDeclaringElement>
get() = stmtList.filterIsInstance<RustDeclStmt>()
.map { it.letDecl }
.filterNotNull()
}
/**
* Let declarations visible at the `element` according to Rust scoping rules.
* More recent declarations come first.
*
* Example:
*
* ```
* {
* let x = 92; // visible
* let x = x; // not visible
* ^ element
* let x = 62; // not visible
* }
* ```
*/
fun RustBlock.letDeclarationsVisibleAt(element: RustCompositeElement): Sequence<RustLetDecl> =
stmtList.asReversed().asSequence()
.filterIsInstance<RustDeclStmt>()
.mapNotNull { it.letDecl }
.dropWhile { it.isAfter(element) }
// Drops at most one element
.dropWhile { PsiTreeUtil.isAncestor(it, element, true) }
| mit |
RonnChyran/Face-of-Sidonia | Sidonia/SidoniaWatchface/src/main/java/moe/chyyran/sidonia/drawables/StatusDrawable.kt | 1 | 6848 | package moe.chyyran.sidonia.drawables
import android.graphics.*
import com.ustwo.clockwise.common.WatchFaceTime
import com.ustwo.clockwise.wearable.WatchFace
private class TextOffsets(val leftTextOffset: PointF, val rightTextOffset: PointF, val halfHeightTextOffset: PointF)
class StatusDrawable(watch: WatchFace) : SidoniaDrawable(watch) {
private var mLeftTextPaint: Paint = createWeekDayPaint()
private var mRightTextPaint: Paint = createDatePaint()
private var mHalfHeightTextPaint: Paint = createHalfHeightDisplayPaint()
private fun getTextOffsets(kanji: String, time: String): TextOffsets {
val leftTextMetrics = mLeftTextPaint.fontMetrics
// This text is to be drawn in cell 0, 1.
val leftCellOffset = this.getCellOffset(0, 1)
// Calculate the difference on each side between the cell walls and the
// width of the text, in order to properly center the text horizontally.
val leftTextWidthDiff = (hudCellWidth - mLeftTextPaint.measureText(kanji)) / 2f
// Calculate the difference on each side between the cell walls and the height of
// the text, in order to properly center the text vertically.
val leftTextHeightDiff = (hudCellWidth - (leftTextMetrics.ascent + leftTextMetrics.descent)) / 2f
// The offset is simply the cell offset + the difference between the cell walls
// and the dimensions of the text.
val leftOffset = PointF(leftCellOffset.x + leftTextWidthDiff, leftCellOffset.y + leftTextHeightDiff)
val rightCellOffset = this.getCellOffset(0, 2) // actually 2.5 ish, but we will ignore the x.
val rightTextMetrics = mRightTextPaint.fontMetrics
val rightTextWidth = mRightTextPaint.measureText(time) / 2f
val rightTextHeightDiff = (hudCellWidth - (rightTextMetrics.ascent + rightTextMetrics.descent)) / 2f
val rightLeftOffset = edgeOffset + desiredMinimumWidth / 1.60f - rightTextWidth
// Here the x offset has been manually specified, but the top offset is the same principle
val rightOffset = PointF(rightLeftOffset, rightCellOffset.y + rightTextHeightDiff)
// Half height text is it's own special case.
val halfHeightTextWidth = mHalfHeightTextPaint.measureText("T") / 2f
val halfHeightTextHeight = (rightTextMetrics.ascent + rightTextMetrics.descent) / 2f
val halfHeightTopOffset = edgeOffset + hudCellWidth / 9f
val halfHeightLeftOffset = edgeOffset + desiredMinimumWidth / 2.25f - halfHeightTextWidth
val halfHeightOffset = PointF(halfHeightLeftOffset, halfHeightTopOffset - halfHeightTextHeight)
return TextOffsets(leftOffset, rightOffset, halfHeightOffset)
}
private fun createHalfHeightDisplayPaint(): Paint {
val centerTextSize = desiredMinimumWidth / 12.0f
val halfHeightPaint = Paint()
halfHeightPaint.typeface = this.latinFont
halfHeightPaint.color = this.backgroundColor
halfHeightPaint.textSize = centerTextSize
halfHeightPaint.isAntiAlias = true
return halfHeightPaint
}
private fun createWeekDayPaint() : Paint {
val textSize = desiredMinimumWidth / 5.5f
val paint = Paint(this.hudPaint)
paint.typeface = this.kanjiFont
paint.textSize = textSize
return paint
}
private fun createDatePaint() : Paint {
val textSize = desiredMinimumWidth / 5.5f
val paint = Paint()
paint.typeface = this.latinFont
paint.color = this.backgroundColor
paint.textSize = textSize
paint.isAntiAlias = true
return paint
}
fun drawTime(canvas: Canvas?, time: WatchFaceTime) {
val hour12 = if (time.hour > 11) time.hour - 12 else time.hour
val text = (hour12 % 10).toString() + if (time.minute > 9)
time.minute.toString()
else
"0" + time.minute.toString()
val textOffsets = getTextOffsets(getWeekDayKanji(time.weekDay), text)
canvas?.drawRect(hudCellWidth * 2f + edgeOffset,
edgeOffset,
hudCellWidth * 4f + edgeOffset,
hudCellWidth * 1f + edgeOffset,
this.hudPaint
)
canvas?.drawText("T", textOffsets.halfHeightTextOffset.x, textOffsets.halfHeightTextOffset.y, mHalfHeightTextPaint)
if (time.hour > 11)
canvas?.drawText("P", textOffsets.halfHeightTextOffset.x,
textOffsets.halfHeightTextOffset.y + (edgeOffset + hudCellWidth / 3f),
mHalfHeightTextPaint
)
else
canvas?.drawText("A", textOffsets.halfHeightTextOffset.x,
textOffsets.halfHeightTextOffset.y + (edgeOffset + hudCellWidth / 3f),
mHalfHeightTextPaint
)
canvas?.drawText(text, textOffsets.rightTextOffset.x, textOffsets.rightTextOffset.y, mRightTextPaint)
}
fun drawDate(canvas: Canvas?, time: WatchFaceTime) {
// Months are zero-indexed, so we have to add one in order to correct for it.
val text = ((time.month % 10) + 1).toString() + (if (time.monthDay > 9)
time.monthDay.toString()
else
"0" + time.monthDay.toString())
val textOffsets = getTextOffsets(getWeekDayKanji(time.weekDay), text)
val startOffset = this.getCellOffset(0, 2)
val endOffset = this.getCellOffset(1, 4)
canvas?.drawRect(startOffset.x, startOffset.y,
endOffset.x,
endOffset.y,
this.hudPaint
)
canvas?.drawText("T", textOffsets.halfHeightTextOffset.x, textOffsets.halfHeightTextOffset.y,
mHalfHeightTextPaint)
canvas?.drawText("S", textOffsets.halfHeightTextOffset.x,
textOffsets.halfHeightTextOffset.y + (edgeOffset + hudCellWidth / 3f),
mHalfHeightTextPaint
)
canvas?.drawText(text, textOffsets.rightTextOffset.x, textOffsets.rightTextOffset.y, mRightTextPaint)
}
fun drawWeekDay(canvas: Canvas?, time: WatchFaceTime) {
val text = ((time.month % 10) + 1).toString() + (if (time.monthDay > 9)
time.monthDay.toString()
else
"0" + time.monthDay.toString())
val textOffsets = getTextOffsets(getWeekDayKanji(time.weekDay), text)
canvas?.drawText(getWeekDayKanji(time.weekDay),
textOffsets.leftTextOffset.x, textOffsets.leftTextOffset.y, mLeftTextPaint)
}
private fun getWeekDayKanji(num: Int): String {
var c: String = ""
when (num) {
0 -> c = "曰"
1 -> c = "月"
2 -> c = "火"
3 -> c = "水"
4 -> c = "木"
5 -> c = "金"
6 -> c = "土"
}
return c
}
}
| mit |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/GetPostTagsUseCase.kt | 1 | 704 | package org.wordpress.android.ui.posts
import android.text.TextUtils
import dagger.Reusable
import org.apache.commons.text.StringEscapeUtils
import javax.inject.Inject
@Reusable
class GetPostTagsUseCase @Inject constructor() {
fun getTags(editPostRepository: EditPostRepository): String? {
val tags = editPostRepository.getPost()?.tagNameList
return tags?.let {
if (it.isNotEmpty()) {
formatTags(it)
} else {
null
}
}
}
private fun formatTags(tags: List<String>): String {
val formattedTags = TextUtils.join(",", tags)
return StringEscapeUtils.unescapeHtml4(formattedTags)
}
}
| gpl-2.0 |
wordpress-mobile/WordPress-Android | WordPress/src/test/java/org/wordpress/android/sharedlogin/SharedLoginAnalyticsTrackerTest.kt | 1 | 1527 | package org.wordpress.android.sharedlogin
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.sharedlogin.SharedLoginAnalyticsTracker.ErrorType
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
class SharedLoginAnalyticsTrackerTest {
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper = mock()
private val classToTest = SharedLoginAnalyticsTracker(analyticsTrackerWrapper)
@Test
fun `Should track login start correctly`() {
classToTest.trackLoginStart()
verify(analyticsTrackerWrapper).track(Stat.SHARED_LOGIN_START)
}
@Test
fun `Should track login success correctly`() {
classToTest.trackLoginSuccess()
verify(analyticsTrackerWrapper).track(Stat.SHARED_LOGIN_SUCCESS)
}
@Test
fun `Should track login failed WPNotLoggedInError correctly`() {
classToTest.trackLoginFailed(ErrorType.WPNotLoggedInError)
verify(analyticsTrackerWrapper).track(
Stat.SHARED_LOGIN_FAILED,
mapOf("error_type" to "wp_not_logged_in_error")
)
}
@Test
fun `Should track login failed QueryLoginDataError correctly`() {
classToTest.trackLoginFailed(ErrorType.QueryLoginDataError)
verify(analyticsTrackerWrapper).track(
Stat.SHARED_LOGIN_FAILED,
mapOf("error_type" to "query_login_data_error")
)
}
}
| gpl-2.0 |
Turbo87/intellij-rust | src/test/kotlin/org/rust/lang/RustTestCaseBase.kt | 1 | 1055 | package org.rust.lang
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
abstract class RustTestCaseBase : LightCodeInsightFixtureTestCase(), RustTestCase {
abstract val dataPath: String
override fun getTestDataPath(): String = "${RustTestCase.testResourcesPath}/$dataPath"
final protected val fileName: String
get() = "$testName.rs"
final protected val testName: String
get() = camelToSnake(getTestName(true))
final protected fun checkByFile(ignoreTrailingWhitespace: Boolean = true, action: () -> Unit) {
val before = fileName
val after = before.replace(".rs", "_after.rs")
myFixture.configureByFile(before)
action()
myFixture.checkResultByFile(after, ignoreTrailingWhitespace)
}
companion object {
@JvmStatic
fun camelToSnake(camelCaseName: String): String =
camelCaseName.split("(?=[A-Z])".toRegex())
.map { it.toLowerCase() }
.joinToString("_")
}
}
| mit |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/StatsListViewModel.kt | 1 | 10378 | package org.wordpress.android.ui.stats.refresh.lists
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.stats.refresh.DAY_STATS_USE_CASE
import org.wordpress.android.ui.stats.refresh.INSIGHTS_USE_CASE
import org.wordpress.android.ui.stats.refresh.MONTH_STATS_USE_CASE
import org.wordpress.android.ui.stats.refresh.NavigationTarget
import org.wordpress.android.ui.stats.refresh.NavigationTarget.ViewInsightsManagement
import org.wordpress.android.ui.stats.refresh.StatsViewModel.DateSelectorUiModel
import org.wordpress.android.ui.stats.refresh.TOTAL_COMMENTS_DETAIL_USE_CASE
import org.wordpress.android.ui.stats.refresh.TOTAL_FOLLOWERS_DETAIL_USE_CASE
import org.wordpress.android.ui.stats.refresh.TOTAL_LIKES_DETAIL_USE_CASE
import org.wordpress.android.ui.stats.refresh.VIEWS_AND_VISITORS_USE_CASE
import org.wordpress.android.ui.stats.refresh.WEEK_STATS_USE_CASE
import org.wordpress.android.ui.stats.refresh.YEAR_STATS_USE_CASE
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.DAYS
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.INSIGHTS
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.MONTHS
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.WEEKS
import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.YEARS
import org.wordpress.android.ui.stats.refresh.utils.ActionCardHandler
import org.wordpress.android.ui.stats.refresh.utils.ItemPopupMenuHandler
import org.wordpress.android.ui.stats.refresh.utils.NewsCardHandler
import org.wordpress.android.ui.stats.refresh.utils.StatsDateSelector
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import org.wordpress.android.util.mapNullable
import org.wordpress.android.util.merge
import org.wordpress.android.util.mergeNotNull
import org.wordpress.android.util.throttle
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import javax.inject.Inject
import javax.inject.Named
const val SCROLL_EVENT_DELAY = 2000L
abstract class StatsListViewModel(
defaultDispatcher: CoroutineDispatcher,
private val statsUseCase: BaseListUseCase,
private val analyticsTracker: AnalyticsTrackerWrapper,
protected val dateSelector: StatsDateSelector,
popupMenuHandler: ItemPopupMenuHandler? = null,
private val newsCardHandler: NewsCardHandler? = null,
actionCardHandler: ActionCardHandler? = null
) : ScopedViewModel(defaultDispatcher) {
private var trackJob: Job? = null
private var isInitialized = false
enum class StatsSection(@StringRes val titleRes: Int) {
INSIGHTS(R.string.stats_insights),
DAYS(R.string.stats_timeframe_days),
WEEKS(R.string.stats_timeframe_weeks),
MONTHS(R.string.stats_timeframe_months),
YEARS(R.string.stats_timeframe_years),
DETAIL(R.string.stats),
INSIGHT_DETAIL(R.string.stats_insights_views_and_visitors),
TOTAL_LIKES_DETAIL(R.string.stats_view_total_likes),
TOTAL_COMMENTS_DETAIL(R.string.stats_view_total_comments),
TOTAL_FOLLOWERS_DETAIL(R.string.stats_view_total_followers),
ANNUAL_STATS(R.string.stats_insights_annual_site_stats);
}
val selectedDate = dateSelector.selectedDate
private val mutableNavigationTarget = MutableLiveData<Event<NavigationTarget>>()
val navigationTarget: LiveData<Event<NavigationTarget>> = mergeNotNull(
statsUseCase.navigationTarget, mutableNavigationTarget
)
val listSelected = statsUseCase.listSelected
val uiModel: LiveData<UiModel?> by lazy {
statsUseCase.data.throttle(viewModelScope, distinct = true)
}
val dateSelectorData: LiveData<DateSelectorUiModel> = dateSelector.dateSelectorData.mapNullable {
it ?: DateSelectorUiModel(false)
}
val typesChanged = merge(
popupMenuHandler?.typeMoved,
newsCardHandler?.cardDismissed,
actionCardHandler?.actionCard
)
val scrollTo = newsCardHandler?.scrollTo
val scrollToNewCard = statsUseCase.scrollTo
override fun onCleared() {
statsUseCase.onCleared()
super.onCleared()
}
fun onScrolledToBottom() {
if (trackJob?.isCompleted != false) {
trackJob = launch {
analyticsTracker.track(Stat.STATS_SCROLLED_TO_BOTTOM)
delay(SCROLL_EVENT_DELAY)
}
}
}
fun onNextDateSelected() {
launch(Dispatchers.Default) {
dateSelector.onNextDateSelected()
}
}
fun onPreviousDateSelected() {
launch(Dispatchers.Default) {
dateSelector.onPreviousDateSelected()
}
}
fun onRetryClick() {
launch {
statsUseCase.refreshData(true)
}
}
fun onDateChanged(selectedSection: StatsSection) {
launch {
statsUseCase.onDateChanged(selectedSection)
}
}
fun onListSelected() {
dateSelector.updateDateSelector()
}
fun onEmptyInsightsButtonClicked() {
mutableNavigationTarget.value = Event(ViewInsightsManagement)
}
fun onAddNewStatsButtonClicked() {
newsCardHandler?.dismiss()
analyticsTracker.track(Stat.STATS_INSIGHTS_MANAGEMENT_ACCESSED, mapOf("source" to "button"))
mutableNavigationTarget.value = Event(ViewInsightsManagement)
}
fun start() {
if (!isInitialized) {
isInitialized = true
launch {
statsUseCase.loadData()
dateSelector.updateDateSelector()
}
}
dateSelector.updateDateSelector()
}
sealed class UiModel {
data class Success(val data: List<StatsBlock>) : UiModel()
data class Error(val message: Int = R.string.stats_loading_error) : UiModel()
data class Empty(
val title: Int,
val subtitle: Int? = null,
val image: Int? = null,
val showButton: Boolean = false
) : UiModel()
}
fun onTypesChanged() {
launch {
statsUseCase.refreshTypes()
}
}
}
class InsightsListViewModel
@Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
@Named(INSIGHTS_USE_CASE) private val insightsUseCase: BaseListUseCase,
analyticsTracker: AnalyticsTrackerWrapper,
dateSelectorFactory: StatsDateSelector.Factory,
popupMenuHandler: ItemPopupMenuHandler,
newsCardHandler: NewsCardHandler,
actionCardHandler: ActionCardHandler
) : StatsListViewModel(
mainDispatcher,
insightsUseCase,
analyticsTracker,
dateSelectorFactory.build(INSIGHTS),
popupMenuHandler,
newsCardHandler,
actionCardHandler
)
class YearsListViewModel @Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
@Named(YEAR_STATS_USE_CASE) statsUseCase: BaseListUseCase,
analyticsTracker: AnalyticsTrackerWrapper,
dateSelectorFactory: StatsDateSelector.Factory
) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(YEARS))
class MonthsListViewModel @Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
@Named(MONTH_STATS_USE_CASE) statsUseCase: BaseListUseCase,
analyticsTracker: AnalyticsTrackerWrapper,
dateSelectorFactory: StatsDateSelector.Factory
) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(MONTHS))
class WeeksListViewModel @Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
@Named(WEEK_STATS_USE_CASE) statsUseCase: BaseListUseCase,
analyticsTracker: AnalyticsTrackerWrapper,
dateSelectorFactory: StatsDateSelector.Factory
) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(WEEKS))
class DaysListViewModel @Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
@Named(DAY_STATS_USE_CASE) statsUseCase: BaseListUseCase,
analyticsTracker: AnalyticsTrackerWrapper,
dateSelectorFactory: StatsDateSelector.Factory
) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(DAYS))
// Using Weeks granularity on new insight details screens
class InsightsDetailListViewModel @Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
@Named(VIEWS_AND_VISITORS_USE_CASE) statsUseCase: BaseListUseCase,
analyticsTracker: AnalyticsTrackerWrapper,
dateSelectorFactory: StatsDateSelector.Factory
) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(WEEKS))
class TotalLikesDetailListViewModel @Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
@Named(TOTAL_LIKES_DETAIL_USE_CASE) statsUseCase: BaseListUseCase,
analyticsTracker: AnalyticsTrackerWrapper,
dateSelectorFactory: StatsDateSelector.Factory
) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(WEEKS))
class TotalCommentsDetailListViewModel @Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
@Named(TOTAL_COMMENTS_DETAIL_USE_CASE) statsUseCase: BaseListUseCase,
analyticsTracker: AnalyticsTrackerWrapper,
dateSelectorFactory: StatsDateSelector.Factory
) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(WEEKS))
class TotalFollowersDetailListViewModel @Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
@Named(TOTAL_FOLLOWERS_DETAIL_USE_CASE) statsUseCase: BaseListUseCase,
analyticsTracker: AnalyticsTrackerWrapper,
dateSelectorFactory: StatsDateSelector.Factory
) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(WEEKS))
| gpl-2.0 |
ingokegel/intellij-community | platform/lang-impl/testSources/com/intellij/toolWindow/ToolWindowManagerTestCase.kt | 2 | 1904 | // 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.toolWindow
import com.intellij.openapi.application.EDT
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener.ToolWindowManagerEventType
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.ProjectFrameHelper
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.SkipInHeadlessEnvironment
import com.intellij.testFramework.replaceService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
@SkipInHeadlessEnvironment
abstract class ToolWindowManagerTestCase : LightPlatformTestCase() {
@JvmField
protected var manager: ToolWindowManagerImpl? = null
final override fun runInDispatchThread() = false
public override fun setUp() {
super.setUp()
runBlocking {
val project = project
manager = object : ToolWindowManagerImpl(project) {
override fun fireStateChanged(changeType: ToolWindowManagerEventType) {}
}
project.replaceService(ToolWindowManager::class.java, manager!!, testRootDisposable)
val frame = withContext(Dispatchers.EDT) {
val frame = ProjectFrameHelper(IdeFrameImpl(), null)
frame.init()
frame
}
manager!!.doInit(frame, project.messageBus.connect(testRootDisposable), FileEditorManagerEx.getInstanceEx(project).component)
}
}
public override fun tearDown() {
try {
manager!!.projectClosed()
manager = null
}
catch (e: Throwable) {
addSuppressedException(e)
}
finally {
super.tearDown()
}
}
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/functionNestedType2.kt | 9 | 252 | // "Change type of 'myFunction' to '(Int) -> KFunction0<Boolean>'" "true"
// WITH_STDLIB
fun foo() {
var myFunction: (Int, Int) -> Int = <caret>::verifyData
}
fun Int.internalVerifyData() = this > 0
fun verifyData(a: Int) = a::internalVerifyData | apache-2.0 |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/codevision/KotlinCodeVisionLimitedHint.kt | 1 | 6007 | // 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.codeInsight.codevision
import com.intellij.codeInsight.hints.settings.InlayHintsConfigurable
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.CLASS_LOCATION
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.FUNCTION_LOCATION
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.INTERFACE_LOCATION
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.PROPERTY_LOCATION
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.logInheritorsClicked
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.logSettingsClicked
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.logUsagesClicked
import org.jetbrains.kotlin.idea.highlighter.markers.OVERRIDDEN_FUNCTION
import org.jetbrains.kotlin.idea.highlighter.markers.OVERRIDDEN_PROPERTY
import org.jetbrains.kotlin.idea.highlighter.markers.SUBCLASSED_CLASS
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtProperty
import java.awt.event.MouseEvent
abstract class KotlinCodeVisionHint(hintKey: String) {
open val regularText: String = KotlinBundle.message(hintKey)
abstract fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?)
}
abstract class KotlinCodeVisionLimitedHint(num: Int, limitReached: Boolean, regularHintKey: String, tooManyHintKey: String) :
KotlinCodeVisionHint(regularHintKey) {
override val regularText: String =
if (limitReached) KotlinBundle.message(tooManyHintKey, num) else KotlinBundle.message(regularHintKey, num)
}
private const val IMPLEMENTATIONS_KEY = "hints.codevision.implementations.format"
private const val IMPLEMENTATIONS_TO_MANY_KEY = "hints.codevision.implementations.too_many.format"
private const val INHERITORS_KEY = "hints.codevision.inheritors.format"
private const val INHERITORS_TO_MANY_KEY = "hints.codevision.inheritors.to_many.format"
private const val OVERRIDES_KEY = "hints.codevision.overrides.format"
private const val OVERRIDES_TOO_MANY_KEY = "hints.codevision.overrides.to_many.format"
private const val USAGES_KEY = "hints.codevision.usages.format"
private const val USAGES_TOO_MANY_KEY = "hints.codevision.usages.too_many.format"
private const val SETTINGS_FORMAT = "hints.codevision.settings"
class Usages(usagesNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(usagesNum, limitReached, USAGES_KEY, USAGES_TOO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logUsagesClicked(editor.project)
GotoDeclarationAction.startFindUsages(editor, editor.project!!, element)
}
}
class FunctionOverrides(overridesNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(overridesNum, limitReached, OVERRIDES_KEY, OVERRIDES_TOO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logInheritorsClicked(editor.project, FUNCTION_LOCATION)
val navigationHandler = OVERRIDDEN_FUNCTION.navigationHandler
navigationHandler.navigate(event, (element as KtFunction).nameIdentifier)
}
}
class FunctionImplementations(implNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(implNum, limitReached, IMPLEMENTATIONS_KEY, IMPLEMENTATIONS_TO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logInheritorsClicked(editor.project, FUNCTION_LOCATION)
val navigationHandler = OVERRIDDEN_FUNCTION.navigationHandler
navigationHandler.navigate(event, (element as KtFunction).nameIdentifier)
}
}
class PropertyOverrides(overridesNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(overridesNum, limitReached, OVERRIDES_KEY, OVERRIDES_TOO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logInheritorsClicked(editor.project, PROPERTY_LOCATION)
val navigationHandler = OVERRIDDEN_PROPERTY.navigationHandler
navigationHandler.navigate(event, (element as KtProperty).nameIdentifier)
}
}
class ClassInheritors(inheritorsNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(inheritorsNum, limitReached, INHERITORS_KEY, INHERITORS_TO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logInheritorsClicked(editor.project, CLASS_LOCATION)
val navigationHandler = SUBCLASSED_CLASS.navigationHandler
navigationHandler.navigate(event, (element as KtClass).nameIdentifier)
}
}
class InterfaceImplementations(implNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(implNum, limitReached, IMPLEMENTATIONS_KEY, IMPLEMENTATIONS_TO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logInheritorsClicked(editor.project, INTERFACE_LOCATION)
val navigationHandler = SUBCLASSED_CLASS.navigationHandler
navigationHandler.navigate(event, (element as KtClass).nameIdentifier)
}
}
class SettingsHint : KotlinCodeVisionHint(SETTINGS_FORMAT) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
val project = element.project
logSettingsClicked(project)
InlayHintsConfigurable.showSettingsDialogForLanguage(project, element.language)
}
} | apache-2.0 |
benjamin-bader/thrifty | thrifty-schema/src/test/kotlin/com/microsoft/thrifty/schema/FieldTest.kt | 1 | 4730 | /*
* Thrifty
*
* Copyright (c) Microsoft Corporation
*
* 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
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.thrifty.schema
import com.microsoft.thrifty.schema.parser.AnnotationElement
import com.microsoft.thrifty.schema.parser.FieldElement
import com.microsoft.thrifty.schema.parser.ScalarTypeElement
import com.microsoft.thrifty.schema.parser.TypeElement
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class FieldTest {
private var location: Location = Location.get("", "")
private var fieldId: Int = 1
private var fieldName: String = "foo"
private var fieldType: TypeElement = ScalarTypeElement(location, "i32", null)
private var requiredness: Requiredness = Requiredness.DEFAULT
private var annotations: AnnotationElement? = null
private var documentation: String = ""
@Test
fun requiredFields() {
requiredness = Requiredness.REQUIRED
val element = field()
val field = Field(element, emptyMap())
field.required shouldBe true
field.optional shouldBe false
}
@Test
fun optionalFields() {
requiredness = Requiredness.OPTIONAL
val element = field()
val field = Field(element, emptyMap())
field.required shouldBe false
field.optional shouldBe true
}
@Test
fun defaultFields() {
val element = field()
val field = Field(element, emptyMap())
field.required shouldBe false
field.optional shouldBe false
}
@Test
fun unredactedAndUnobfuscatedByDefault() {
val element = field()
val field = Field(element, emptyMap())
field.isRedacted shouldBe false
field.isObfuscated shouldBe false
}
@Test
fun redactedByThriftAnnotation() {
annotations = annotation("thrifty.redacted")
val element = field()
val field = Field(element, emptyMap())
field.isRedacted shouldBe true
}
@Test
fun redactedByShortThriftAnnotation() {
annotations = annotation("redacted")
val element = field()
val field = Field(element, emptyMap())
field.isRedacted shouldBe true
}
@Test
fun redactedByJavadocAnnotation() {
documentation = "/** @redacted */"
val element = field()
val field = Field(element, emptyMap())
field.isRedacted shouldBe true
}
@Test
fun obfuscatedByThriftAnnotation() {
annotations = annotation("thrifty.obfuscated")
val element = field()
val field = Field(element, emptyMap())
field.isObfuscated shouldBe true
}
@Test
fun obfuscatedByShortThriftAnnotation() {
annotations = annotation("obfuscated")
val element = field()
val field = Field(element, emptyMap())
field.isObfuscated shouldBe true
}
@Test
fun obfuscatedByJavadocAnnotation() {
documentation = "/** @obfuscated */"
val element = field()
val field = Field(element, emptyMap())
field.isObfuscated shouldBe true
}
@Test
fun builderCreatesCorrectField() {
val fieldElement = field()
val field = Field(fieldElement, emptyMap())
val annotations = emptyMap<String, String>()
val thriftType = BuiltinType.DOUBLE
val builderField = field.toBuilder()
.annotations(annotations)
.type(thriftType)
.build()
builderField.annotations shouldBe annotations
builderField.type shouldBe thriftType
}
private fun annotation(name: String): AnnotationElement {
return AnnotationElement(Location.get("", ""), mapOf(name to "true"))
}
private fun field(): FieldElement {
return FieldElement(
location = location,
fieldId = fieldId,
type = fieldType,
name = fieldName,
requiredness = requiredness,
documentation = documentation,
constValue = null,
annotations = annotations)
}
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/unifier/equivalence/types/nonNullable.kt | 13 | 114 | val a: <selection>String</selection> = ""
val b: String? = ""
val c: kotlin.String? = ""
val d: kotlin.String = "" | apache-2.0 |
johnjohndoe/Umweltzone | Umweltzone/src/main/java/de/avpptr/umweltzone/extensions/ContextExtensions.kt | 1 | 1035 | @file:JvmName("ContextExtensions")
/*
* Copyright (C) 2020 Tobias Preuss
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.avpptr.umweltzone.extensions
import android.content.Context
import androidx.annotation.ColorRes
import androidx.annotation.NonNull
import androidx.core.content.ContextCompat
fun @receiver:NonNull Context.getColorCompat(@ColorRes id: Int) =
ContextCompat.getColor(this, id)
| gpl-3.0 |
android/nowinandroid | core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/testdoubles/TestNewsResourceDao.kt | 1 | 4765 | /*
* 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.samples.apps.nowinandroid.core.data.testdoubles
import com.google.samples.apps.nowinandroid.core.database.dao.NewsResourceDao
import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceAuthorCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity
import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef
import com.google.samples.apps.nowinandroid.core.database.model.PopulatedNewsResource
import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity
import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Video
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.datetime.Instant
val filteredInterestsIds = setOf("1")
val nonPresentInterestsIds = setOf("2")
/**
* Test double for [NewsResourceDao]
*/
class TestNewsResourceDao : NewsResourceDao {
private var entitiesStateFlow = MutableStateFlow(
listOf(
NewsResourceEntity(
id = "1",
title = "news",
content = "Hilt",
url = "url",
headerImageUrl = "headerImageUrl",
type = Video,
publishDate = Instant.fromEpochMilliseconds(1),
)
)
)
internal var topicCrossReferences: List<NewsResourceTopicCrossRef> = listOf()
internal var authorCrossReferences: List<NewsResourceAuthorCrossRef> = listOf()
override fun getNewsResourcesStream(): Flow<List<PopulatedNewsResource>> =
entitiesStateFlow.map {
it.map(NewsResourceEntity::asPopulatedNewsResource)
}
override fun getNewsResourcesStream(
filterAuthorIds: Set<String>,
filterTopicIds: Set<String>
): Flow<List<PopulatedNewsResource>> =
getNewsResourcesStream()
.map { resources ->
resources.filter { resource ->
resource.topics.any { it.id in filterTopicIds } ||
resource.authors.any { it.id in filterAuthorIds }
}
}
override suspend fun insertOrIgnoreNewsResources(
entities: List<NewsResourceEntity>
): List<Long> {
entitiesStateFlow.value = entities
// Assume no conflicts on insert
return entities.map { it.id.toLong() }
}
override suspend fun updateNewsResources(entities: List<NewsResourceEntity>) {
throw NotImplementedError("Unused in tests")
}
override suspend fun upsertNewsResources(newsResourceEntities: List<NewsResourceEntity>) {
entitiesStateFlow.value = newsResourceEntities
}
override suspend fun insertOrIgnoreTopicCrossRefEntities(
newsResourceTopicCrossReferences: List<NewsResourceTopicCrossRef>
) {
topicCrossReferences = newsResourceTopicCrossReferences
}
override suspend fun insertOrIgnoreAuthorCrossRefEntities(
newsResourceAuthorCrossReferences: List<NewsResourceAuthorCrossRef>
) {
authorCrossReferences = newsResourceAuthorCrossReferences
}
override suspend fun deleteNewsResources(ids: List<String>) {
val idSet = ids.toSet()
entitiesStateFlow.update { entities ->
entities.filterNot { idSet.contains(it.id) }
}
}
}
private fun NewsResourceEntity.asPopulatedNewsResource() = PopulatedNewsResource(
entity = this,
authors = listOf(
AuthorEntity(
id = "id",
name = "name",
imageUrl = "imageUrl",
twitter = "twitter",
mediumPage = "mediumPage",
bio = "bio",
)
),
topics = listOf(
TopicEntity(
id = filteredInterestsIds.random(),
name = "name",
shortDescription = "short description",
longDescription = "long description",
url = "URL",
imageUrl = "image URL",
)
),
)
| apache-2.0 |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/clipper/ClipperTrip.kt | 1 | 4385 | /*
* ClipperTrip.kt
*
* Copyright 2011 "an anonymous contributor"
* Copyright 2011-2014 Eric Butler <[email protected]>
* Copyright 2018 Michael Farrell <[email protected]>
* Copyright 2018 Google
*
* Thanks to:
* An anonymous contributor for reverse engineering Clipper data and providing
* most of the code here.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.clipper
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.time.Timestamp
import au.id.micolous.metrodroid.transit.Station
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.util.NumberUtils
import au.id.micolous.metrodroid.util.ImmutableByteArray
@Parcelize
class ClipperTrip (private val mTimestamp: Long,
private val mExitTimestamp: Long,
private val mFare: Int,
private val mAgency: Int,
private val mFrom: Int,
private val mTo: Int,
private val mRoute: Int,
private val mVehicleNum: Int,
private val mTransportCode: Int): Trip() {
override val startTimestamp: Timestamp?
get() = ClipperTransitData.clipperTimestampToCalendar(mTimestamp)
override val endTimestamp: Timestamp?
get() = ClipperTransitData.clipperTimestampToCalendar(mExitTimestamp)
// Bus doesn't record line
override val routeName: FormattedString?
get() = ClipperData.getRouteName(mAgency, mRoute)
override val humanReadableRouteID: String?
get() = if (mAgency == ClipperData.AGENCY_GG_FERRY) {
NumberUtils.intToHex(mRoute)
} else null
override val vehicleID: String?
get() = when (mVehicleNum) {
0, 0xffff -> null
in 1..9999 -> mVehicleNum.toString()
// For LRV4 Muni vehicles with newer Clipper readers, it stores a 4-digit vehicle number followed
// by a letter. For example 0d20461 is vehicle number 2046A, 0d20462 is 2046B, and so on.
else -> (mVehicleNum / 10).toString() + ((mVehicleNum % 10) + 9).toString(16).toUpperCase()
}
override val fare: TransitCurrency?
get() = TransitCurrency.USD(mFare)
override val startStation: Station?
get() = ClipperData.getStation(mAgency, mFrom, false)
override val endStation: Station?
get() = ClipperData.getStation(mAgency, mTo, true)
override val mode: Trip.Mode
get() = when (mTransportCode) {
0x62 -> {
when (mAgency) {
ClipperData.AGENCY_BAY_FERRY, ClipperData.AGENCY_GG_FERRY -> Trip.Mode.FERRY
ClipperData.AGENCY_CALTRAIN, ClipperData.AGENCY_SMART -> Trip.Mode.TRAIN
else -> Trip.Mode.TRAM
}
}
0x6f -> Trip.Mode.METRO
0x61, 0x75 -> Trip.Mode.BUS
0x73 -> Trip.Mode.FERRY
else -> Trip.Mode.OTHER
}
internal constructor(useData: ImmutableByteArray): this(
mAgency = useData.byteArrayToInt(0x2, 2),
mFare = useData.byteArrayToInt(0x6, 2),
mVehicleNum = useData.byteArrayToInt(0xa, 2),
mTimestamp = useData.byteArrayToLong(0xc, 4),
mExitTimestamp = useData.byteArrayToLong(0x10, 4),
mFrom = useData.byteArrayToInt(0x14, 2),
mTo = useData.byteArrayToInt(0x16, 2),
mRoute = useData.byteArrayToInt(0x1c, 2),
mTransportCode = useData.byteArrayToInt(0x1e, 2)
)
override fun getAgencyName(isShort: Boolean) = ClipperData.getAgencyName(mAgency, isShort)
}
| gpl-3.0 |
googlecodelabs/cronet-basics | solution/src/main/java/com/google/codelabs/cronet/ui/theme/Shape.kt | 2 | 913 | /*
* 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.codelabs.cronet.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
) | apache-2.0 |
AberrantFox/hotbot | src/main/kotlin/me/aberrantfox/hotbot/services/APIRateLimiter.kt | 1 | 1146 | package me.aberrantfox.hotbot.services
import com.google.gson.Gson
import org.joda.time.DateTime
import java.io.File
import kotlin.concurrent.timer
private data class Datum(var current: Int)
data class APIRateLimiter(private val limit: Int, private var current: Int, val name: String) {
private val gson = Gson()
private val file = File(configPath("ratelimit/$name.json"))
init {
val parent = file.parentFile
if( !(parent.exists()) ) {
parent.mkdirs()
}
if(file.exists()) {
val datum = gson.fromJson(file.readText(), Datum::class.java)
current = datum.current
}
timer(name, false, 0.toLong(), 60 * 1000 * 60 * 24) { checkReset() }
}
fun increment() {
current++
val text = gson.toJson(Datum(current))
file.writeText(text)
}
fun left() = limit - current
fun canCall() = limit != current && limit > current
private fun checkReset() =
if(DateTime.now().toLocalDate().dayOfMonth == 25) {
file.writeText(gson.toJson(Datum(0)))
current = 0
} else { Unit }
}
| mit |
Turbo87/intellij-emberjs | src/main/kotlin/com/emberjs/resolver/EmberName.kt | 1 | 8504 | package com.emberjs.resolver
import com.emberjs.EmberFileType
import com.emberjs.utils.parentEmberModule
import com.emberjs.utils.parents
import com.intellij.openapi.vfs.VfsUtilCore.isAncestor
import com.intellij.openapi.vfs.VirtualFile
data class EmberName(val type: String, val name: String) {
val fullName by lazy { "$type:$name" }
val displayName by lazy {
if (isComponentStyles) {
"${name.removePrefix("components/").replace('/', '.')} component-styles"
} else if (isComponentTemplate) {
"${name.removePrefix("components/").replace('/', '.')} component-template"
} else {
"${name.replace('/', '.')} $type"
}
}
// adapted from https://github.com/ember-codemods/ember-angle-brackets-codemod/blob/v3.0.1/transforms/angle-brackets/transform.js#L36-L62
val angleBracketsName by lazy {
assert(type == "component" || isComponentTemplate)
val baseName = if (isComponentTemplate) name.removePrefix("components/") else name
baseName.replace(SIMPLE_DASHERIZE_REGEXP) {
assert(it.range.first - it.range.last == 0)
if (it.value == "/") return@replace "::"
if (it.range.first == 0 || !ALPHA.matches(baseName.subSequence(it.range.start - 1, it.range.start))) {
return@replace it.value.toUpperCase()
}
if (it.value == "-") "" else it.value.toLowerCase()
}
}
val isTest: Boolean = type.endsWith("-test")
val isComponentStyles = type == "styles" && name.startsWith("components/")
val isComponentTemplate = type == "template" && name.startsWith("components/")
companion object {
private val SIMPLE_DASHERIZE_REGEXP = Regex("[a-z]|/|-")
private val ALPHA = Regex("[A-Za-z0-9]")
fun from(fullName: String): EmberName? {
val parts = fullName.split(":")
return when {
parts.count() == 2 -> EmberName(parts[0], parts[1])
else -> null
}
}
fun from(file: VirtualFile) = file.parentEmberModule?.let { from(it, file) }
fun from(root: VirtualFile, file: VirtualFile): EmberName? {
val appFolder = root.findChild("app")
val addonFolder = root.findChild("addon")
val testsFolder = root.findChild("tests")
val unitTestsFolder = testsFolder?.findChild("unit")
val integrationTestsFolder = testsFolder?.findChild("integration")
val acceptanceTestsFolder = testsFolder?.findChild("acceptance")
val dummyAppFolder = testsFolder?.findFileByRelativePath("dummy/app")
return fromPod(appFolder, file) ?: fromPod(addonFolder, file) ?: fromPodTest(unitTestsFolder, file)
?: fromPodTest(integrationTestsFolder, file) ?: fromClassic(appFolder, file)
?: fromClassic(addonFolder, file) ?: fromClassic(dummyAppFolder, file)
?: fromClassicTest(unitTestsFolder, file) ?: fromClassicTest(integrationTestsFolder, file)
?: fromAcceptanceTest(acceptanceTestsFolder, file)
}
fun fromClassic(appFolder: VirtualFile?, file: VirtualFile): EmberName? {
appFolder ?: return null
val typeFolder = file.parents.find { it.parent == appFolder } ?: return null
if (typeFolder.name == "styles") {
val path = file.parents
.takeWhile { it != typeFolder }
.map { it.name }
.reversed()
.joinToString("/")
val name = "$path/${file.nameWithoutExtension}".removePrefix("/")
return EmberName("styles", name.removeSuffix(".module"))
}
return EmberFileType.FOLDER_NAMES[typeFolder.name]?.let { type ->
val path = file.parents
.takeWhile { it != typeFolder }
.map { it.name }
.reversed()
.joinToString("/")
val name = "$path/${file.nameWithoutExtension}".removePrefix("/")
// detect flat and nested component layout (where hbs file lies in the components/ folder)
if (type == EmberFileType.COMPONENT) {
if (file.extension == "hbs") {
return EmberName(EmberFileType.TEMPLATE.name.toLowerCase(), "components/$name")
}
if (file.extension == "css" || file.extension == "scss") {
return EmberName("styles", "components/${name.removeSuffix(".module")}")
}
}
EmberName(type.name.toLowerCase(), name)
}
}
fun fromClassicTest(testsFolder: VirtualFile?, file: VirtualFile): EmberName? {
testsFolder ?: return null
val typeFolder = file.parents.find { it.parent == testsFolder } ?: return null
val testSuffix = when (testsFolder.name) {
"unit" -> "-test"
else -> "-${testsFolder.name}-test"
}
return EmberFileType.FOLDER_NAMES[typeFolder.name]?.let { type ->
val path = file.parents
.takeWhile { it != typeFolder }
.map { it.name }
.reversed()
.joinToString("/")
val name = "$path/${file.nameWithoutExtension.removeSuffix("-test")}".removePrefix("/")
EmberName("${type.name.toLowerCase()}$testSuffix", name)
}
}
fun fromAcceptanceTest(testsFolder: VirtualFile?, file: VirtualFile): EmberName? {
testsFolder ?: return null
if (!isAncestor(testsFolder, file, true))
return null
val path = file.parents
.takeWhile { it != testsFolder }
.map { it.name }
.reversed()
.joinToString("/")
val name = "$path/${file.nameWithoutExtension.removeSuffix("-test")}".removePrefix("/")
return EmberName("acceptance-test", name)
}
fun fromPod(appFolder: VirtualFile?, file: VirtualFile): EmberName? {
appFolder ?: return null
if (!isAncestor(appFolder, file, true))
return null
if (file.nameWithoutExtension.removeSuffix(".module") == "styles") {
return file.parents.takeWhile { it != appFolder }
.map { it.name }
.reversed()
.joinToString("/")
.let { EmberName("styles", it) }
}
return EmberFileType.FILE_NAMES[file.name]?.let { type ->
file.parents.takeWhile { it != appFolder }
.map { it.name }
.reversed()
.joinToString("/")
.let {
when (type) {
EmberFileType.COMPONENT -> it.removePrefix("components/")
else -> it
}
}
.let { EmberName(type.name.toLowerCase(), it) }
}
}
fun fromPodTest(testsFolder: VirtualFile?, file: VirtualFile): EmberName? {
testsFolder ?: return null
if (!isAncestor(testsFolder, file, true))
return null
val fileName = "${file.nameWithoutExtension.removeSuffix("-test")}.${file.extension}"
val testSuffix = when (testsFolder.name) {
"unit" -> "-test"
else -> "-${testsFolder.name}-test"
}
return EmberFileType.FILE_NAMES[fileName]?.let { type ->
val name = file.parents
.takeWhile { it != testsFolder }
.map { it.name }
.reversed()
.joinToString("/")
.let {
when (type) {
EmberFileType.COMPONENT -> it.removePrefix("components/")
else -> it
}
}
EmberName("${type.name.toLowerCase()}$testSuffix", name)
}
}
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/notification/notificationUtils.kt | 2 | 2252 | // 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.notification
import com.intellij.notification.Notification
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.NonBlockingReadActionImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.migration.KotlinMigrationBundle
fun catchNotificationText(project: Project, action: () -> Unit): String? {
val notifications = catchNotifications(project, action).ifEmpty { return null }
return notifications.single().content
}
fun catchNotifications(project: Project, action: () -> Unit): List<Notification> {
val myDisposable = Disposer.newDisposable()
try {
val notifications = mutableListOf<Notification>()
val connection = project.messageBus.connect(myDisposable)
connection.subscribe(Notifications.TOPIC, object : Notifications {
override fun notify(notification: Notification) {
notifications += notification
}
})
action()
connection.deliverImmediately()
ApplicationManager.getApplication().invokeAndWait { NonBlockingReadActionImpl.waitForAsyncTaskCompletion() }
return notifications
} finally {
Disposer.dispose(myDisposable)
}
}
val Notification.asText: String get() = "Title: '$title'\nContent: '$content'"
fun List<Notification>.asText(filterNotificationAboutNewKotlinVersion: Boolean = true): String =
sortedBy { it.content }
.filter {
!filterNotificationAboutNewKotlinVersion ||
!it.content.contains(
KotlinMigrationBundle.message(
"kotlin.external.compiler.updates.notification.content.0",
KotlinPluginLayout.standaloneCompilerVersion.kotlinVersion
)
)
}
.joinToString(separator = "\n-----\n", transform = Notification::asText)
| apache-2.0 |
Firenox89/Shinobooru | app/src/main/java/com/github/firenox89/shinobooru/repo/LocalPostLoader.kt | 1 | 2935 | package com.github.firenox89.shinobooru.repo
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Point
import android.view.WindowManager
import com.github.firenox89.shinobooru.repo.model.DownloadedPost
import com.github.firenox89.shinobooru.repo.model.Post
import com.github.firenox89.shinobooru.repo.model.Tag
import com.github.firenox89.shinobooru.utility.Constants
import com.github.firenox89.shinobooru.utility.UI.loadSubsampledImage
import com.github.kittinunf.result.Result
import kotlinx.coroutines.channels.Channel
import timber.log.Timber
/**
* Sub-classes the [PostLoader] to use the downloaded post images as a source for posts.
* Does not refresh the post list when new images are downloaded.
*/
class LocalPostLoader(private val appContext: Context, private val fileManager: FileManager) : PostLoader {
override val board: String
get() = Constants.FILE_LOADER_NAME
override val tags: String
get() = ""
private val changeChannel = Channel<Pair<Int, Int>>()
private val newestDownloadedPostComparator = Comparator<DownloadedPost> { post1, post2 ->
val date1 = post1.file.lastModified()
val date2 = post2.file.lastModified()
var result = 0
if (date1 < date2)
result = 1
if (date1 > date2)
result = -1
result
}
private var posts = fileManager.getAllDownloadedPosts().sortedWith(newestDownloadedPostComparator)
override suspend fun loadPreview(post: Post): Result<Bitmap, Exception> =
loadSubsampledImage((post as DownloadedPost).file, 250, 400)
override suspend fun loadSample(post: Post): Result<Bitmap, Exception> {
val wm = appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val size = Point()
display.getSize(size)
//sample huge images=
return loadSubsampledImage((post as DownloadedPost).file, size.x, size.y)
}
override suspend fun getRangeChangeEventStream(): Channel<Pair<Int, Int>> =
changeChannel.apply{ offer(Pair(0, posts.size))}
/**
* Return a post from the postlist for the given number
*/
override fun getPostAt(index: Int): DownloadedPost {
return posts[index]
}
/** Does nothing */
override suspend fun requestNextPosts() {
//nothing to request in file mode
}
/**
* Returns the size of the postlist.
*/
override fun getCount(): Int {
return posts.size
}
/**
* Return the index for a post in the postlist.
*/
override fun getIndexOf(post: Post): Int {
return posts.indexOf(post)
}
override suspend fun onRefresh() {
Timber.d("onRefresh")
posts = fileManager.getAllDownloadedPosts(true).sortedWith(newestDownloadedPostComparator)
changeChannel.offer(Pair(0, posts.size))
}
} | mit |
GunoH/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigShadowedOptionInspection.kt | 7 | 3296 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.editorconfig.language.codeinsight.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import org.editorconfig.language.codeinsight.quickfixes.EditorConfigRemoveOptionQuickFix
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.EditorConfigOption
import org.editorconfig.language.psi.EditorConfigVisitor
import org.editorconfig.language.schema.descriptors.EditorConfigDescriptor
import org.editorconfig.language.schema.descriptors.impl.EditorConfigQualifiedKeyDescriptor
import org.editorconfig.language.util.EditorConfigDescriptorUtil
import org.editorconfig.language.util.EditorConfigPsiTreeUtil.findShadowingSections
class EditorConfigShadowedOptionInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() {
override fun visitOption(option: EditorConfigOption) {
findShadowingSections(option.section)
.asSequence()
.flatMap { it.optionList.asSequence() }
.dropWhile { it !== option }
.drop(1)
.firstOrNull { equalOptions(option, it) }
?.apply {
val message = EditorConfigBundle["inspection.option.shadowed.message"]
holder.registerProblem(option, message, ProblemHighlightType.LIKE_UNUSED_SYMBOL, EditorConfigRemoveOptionQuickFix())
}
}
}
companion object {
fun equalOptions(first: EditorConfigOption, second: EditorConfigOption): Boolean {
val firstDescriptor = first.getDescriptor(false) ?: return false
if (first.keyParts.size != second.keyParts.size) return false
val secondDescriptor = second.getDescriptor(false)
if (firstDescriptor != secondDescriptor) return false
if (EditorConfigDescriptorUtil.isConstant(firstDescriptor.key)) return true
if (!equalToIgnoreCase(findDeclarations(first), findDeclarations(second))) return false
return equalToIgnoreCase(findConstants(first), findConstants(second))
}
private fun equalToIgnoreCase(first: List<String>, second: List<String>): Boolean {
if (first.size != second.size) return false
return first.zip(second).all(::equalToIgnoreCase)
}
private fun equalToIgnoreCase(pair: Pair<String, String>) =
pair.first.equals(pair.second, true)
private fun findDeclarations(option: EditorConfigOption) = findMatching(option, EditorConfigDescriptorUtil::isVariable)
private fun findConstants(option: EditorConfigOption) = findMatching(option, EditorConfigDescriptorUtil::isConstant)
private fun findMatching(option: EditorConfigOption, filter: (EditorConfigDescriptor) -> Boolean): List<String> {
val descriptor = option.getDescriptor(false) ?: return emptyList()
val keyDescriptor = descriptor.key as? EditorConfigQualifiedKeyDescriptor ?: return emptyList()
if (option.keyParts.size != keyDescriptor.children.size) throw IllegalStateException()
return option.keyParts.filterIndexed { index, _ -> filter(keyDescriptor.children[index]) }
}
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/base/fir/analysis-api-providers/test/org/jetbrains/kotlin/idea/fir/analysis/providers/testUtils.kt | 4 | 549 | // 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.fir.analysis.providers
import com.intellij.openapi.components.service
import com.intellij.openapi.module.Module
import org.jetbrains.kotlin.idea.base.fir.analysisApiProviders.FirIdeModificationTrackerService
internal fun Module.incModificationTracker() {
project.service<FirIdeModificationTrackerService>().increaseModificationCountForModule(this)
} | apache-2.0 |
cleverchap/AutoAnylysis | src/com/cc/patten/PattenManager.kt | 1 | 1080 | package com.cc.patten
/**
* Created by clevercong on 2017/10/15.
* 用于正则表达式匹配的字符串,从这里获取。
*/
fun getLogTagPattenString() : String = "startElement|endElement"
// 当前调试先用这个也OK,但是下面的更严谨一些,且符合新版本Log文件名格式。
fun getFileNamePattenString() : String = "rillogcat-log.[0-9]{1}"
fun getFileNamePattenStringV2() : String = "rillogcat-log.[0-9]{8}-[0-9]{6}"
const val VERSION_INCLUDE_DATE = 2
const val VERSION_NOT_INCLUDE_DATE = 1
const val VERSION_UNKNOWN = 0
/**
* fileName: Log文件名
* return 2: version 2 含有日期(新版)
* return 1: version 1 不含有日期
* return 0: version unknown 暂时没有用
*/
fun getFileNameVersion(fileName: String) : Int {
val pattenV1 = getFileNamePattenString().toRegex()
val pattenV2 = getFileNamePattenStringV2().toRegex()
return when {
pattenV2.containsMatchIn(fileName) -> VERSION_INCLUDE_DATE
pattenV1.containsMatchIn(fileName) -> VERSION_NOT_INCLUDE_DATE
else -> VERSION_UNKNOWN
}
} | apache-2.0 |
NiciDieNase/chaosflix | common/src/test/java/de/nicidienase/chaosflix/common/ChaosflixUtilTest.kt | 1 | 1622 | package de.nicidienase.chaosflix.common
import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Event
import de.nicidienase.chaosflix.common.mediadata.network.ApiFactory
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class ChaosflixUtilTest {
val api = ApiFactory.getInstance("https://api.media.ccc.de", null).recordingApi
@Test
fun testGPN19() = genericTest("gpn19", false)
@Test
fun testGPN18() = genericTest("gpn18", false)
@Test
fun testGPN17() = genericTest("gpn17", false)
@Test
fun testGPN16() = genericTest("gpn16", false)
@Test
fun testGPN15() = genericTest("gpn15", false)
@Test
fun testGPN14() = genericTest("gpn14", false)
@Test
fun test36c3() = genericTest("36c3", true)
@Test
fun chaosradio() = genericTest("chaosradio", false)
@Test
fun fiffkon18() = genericTest("fiffkon18", false)
@Test
fun denog7() = genericTest("denog7", false)
@Test
fun denog8() = genericTest("denog8", false)
@Test
fun denog10() = genericTest("denog10", false)
@Test
fun denog11() = genericTest("denog11", false)
@Test
fun openChaos() = genericTest("openchaos", false)
fun genericTest(acronym: String, expResult: Boolean) = runBlocking {
val conference = api.getConferenceByName(acronym).body()
val map = conference?.events?.map { Event(it) }
if (map != null) {
assertTrue(expResult == ChaosflixUtil.areTagsUsefull(map, conference.acronym))
}
}
}
| mit |
jk1/intellij-community | plugins/stats-collector/src/com/intellij/completion/FeatureManagerImpl.kt | 2 | 2240 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.completion
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ApplicationComponent
import com.jetbrains.completion.feature.*
import com.jetbrains.completion.feature.impl.CompletionFactors
import com.jetbrains.completion.feature.impl.FeatureInterpreterImpl
import com.jetbrains.completion.feature.impl.FeatureManagerFactory
import com.jetbrains.completion.feature.impl.FeatureReader
/**
* @author Vitaliy.Bibaev
*/
class FeatureManagerImpl : FeatureManager, ApplicationComponent {
companion object {
fun getInstance(): FeatureManager = ApplicationManager.getApplication().getComponent(FeatureManager::class.java)
}
private lateinit var manager: FeatureManager
override val binaryFactors: List<BinaryFeature> get() = manager.binaryFactors
override val doubleFactors: List<DoubleFeature> get() = manager.doubleFactors
override val categoricalFactors: List<CategoricalFeature> get() = manager.categoricalFactors
override val ignoredFactors: Set<String> get() = manager.ignoredFactors
override val completionFactors: CompletionFactors get() = manager.completionFactors
override val featureOrder: Map<String, Int> get() = manager.featureOrder
override fun createTransformer(): Transformer {
return manager.createTransformer()
}
override fun isUserFeature(name: String): Boolean = false
override fun initComponent() {
manager = FeatureManagerFactory().createFeatureManager(FeatureReader, FeatureInterpreterImpl())
}
override fun allFeatures(): List<Feature> = manager.allFeatures()
} | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.